Exemplo n.º 1
0
bool DiskImagePro::seekToSector(quint16 sector)
{
    if (sector < 1 || sector > m_geometry.sectorCount()) {
        qCritical() << "!e" << tr("[%1] Cannot seek to sector %2: %3")
                       .arg(deviceName())
                       .arg(sector)
           .arg(tr("Sector number is out of bounds."));
    }
    qint64 pos = 16 + (sector - 1) * (m_geometry.bytesPerSector()+12);
    if (m_geometry.bytesPerSector() == 256) {
        if (sector <= 3) {
            pos = (sector - 1) * (128+12);
        } else {
            pos -= (384+36);
        }
    }
    if (!sourceFile->seek(pos)) {
        qCritical() << "!e" << tr("[%1] Cannot seek to sector %2: %3")
                       .arg(deviceName())
                       .arg(sector)
                       .arg(sourceFile->error());
        return false;
    }
    return true;
}
Exemplo n.º 2
0
void SioWorker::run()
{
    connect(mPort, SIGNAL(statusChanged(QString)), this, SIGNAL(statusChanged(QString)));

    /* Open serial port */
    if (!mPort->open()) {
        return;
    }

    /* Process SIO commands until we're explicitly stopped */
    while (!mustTerminate) {

//        qDebug() << "!d" << tr("DBG -- SIOWORKER...");

        QByteArray cmd = mPort->readCommandFrame();
        if (mustTerminate) {
            break;
        }
        if (cmd.isEmpty()) {
            qCritical() << "!e" << tr("Cannot read command frame.");
            break;
        }
        /* Decode the command */
        quint8 no = (quint8)cmd[0];
        quint8 command = (quint8)cmd[1];
        quint16 aux = ((quint8)cmd[2]) + ((quint8)cmd[3] * 256);

        /* Redirect the command to the appropriate device */
        deviceMutex->lock();
        if (devices[no]) {
            if (devices[no]->tryLock()) {
                devices[no]->handleCommand(command, aux);
                devices[no]->unlock();
            } else {
                qWarning() << "!w" << tr("[%1] command: $%2, aux: $%3 ignored because the image explorer is open.")
                               .arg(deviceName(no))
                               .arg(command, 2, 16, QChar('0'))
                               .arg(aux, 4, 16, QChar('0'));
            }
        } else {
            qDebug() << "!u" << tr("[%1] command: $%2, aux: $%3 ignored.")
                           .arg(deviceName(no))
                           .arg(command, 2, 16, QChar('0'))
                           .arg(aux, 4, 16, QChar('0'));
        }
        deviceMutex->unlock();
        cmd.clear();
    }
    mPort->close();
}
// create a topic for the requested sampling period if it doesn't exist yet,
// enable the sensor with the new period if needed and
// store publisher and it's details into the mPublishList vector
bool RosSensor::sensorEnableCallback(webots_ros::sensor_enable::Request &req, webots_ros::sensor_enable::Response &res) {
  if (req.period == 0) {
    res.success = 0;
    for (unsigned int i = 0; i < mPublishList.size(); ++i)
      mPublishList[i].mPublisher.shutdown();
    mPublishList.clear();
    rosDisable();
  } else if (req.period % (mRos->stepSize()) == 0) {
    int copy = 0;
    int minPeriod = req.period;
    for (unsigned int i = 0; i < mPublishList.size(); ++i) {
      if (mPublishList[i].mSamplingPeriod < minPeriod)
        minPeriod = mPublishList[i].mSamplingPeriod;
      if (mPublishList[i].mSamplingPeriod == req.period)
        copy++;
    }
    if (copy == 0) {
      mPublishList.push_back(publisherDetails());
      mPublishList.back().mSamplingPeriod = req.period;
      mPublishList.back().mNewPublisher = true;
      mPublishList.back().mPublisher = createPublisher();
      if (minPeriod == req.period)
        rosEnable(req.period);
      res.success = 1;
    }
    res.success = 1;
  } else {
    ROS_ERROR("Wrong sampling period: %d for device: %s.", req.period,deviceName().c_str());
    res.success = -1;
  }
  return true;
}
Exemplo n.º 4
0
bool KMobileDevice::configDialog( QWidget *parent )
{
  KMessageBox::information( parent,
		i18n("This device does not need any configuration."),
		deviceName() );
  return true;
}
void QGstreamerVideoInputDeviceControl::setSelectedDevice(int index)
{
    if (index != m_selectedDevice) {
        m_selectedDevice = index;
        emit selectedDeviceChanged(index);
        emit selectedDeviceChanged(deviceName(index));
    }
}
Exemplo n.º 6
0
int AudioStream::deviceIndex(QString const& name)
{
    int count = deviceCount();
    for (int i = 0; i < count; ++i)
        if (deviceName(i) == name)
            return i;
    return -1;
}
void GPhotoVideoInputDeviceControl::setSelectedDevice(int index)
{
    if (index != m_selectedDevice) {
        m_selectedDevice = index;
        m_session->setCamera(index);
        emit selectedDeviceChanged(index);
        emit selectedDeviceChanged(deviceName(index));
    }
}
Exemplo n.º 8
0
/*!
    Returns true if this QAudioDeviceInfo class represents the
    same audio device as \a other.
*/
bool QAudioDeviceInfo::operator ==(const QAudioDeviceInfo &other) const
{
    if (d == other.d)
        return true;
    if (d->realm == other.d->realm
            && d->mode == other.d->mode
            && d->handle == other.d->handle
            && deviceName() == other.deviceName())
        return true;
    return false;
}
static status_t s_open(alsa_handle_t *handle, uint32_t devices, int mode)
{
    // Close off previously opened device.
    // It would be nice to determine if the underlying device actually
    // changes, but we might be recovering from an error or manipulating
    // mixer settings (see asound.conf).
    //
    s_close(handle);

    LOGD("open called for devices %08x in mode %d...", devices, mode);

    const char *stream = streamName(handle);
    const char *devName = deviceName(handle, devices, mode);

    int err;

    for (;;) {
        // The PCM stream is opened in blocking mode, per ALSA defaults.  The
        // AudioFlinger seems to assume blocking mode too, so asynchronous mode
        // should not be used.
        err = snd_pcm_open(&handle->handle, devName, direction(handle),
                SND_PCM_ASYNC);
        if (err == 0) break;

        // See if there is a less specific name we can try.
        // Note: We are changing the contents of a const char * here.
        char *tail = strrchr(devName, '_');
        if (!tail) break;
        *tail = 0;
    }

    if (err < 0) {
        // None of the Android defined audio devices exist. Open a generic one.
        devName = "default";
        err = snd_pcm_open(&handle->handle, devName, direction(handle), 0);
    }

    if (err < 0) {
        LOGE("Failed to Initialize any ALSA %s device: %s",
                stream, strerror(err));
        return NO_INIT;
    }

    err = setHardwareParams(handle);

    if (err == NO_ERROR) err = setSoftwareParams(handle);

    LOGI("Initialized ALSA %s device %s", stream, devName);

    handle->curDev = devices;
    handle->curMode = mode;

    return err;
}
Exemplo n.º 10
0
void AutoBoot::passToOldHandler(quint8 command, quint16 aux)
{
    if (oldDevice) {
        oldDevice->handleCommand(command, aux);
    } else {
        sio->port()->writeCommandNak();
        qWarning() << "!w" << tr("[%1] command: $%2, aux: $%3 NAKed.")
                       .arg(deviceName())
                       .arg(command, 2, 16, QChar('0'))
                       .arg(aux, 4, 16, QChar('0'));
    }
}
Exemplo n.º 11
0
int KMobileGnokii::readNote( int index, QString &note )
{
  // index is zero-based, and we only have one simulated note
  if (index<0 || index>=numNotes())
    return KIO::ERR_DOES_NOT_EXIST;

  note = QString("NOTE #%1\n"
		 "--------\n"
	"This is a sample note #%2\n\n"
	"DeviceClassName: %3\n"
	"Device Driver  : %4\n"
	"Device Revision: %5\n")
	.arg(index).arg(index)
	.arg(deviceClassName()).arg(deviceName()).arg(revision()); 
  return 0;
}
Exemplo n.º 12
0
bool DiskImagePro::readSector(quint16 sector, QByteArray &data)
{
    if (!seekToSector(sector)) {
        return false;
    }
    
    QByteArray header;
    header = sourceFile->read(12);
    
    if ((quint8)header[5] != 0)
    {
        int dupnum = count[sector];

        qDebug() << "!e" << tr("Duplicate sector: %1 dupnum: %2").arg(sector).arg(dupnum);

        count[sector] = (count[sector]+1) % ((quint8)header[5]+1);
        if (dupnum != 0)  {
            sector = m_geometry.sectorCount() + (quint8)header[6+dupnum];
            /* can dupnum be 5? */
            if (dupnum > 4 || sector <= 0 || sector > ((sourceFile->size()-16)/(128+12)))
            {
              qCritical() << "!e" << tr("Error in .pro image: sector: %1 dupnum: %2").arg(sector).arg(dupnum);
              return false;
            }
            seekToSector(sector);
            /* read sector header */
            header = sourceFile->read(12);
        }
    }
    
    wd1772status = header[1];
    if (wd1772status != 0xff)
    {
        qDebug() << "!e" << tr("Bad sector");
        return false;
    }
    
    data = sourceFile->read(m_geometry.bytesPerSector(sector));
    if (data.size() != m_geometry.bytesPerSector(sector)) {
        qCritical() << "!e" << tr("[%1] Cannot read from sector %2: %3.")
                       .arg(deviceName())
                       .arg(sector)
                       .arg(sourceFile->errorString());
        return false;
    }
    return true;
}
Exemplo n.º 13
0
QString tNDP2kInstrument::GetVirtualDeviceName( unsigned int )
{
    QString deviceName( "" );

    switch( tProductSettings::Instance().GetProductId() )
    {
    case tProductSettings::HOBART:
        deviceName = "Graphic Display";
        break;

    case tProductSettings::RepowerSimrad:
    case tProductSettings::RepowerSuzuki:
    case tProductSettings::Trafalgar:
        deviceName = "Color Gauge";
        break;

    default:
        Assert( 0 );
    }

    return deviceName;
}
Exemplo n.º 14
0
// -----------------------------------------
//    entry point
// -----------------------------------------
int main(int argc, char** argv) 
{
	// default parameters
	const char *dev_name = "/dev/video0";	
	int format = V4L2_PIX_FMT_H264;
	int width = 640;
	int height = 480;
	int queueSize = 10;
	int fps = 25;
	unsigned short rtspPort = 8554;
	unsigned short rtspOverHTTPPort = 0;
	bool multicast = false;
	int verbose = 0;
	std::string outputFile;
	bool useMmap = true;
	std::string url = "unicast";
	std::string murl = "multicast";
	bool useThread = true;
	std::string maddr;
	bool repeatConfig = true;
	int timeout = 65;

	// decode parameters
	int c = 0;     
	while ((c = getopt (argc, argv, "v::Q:O:" "I:P:T:m:u:M:ct:" "rsfF:W:H:" "h")) != -1)
	{
		switch (c)
		{
			case 'v':	verbose = 1; if (optarg && *optarg=='v') verbose++;  break;
			case 'Q':	queueSize = atoi(optarg); break;
			case 'O':	outputFile = optarg; break;
			// RTSP/RTP
			case 'I':       ReceivingInterfaceAddr = inet_addr(optarg); break;
			case 'P':	rtspPort = atoi(optarg); break;
			case 'T':	rtspOverHTTPPort = atoi(optarg); break;
			case 'u':	url = optarg; break;
			case 'm':	multicast = true; murl = optarg; break;
			case 'M':	multicast = true; maddr = optarg; break;
			case 'c':	repeatConfig = false; break;
			case 't':	timeout = atoi(optarg); break;
			// V4L2
			case 'r':	useMmap =  false; break;
			case 's':	useThread =  false; break;
			case 'f':	format = 0; break;
			case 'F':	fps = atoi(optarg); break;
			case 'W':	width = atoi(optarg); break;
			case 'H':	height = atoi(optarg); break;

			case 'h':
			default:
			{
				std::cout << argv[0] << " [-v[v]] [-Q queueSize] [-O file]"                                        << std::endl;
				std::cout << "\t          [-I interface] [-P RTSP port] [-T RTSP/HTTP port] [-m multicast url] [-u unicast url] [-M multicast addr] [-c] [-t timeout]" << std::endl;
				std::cout << "\t          [-r] [-s] [-W width] [-H height] [-F fps] [device] [device]"           << std::endl;
				std::cout << "\t -v       : verbose"                                                               << std::endl;
				std::cout << "\t -vv      : very verbose"                                                          << std::endl;
				std::cout << "\t -Q length: Number of frame queue  (default "<< queueSize << ")"                   << std::endl;
				std::cout << "\t -O output: Copy captured frame to a file or a V4L2 device"                        << std::endl;
				std::cout << "\t RTSP options :"                                                                   << std::endl;
				std::cout << "\t -I addr  : RTSP interface (default autodetect)"                                   << std::endl;
				std::cout << "\t -P port  : RTSP port (default "<< rtspPort << ")"                                 << std::endl;
				std::cout << "\t -T port  : RTSP over HTTP port (default "<< rtspOverHTTPPort << ")"               << std::endl;
				std::cout << "\t -u url   : unicast url (default " << url << ")"                                   << std::endl;
				std::cout << "\t -m url   : multicast url (default " << murl << ")"                                << std::endl;
				std::cout << "\t -M addr  : multicast group:port (default is random_address:20000)"                << std::endl;
				std::cout << "\t -c       : don't repeat config (default repeat config before IDR frame)"          << std::endl;
				std::cout << "\t -t secs  : RTCP expiration timeout (default " << timeout << ")"                   << std::endl;
				std::cout << "\t V4L2 options :"                                                                   << std::endl;
				std::cout << "\t -r       : V4L2 capture using read interface (default use memory mapped buffers)" << std::endl;
				std::cout << "\t -s       : V4L2 capture using live555 mainloop (default use a reader thread)"     << std::endl;
				std::cout << "\t -f       : V4L2 capture using current format (-W,-H,-F are ignore)"               << std::endl;
				std::cout << "\t -W width : V4L2 capture width (default "<< width << ")"                           << std::endl;
				std::cout << "\t -H height: V4L2 capture height (default "<< height << ")"                         << std::endl;
				std::cout << "\t -F fps   : V4L2 capture framerate (default "<< fps << ")"                         << std::endl;
				std::cout << "\t device   : V4L2 capture device (default "<< dev_name << ")"                       << std::endl;
				exit(0);
			}
		}
	}
	std::list<std::string> devList;
	while (optind<argc)
	{
		devList.push_back(argv[optind]);
		optind++;
	}
	if (devList.empty())
	{
		devList.push_back(dev_name);
	}

	// init logger
	initLogger(verbose);
     
	// create live555 environment
	TaskScheduler* scheduler = BasicTaskScheduler::createNew();
	UsageEnvironment* env = BasicUsageEnvironment::createNew(*scheduler);	

	// split multicast info
	std::istringstream is(maddr);
	std::string ip;
	getline(is, ip, ':');						
	struct in_addr destinationAddress;
	destinationAddress.s_addr = chooseRandomIPv4SSMAddress(*env);
	if (!ip.empty())
	{
		destinationAddress.s_addr = inet_addr(ip.c_str());
	}						
	
	std::string port;
	getline(is, port, ':');						
	unsigned short rtpPortNum = 20000;
	if (!port.empty())
	{
		rtpPortNum = atoi(port.c_str());
	}	
	unsigned short rtcpPortNum = rtpPortNum+1;
	unsigned char ttl = 5;
	
	// create RTSP server
	RTSPServer* rtspServer = createRTSPServer(*env, rtspPort, rtspOverHTTPPort, timeout);
	if (rtspServer == NULL) 
	{
		LOG(ERROR) << "Failed to create RTSP server: " << env->getResultMsg();
	}
	else
	{			
		int nbSource = 0;
		std::list<std::string>::iterator devIt;
		for ( devIt=devList.begin() ; devIt!=devList.end() ; ++devIt)
		{
			std::string deviceName(*devIt);
			
			// Init capture
			LOG(NOTICE) << "Create V4L2 Source..." << deviceName;
			V4L2DeviceParameters param(deviceName.c_str(),format,width,height,fps, verbose);
			V4l2Capture* videoCapture = V4l2DeviceFactory::CreateVideoCapure(param, useMmap);
			if (videoCapture)
			{
				nbSource++;
				format = videoCapture->getFormat();				
				int outfd = -1;
				
				V4l2Output* out = NULL;
				if (!outputFile.empty())
				{
					V4L2DeviceParameters outparam(outputFile.c_str(), videoCapture->getFormat(), videoCapture->getWidth(), videoCapture->getHeight(), 0,verbose);
					V4l2Output* out = V4l2DeviceFactory::CreateVideoOutput(outparam, useMmap);
					if (out != NULL)
					{
						outfd = out->getFd();
					}
				}
				
				LOG(NOTICE) << "Start V4L2 Capture..." << deviceName;
				if (!videoCapture->captureStart())
				{
					LOG(NOTICE) << "Cannot start V4L2 Capture for:" << deviceName;
				}
				V4L2DeviceSource* videoES = NULL;
				if (format == V4L2_PIX_FMT_H264)
				{
					videoES = H264_V4L2DeviceSource::createNew(*env, param, videoCapture, outfd, queueSize, useThread, repeatConfig);
				}
				else
				{
					videoES = V4L2DeviceSource::createNew(*env, param, videoCapture, outfd, queueSize, useThread);
				}
				if (videoES == NULL) 
				{
					LOG(FATAL) << "Unable to create source for device " << deviceName;
					delete videoCapture;
				}
				else
				{	
					// extend buffer size if needed
					if (videoCapture->getBufferSize() > OutPacketBuffer::maxSize)
					{
						OutPacketBuffer::maxSize = videoCapture->getBufferSize();
					}
					
					StreamReplicator* replicator = StreamReplicator::createNew(*env, videoES, false);
					
					std::string baseUrl;
					if (devList.size() > 1)
					{
						baseUrl = basename(deviceName.c_str());
						baseUrl.append("/");
					}
					
					// Create Multicast Session
					if (multicast)						
					{		
						LOG(NOTICE) << "RTP  address " << inet_ntoa(destinationAddress) << ":" << rtpPortNum;
						LOG(NOTICE) << "RTCP address " << inet_ntoa(destinationAddress) << ":" << rtcpPortNum;
						addSession(rtspServer, baseUrl+murl, MulticastServerMediaSubsession::createNew(*env,destinationAddress, Port(rtpPortNum), Port(rtcpPortNum), ttl, replicator,format));					
						
						// increment ports for next sessions
						rtpPortNum+=2;
						rtcpPortNum+=2;
						
					}
					// Create Unicast Session
					addSession(rtspServer, baseUrl+url, UnicastServerMediaSubsession::createNew(*env,replicator,format));
				}	
				if (out)
				{
					delete out;
				}
			}
		}

		if (nbSource>0)
		{
			// main loop
			signal(SIGINT,sighandler);
			env->taskScheduler().doEventLoop(&quit); 
			LOG(NOTICE) << "Exiting....";			
		}
		
		Medium::close(rtspServer);
	}
	
	env->reclaim();
	delete scheduler;	
	
	return 0;
}
	//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	// SaveToPrefs()
	//	The settings for each device are stored in CFPreferences on a per-user basis. 
	//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	void DeviceSettings::SaveToPrefs(const Device& device, const DeviceSettings::ControlInfo* controlsToSave, UInt32 numberControlsToSave)
	{
		// Until further implementation, make this a NOP
		return;
		
		#if	Log_SaveRestoreFromPrefs
			CACFString deviceName(device.CopyDeviceName());
			char name[256];
			UInt32 nameSize = 256;
			deviceName.GetCString(name, nameSize);
			DebugMessage("CMIO::DP::DeviceSettings::SaveToPrefs: %s", name);
		#endif
		
		// Get the current prefs Data
		CFMutableDictionaryRef currentPrefsCFDictionary = NULL;

		// Open the prefs file for reading
		FILE* prefsFile = fopen(kDALDeviceSettingsFilePath, "r");
		if (prefsFile != NULL)
		{
			// Get the length of the file
			fseek(prefsFile, 0, SEEK_END);
			UInt32 fileLength = ftell(prefsFile);
			fseek(prefsFile, 0, SEEK_SET);
			
			if (fileLength > 0)
			{
				// Allocate a block of memory to hold the data in the file
				CAAutoFree<Byte> rawPrefsData(fileLength);
				
				// Read all the data in
				fread(static_cast<Byte*>(rawPrefsData), fileLength, 1, prefsFile);
				
				// Close the file
				fclose(prefsFile);
				
				// Put it into a CFData object
				CACFData rawPrefsCFData(static_cast<Byte*>(rawPrefsData), fileLength);
				
				// Parse the data as a property list
				currentPrefsCFDictionary = (CFMutableDictionaryRef)CFPropertyListCreateFromXMLData(NULL, rawPrefsCFData.GetCFData(), kCFPropertyListMutableContainersAndLeaves, NULL);
			}
			else
			{
				// No data, so close the file
				fclose(prefsFile);
				
				// Create a new, mutable dictionary
				currentPrefsCFDictionary = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
			}
		}
		else
		{
			// No file, or a bad file, so just create a new, mutable dictionary
			currentPrefsCFDictionary = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
		}
		
		// Just skip things if we still don't have a current prefs dictionary
		if (currentPrefsCFDictionary != NULL)
		{
			// Make a CACFDictionary for convenience and to be sure it gets released
			CACFDictionary currentPrefsDictionary(currentPrefsCFDictionary, true);
			
			// Make the dictionary key for this device
			CACFString uid(device.CopyDeviceUID());
			CACFString prefsKey(CFStringCreateWithFormat(NULL, NULL, CFSTR("com.apple.cmio.CMIO.DeviceSettings.%@"), uid.GetCFString()));
			
			// Save the device's settings into a dictionary
			CACFDictionary settingsDictionary(SaveToDictionary(device, controlsToSave, numberControlsToSave), true);
			
			// Put the settings into the prefs
			currentPrefsDictionary.AddDictionary(prefsKey.GetCFString(), settingsDictionary.GetCFDictionary());
			
			// Make a CFData that contains the new prefs
			CACFData newRawPrefsCFData(CFPropertyListCreateXMLData(NULL, (CFPropertyListRef)currentPrefsDictionary.GetCFMutableDictionary()), true);
			
			if (newRawPrefsCFData.IsValid())
			{
				// Open the prefs file for writing
				prefsFile = fopen(kDALDeviceSettingsFilePath, "w+");
				if (prefsFile != NULL)
				{
					// Write the data
					fwrite(newRawPrefsCFData.GetDataPtr(), newRawPrefsCFData.GetSize(), 1, prefsFile);
					
					// Close the file
					fclose(prefsFile);
				}
			}
		}
		
		#if	Log_SaveRestoreFromPrefs
			DebugMessage("CMIO::DP::DeviceSettings::SaveToPrefs: %s finished", name);
		#endif
	}
	void	DeviceSettings::RestoreFromPrefs(CMIO::DP::Device& device, const DeviceSettings::ControlInfo* controlsToRestore, UInt32 numberControlsToRestore)
	{
		// Until further implementation, make this a NOP
		return;
		
		// Take and hold the device's state guard while we do this to prevent notifications from
		// Interupting the full completion of this routine.
		CAMutex::Locker deviceStateMutex(device.GetStateMutex());
		
		#if	Log_SaveRestoreFromPrefs
			CACFString deviceName(device.CopyDeviceName());
			char name[256];
			UInt32 nameSize = 256;
			deviceName.GetCString(name, nameSize);
		#endif

		// Look for this device's settings in the global preferences domain
		CACFString uid(device.CopyDeviceUID());
		CACFString prefsKey(CFStringCreateWithFormat(NULL, NULL, CFSTR("com.apple.cmio.CMIO.DeviceSettings.%@"), uid.GetCFString()));
		CFDictionaryRef prefValue = CACFPreferences::CopyDictionaryValue(prefsKey.GetCFString(), false, true);
		
		// Delete it if we found it, since we aren't using this location any longer
		if (prefValue != NULL)
		{
			#if	Log_SaveRestoreFromPrefs
				DebugMessage("CMIO::DP::DeviceSettings::RestoreFromPrefs: %s (old-skool)", name);
			#endif
			CACFPreferences::DeleteValue(prefsKey.GetCFString(), false, true, true);
			CACFPreferences::Synchronize(false, true, true);
		}
		
		// If we didn't find it, look in the prefs file
		if (prefValue == NULL)
		{
			// Get the current prefs Data
			CFMutableDictionaryRef currentPrefsCFDictionary = NULL;

			// Open the prefs file for reading
			FILE* prefsFile = fopen(kDALDeviceSettingsFilePath, "r");
			if (prefsFile != NULL)
			{
				// Get the length of the file
				fseek(prefsFile, 0, SEEK_END);
				UInt32 fileLength = ftell(prefsFile);
				fseek(prefsFile, 0, SEEK_SET);
				
				if (fileLength > 0)
				{
					// Allocate a block of memory to hold the data in the file
					CAAutoFree<Byte> rawPrefsData(fileLength);
					
					// Read all the data in
					fread(static_cast<Byte*>(rawPrefsData), fileLength, 1, prefsFile);
					
					// Close the file
					fclose(prefsFile);
					
					// Put it into a CFData object
					CACFData rawPrefsCFData(static_cast<Byte*>(rawPrefsData), fileLength);
					
					// Parse the data as a property list
					currentPrefsCFDictionary = (CFMutableDictionaryRef)CFPropertyListCreateFromXMLData(NULL, rawPrefsCFData.GetCFData(), kCFPropertyListMutableContainersAndLeaves, NULL);
				}
				else
				{
					// No data in the file, so just close it
					fclose(prefsFile);
				}
			}
			
			if (currentPrefsCFDictionary != NULL)
			{
				// There are some prefs, so make a CACFDictionary for convenience and to make sure it is released
				CACFDictionary currentPrefsDictionary(currentPrefsCFDictionary, true);
				
				// Look for the settings for this device
				currentPrefsDictionary.GetDictionary(prefsKey.GetCFString(), prefValue);
				
				// If we found it, retain it because we will release it later
				if (prefValue != NULL)
				{
					CFRetain(prefValue);
				}
			}
			
			#if	Log_SaveRestoreFromPrefs
				if (prefValue != NULL)
				{
					DebugMessage("CMIO::DP::DeviceSettings::RestoreFromPrefs: %s (nu-skool)", name);
				}
				else
				{
					DebugMessage("CMIO::DP::DeviceSettings::RestoreFromPrefs: %s (nada)", name);
				}
			#endif
		}
		
		// Restore the settings
		if (prefValue != NULL)
		{
			RestoreFromDictionary(device, prefValue, controlsToRestore, numberControlsToRestore);
			CFRelease(prefValue);
		}
		
		#if	Log_SaveRestoreFromPrefs
			DebugMessage("CMIO::DP::DeviceSettings::RestoreFromPrefs: %s finished", name);
		#endif
	}
Exemplo n.º 17
0
static status_t s_open(alsa_handle_t *handle, uint32_t devices, int mode)
{
	// Close off previously opened device.
	// It would be nice to determine if the underlying device actually
	// changes, but we might be recovering from an error or manipulating
    // mixer settings (see asound.conf).
    //
    ALOGD("open called for devices %08x in mode %d...", devices, mode);
    if( devices == 0 ){
    	return BAD_VALUE;
	}
    s_close(handle);

    pthread_mutex_lock(&handle->mLock);

    const char *stream = streamName(handle);
    const char *devName = deviceName(handle, devices, mode);
    int err,card;
    char prop[20],dev_Name[20],card_name[32]; 
 ALOGD("input handle: %s, devName = %s \n", (char*)handle->modPrivate, devName);
#if 1 
    if ((direction(handle) == SND_PCM_STREAM_CAPTURE)/*||(direction(handle) == SND_PCM_STREAM_PLAYBACK)*/){
        card = getDeviceNum(direction(handle), card_name);
	ALOGD("card : %d\n", card);

        if(card >= 0){
           // sprintf(dev_Name,"plug:SLAVE='hw:%d,0'",card);
            sprintf(dev_Name, "hw:%d", card);
            devName = dev_Name;
        }
        // if we want usb-audio, but returned builtin-audio, return error.
        // audiopolicymanager should try next card
        ALOGD("card name: %s\n", card_name);
        ALOGD("devName: %s\n", devName);
        if(strncmp(card_name,"AML", 3) == 0 && strcmp((char*)handle->modPrivate, "usb-audio") == 0){
          
          pthread_mutex_unlock(&handle->mLock);
          ALOGD("You are request usb-audio with usb's params, but returned builtin-audio card\n");
          return NO_INIT;
        }
   }
    if(direction(handle) == SND_PCM_STREAM_PLAYBACK){
		card = snd_card_get_aml_card();
		ALOGD("SND_PCM_STREAM_PLAYBACK  card : %d\n", card);

		sprintf(dev_Name, "hw:%d", card);
		devName = dev_Name;
    }
#else

	if(direction(handle) == SND_PCM_STREAM_CAPTURE){
		sprintf(dev_Name, "hw:0");
		devName = dev_Name;
    	}

#endif	
    for (;;) {
        // The PCM stream is opened in blocking mode, per ALSA defaults.  The
        // AudioFlinger seems to assume blocking mode too, so asynchronous mode
        // should not be used.
         ALOGD("---- devName = %s \n", devName);

        err = snd_pcm_open(&handle->handle, devName, direction(handle),
                SND_PCM_ASYNC);
        if (err == 0) break;

        // See if there is a less specific name we can try.
        // Note: We are changing the contents of a const char * here.
        char *tail = strrchr(devName, '_');
        if (!tail) break;
        *tail = 0;
    }

    if (err < 0) {
        // None of the Android defined audio devices exist. Open a generic one.
        devName = "default";
         ALOGD("-r-- devName = %s \n", devName);

        err = snd_pcm_open(&handle->handle, devName, direction(handle), 0);
    }

    if (err < 0) {
        ALOGE("Failed to Initialize any ALSA %s device: %s",
                stream, strerror(err));
	 pthread_mutex_unlock(&handle->mLock);
        return NO_INIT;
    }

    err = setHardwareParams(handle);

    if (err == NO_ERROR) err = setSoftwareParams(handle);

    ALOGI("Initialized ALSA %s device %s", stream, devName);

    handle->curDev = devices;
    handle->curMode = mode;

    pthread_mutex_unlock(&handle->mLock);
    return err;
}
Exemplo n.º 18
0
bool KMobileDevice::lockDevice(const QString &device, QString &err_reason)
{
#ifdef HAVE_BAUDBOY_H
  return ttylock(device.local8bit()) == EXIT_SUCCESS;
#else
# ifdef HAVE_LOCKDEV_H
  return !dev_lock(device.local8bit());
# else
  int pid = -1;
  QStringList all = QStringList::split('/', device);
  if (!all.count()) {
	err_reason = i18n("Invalid device (%1)").arg(device);
	return false;
  }
  QString lockName = DEVICE_LOCK_PATH_PREFIX + all[all.count()-1];
  QFile file(lockName);
  if (file.exists() && file.open(IO_ReadOnly)) {
     if (file.size() == 0) {
	err_reason = i18n("Unable to read lockfile %s. Please check for reason and "
		"remove the lockfile by hand.").arg(lockName);
	PRINT_DEBUG << err_reason;
	return false;
     }
     if (file.size() == 4 && sizeof(int)==4) {
        file.readLine((char *)(&pid), 4); /* Kermit-style lockfile */
     } else {
        QTextStream ts(&file);
        ts >> pid; /* Ascii lockfile */
     }
     file.close();

     if (pid > 0 && kill((pid_t)pid, 0) < 0 && errno == ESRCH) {
	PRINT_DEBUG << QString("Lockfile %1 is stale. Overriding it..\n").arg(lockName);
	sleep(1);
	if (!file.remove()) {
		PRINT_DEBUG << QString("Overriding failed, please check the permissions\n");
		PRINT_DEBUG << QString("Cannot lock device %1\n").arg(device);
		err_reason = i18n("Lockfile %1 is stale. Please check permissions.").arg(lockName);
		return false;
	}
     } else {
	err_reason = i18n("Device %1 already locked.").arg(device);
	return false;
    }
  }

  /* Try to create a new file, with 0644 mode */
  int fd = open(lockName.local8Bit(), O_CREAT | O_EXCL | O_WRONLY, 0644);
  if (fd == -1) {
	if (errno == EEXIST)
		err_reason = i18n("Device %1 seems to be locked by unknown process.").arg(device);
	else if (errno == EACCES)
		err_reason = i18n("Please check permission on lock directory.");
	else if (errno == ENOENT)
		err_reason = i18n("Cannot create lockfile %1. Please check for existence of path.").arg(lockName);
	else
		err_reason = i18n("Could not create lockfile %1. Error-Code is %2.").arg(lockName).arg(errno);
	return false;
  }
  QString lockText;
  lockText = QString("%1 kmobile\n").arg(getpid(),10);
  write(fd, lockText.utf8(), lockText.utf8().length());
  close(fd);

  PRINT_DEBUG << QString("%1: Device %2 locked with lockfile %3.\n")
	.arg(deviceName()).arg(device).arg(lockName);

  err_reason = QString::null;

  return true;
# endif
#endif
}
Exemplo n.º 19
0
ControlEditorDialog::ControlEditorDialog
        (
            QWidget *parent,
            RosegardenDocument *doc,
            DeviceId device
       ):
        QMainWindow(parent),
        m_studio(&doc->getStudio()),
        m_doc(doc),
        m_device(device),
        m_modified(false)
{
    RG_DEBUG << "ControlEditorDialog::ControlEditorDialog: device is " << m_device << endl;

    QWidget *mainFrame = new QWidget(this);
    QVBoxLayout *mainFrameLayout = new QVBoxLayout;
    setCentralWidget(mainFrame);
    setAttribute(Qt::WA_DeleteOnClose);

    // everything else failed, so screw it, let's just set the fscking minimum
    // width the brute force way
    setMinimumWidth(935);

    setWindowTitle(tr("Manage Controllers"));

    QString deviceName(tr("<no device>"));
    MidiDevice *md =
        dynamic_cast<MidiDevice *>(m_studio->getDevice(m_device));
    if (md)
        deviceName = strtoqstr(md->getName());

    // spacing hack!
    new QLabel("", mainFrame);
    new QLabel(tr("  Controllers for %1 (device %2)")
           .arg(deviceName)
           .arg(device), mainFrame);
    new QLabel("", mainFrame);
    
    QStringList sl;
    sl  << tr("Name  ")
        << tr("Type  ")
        << tr("Number  ")
        << tr("Description  ")
        << tr("Min. value  ")
        << tr("Max. value  ")
        << tr("Default value  ")
        << tr("Color  ")
        << tr("Position on instrument panel");
    
    m_treeWidget = new QTreeWidget(mainFrame);
    m_treeWidget->setHeaderLabels(sl);
    m_treeWidget->setSortingEnabled(true);
    
    mainFrameLayout->addWidget(m_treeWidget);
    
    QFrame *btnBox = new QFrame(mainFrame);
    mainFrameLayout->addWidget(btnBox);
    mainFrame->setLayout(mainFrameLayout);

    btnBox->setSizePolicy(
        QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed));

    // QT3: I don't think it's necessary to replace the following ",4, 10" with
    // anything to explicitly set the dimensions of the HBox, but there might be
    // some compatibility trickery I'm not remembering, etc.  Leaving as a
    // reminder in case the layout turns out broken:
    QHBoxLayout* layout = new QHBoxLayout(btnBox /*, 4, 10 */);

    m_addButton = new QPushButton(tr("Add"), btnBox);
    m_deleteButton = new QPushButton(tr("Delete"), btnBox);

    m_closeButton = new QPushButton(tr("Close"), btnBox);

    m_addButton->setToolTip(tr("Add a Control Parameter to the Studio"));

    m_deleteButton->setToolTip(tr("Delete a Control Parameter from the Studio"));

    m_closeButton->setToolTip(tr("Close the Control Parameter editor"));

    layout->addStretch(10);
    layout->addWidget(m_addButton);
    layout->addWidget(m_deleteButton);
    layout->addSpacing(30);

    layout->addWidget(m_closeButton);
    layout->addSpacing(5);

    connect(m_addButton, SIGNAL(released()),
            SLOT(slotAdd()));

    connect(m_deleteButton, SIGNAL(released()),
            SLOT(slotDelete()));

    setupActions();

    connect(CommandHistory::getInstance(), SIGNAL(commandExecuted()),
            this, SLOT(slotUpdate()));

    connect(m_treeWidget, SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)),
            SLOT(slotEdit(QTreeWidgetItem *, int)));

    // Highlight all columns - enable extended selection mode
    //
    m_treeWidget->setAllColumnsShowFocus(true);
    
    m_treeWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);

    initDialog();
    
    // Set the top item in the list, if able.
    if (m_treeWidget->topLevelItemCount()) {
        m_treeWidget->setCurrentItem(m_treeWidget->topLevelItem(0));
    }
}
Exemplo n.º 20
0
void AutoBoot::handleCommand(quint8 command, quint16 aux)
{

    switch (command) {
        case 0x3F:  // Speed poll
            {
                if (!sio->port()->writeCommandAck()) {
                    return;
                }
                sio->port()->writeComplete();
                QByteArray speed(1, 0);
                speed[0] = sio->port()->speedByte();
                sio->port()->writeDataFrame(speed);
                qDebug() << "!n" << tr("[%1] Speed poll.").arg(deviceName());
                break;
            }
        case 0x52:
            {    /* Read sector */
                if (loaded) {
                    passToOldHandler(command, aux);
                    return;
                }
                if (aux >= 1 && aux <= sectorCount) {
                    if (!sio->port()->writeCommandAck()) {
                        return;
                    }
                    if (!started) {
                        emit booterStarted();
                        started = true;
                    }
                    QByteArray data;
                    if (readSector(aux, data)) {
                        sio->port()->writeComplete();
                        sio->port()->writeDataFrame(data);
                        qDebug() << "!n" << tr("[%1] Read sector %2 (%3 bytes).")
                                       .arg(deviceName())
                                       .arg(aux)
                                       .arg(data.size());
                    } else {
                        sio->port()->writeError();
                        qCritical() << "!e" << tr("[%1] Read sector %2 failed.")
                                       .arg(deviceName())
                                       .arg(aux);
                    }
                } else {
                    passToOldHandler(command, aux);
                }
                break;
            }
        case 0x53:
            {    /* Get status */
                if (loaded) {
                    passToOldHandler(command, aux);
                    return;
                }
                if (!sio->port()->writeCommandAck()) {
                    return;
                }

                QByteArray status(4, 0);
                status[0] = 8;
                status[3] = 1;
                sio->port()->writeComplete();
                sio->port()->writeDataFrame(status);
                qDebug() << "!n" << tr("[%1] Get status.")
                               .arg(deviceName());
                break;
            }
        case 0xFD:
            {
                if (!sio->port()->writeCommandAck()) {
                    return;
                }
                qDebug() << "!n" << tr("[%1] Atari is jumping to %2.")
                               .arg(deviceName())
                               .arg(aux);
                emit loaderDone();
                sio->port()->writeComplete();
                break;
            }
        case 0xFE:
            {   /* Get chunk */
                if(aux >= chunks.count()) {
                    qDebug() << "!e" << tr("[%1] Invalid chunk in get chunk: aux = %2")
                                   .arg(deviceName())
                                   .arg(aux);
                    return;
                }

                if (!sio->port()->writeCommandAck()) {
                    return;
                }
                qDebug() << "!n" << tr("[%1] Get chunk %2 (%3 bytes).")
                               .arg(deviceName())
                               .arg(aux)
                               .arg(chunks.at(aux).data.size());
                sio->port()->writeComplete();
                sio->port()->writeDataFrame(chunks.at(aux).data);
                emit blockRead(aux + 1, chunks.count());
                break;
            }
        case 0xFF:
            {   /* Get chunk info */
                if(aux >= chunks.count()) {
                    qDebug() << "!e" << tr("[%1] Invalid chunk in get chunk info: aux = %2")
                                   .arg(deviceName())
                                   .arg(aux);
                    return;
                }

                if (!sio->port()->writeCommandAck()) {
                    return;
                }
                if (!loaded) {
                    loaded = true;
                    emit booterLoaded();
                }
                QByteArray data;
                data[0] = chunks.at(aux).address % 256;
                data[1] = chunks.at(aux).address / 256;
                data[2] = 1;
                data[3] = chunks.size() != aux + 1;
                data[4] = chunks.at(aux).data.size() % 256;
                data[5] = chunks.at(aux).data.size() / 256;
                qDebug() << "!d" << tr("[%1] Get chunk info %2 (%3 bytes at %4).")
                               .arg(deviceName())
                               .arg(aux)
                               .arg(chunks.at(aux).data.size())
                               .arg(chunks.at(aux).address);
                sio->port()->writeComplete();
                sio->port()->writeDataFrame(data);
                break;
            }
        default:
            passToOldHandler(command, aux);
            return;
            break;
    }
}
Exemplo n.º 21
0
	std::string WirelessNode::name() const
	{
		return deviceName(nodeAddress());
	}
Exemplo n.º 22
0
	std::string BaseStation::name() const
	{
		return deviceName(serial());
	}
Exemplo n.º 23
0
   QList<DiskDevice *> enumerateDevice()
   {
       QList<DiskDevice *> devices;
       utils::writeLog("Enumerating imageable devices for OSX");
       QProcess process;
       QStringList lines;
       process.setEnvironment(QStringList() << "LANG=C");
       process.start("/usr/sbin/diskutil", QStringList() << "list", QIODevice::ReadWrite | QIODevice::Text);
       if (! process.waitForFinished())
           utils::writeLog("Could not execute diskutil to enumerate devices");
       else
       {
           QTextStream stdoutStream(process.readAllStandardOutput());
           while (true)
           {
               QString line = stdoutStream.readLine().simplified(); /* Remove trailing and leading ws */
               if (line.isNull())
                   break;
               /* The line holding the device is the only line always starting with 0: */
               else if (line.startsWith("0:"))
               {
                   lines << line;
               }
           }
           for (int i = 0; i < lines.count(); i++)
           {
               QString line = lines.at(i);
               QStringList deviceAttr = line.split(" ");

               /*
                * THE FOLLOWING LIST CHANGES IF THE DISK WAS NOT INITIALISED
                * In that case, <partition schema name> is missing and the
                * index for the following elements has to be adressed by n-1
                * content is now:
                * [0] 0:
                * [1] <partition scheme name>
                * [2] <total_size>
                * [3] <size_unit>
                * [4] device name (disk0, disk1, etc)
                */
               QString deviceSpace;
               QString devicePath("/dev/");
               if (deviceAttr.at(1).startsWith("*"))
               {
                   /* partition schema name was missing - uninitialised disk */
                   deviceSpace = deviceAttr.at(1) + " " + deviceAttr.at(2);
                   devicePath += (new QString(deviceAttr.at(3)))->replace(0, 1, "rd");
               } else
               {
                   deviceSpace = deviceAttr.at(2) + " " + deviceAttr.at(3);
                   QString deviceName(deviceAttr.at(4));
                   /* make the disk become a rdisk */
                   devicePath += deviceName.replace(0, 1, "rd");
               }

               deviceSpace.remove("*");
               DiskDevice *nd = new DiskDevice(i, devicePath, deviceSpace);
               utils::writeLog("=================================================");
               utils::writeLog("Starting to parse " + devicePath + " for additional info\n");
               nd = addAdditionalInfo(nd);

               if (nd->getIsWritable())
               {
                   utils::writeLog("Parsed device as writable. Appending.");
                   devices.append(nd);
               }
               else
               {
                   utils::writeLog("Parsed device as NON-writable. NOT Appending.");
               }
               utils::writeLog("\n");
               utils::writeLog("Finished parsing additional info for " + devicePath);
               utils::writeLog("=================================================\n");
           }
       }
       return devices;
   }
Exemplo n.º 24
0
 std::string InertialNode::name()
 {
     return deviceName(info().serialNumber());
 }
Exemplo n.º 25
0
int _tmain(int argc, _TCHAR* argv[])
{
	int						numDevices = 0; 
	HRESULT					result;
	IDeckLinkAttributes		*deckLinkAttributes = NULL;
	HRESULT					attributeResult;
	BOOL					keyingSupported;
	BOOL					HDkeyingSupported;
	int						selectedMode = 0;

	printf("GDI Keyer Sample Application\n\n"); 
	// Initialize COM on this thread
	result = CoInitialize(NULL);

	if (FAILED(result))
	{
		fprintf(stderr, "Initialization of COM failed - result = %08x.\n", result);
		return 1;
	}
	
	// Create an IDeckLinkIterator object to enumerate all DeckLink cards in the system
	result = CoCreateInstance(CLSID_CDeckLinkIterator, NULL, CLSCTX_ALL, IID_IDeckLinkIterator, (void**)&deckLinkIterator);
	if (FAILED(result))
	{
		fprintf(stderr, "A DeckLink iterator could not be created.  The DeckLink drivers may not be installed.\n");
		return 1;
	}

	// Enumerate all cards in this system 
	while (deckLinkIterator->Next(&deckLink) == S_OK) 
	{ 
		BSTR	deviceNameBSTR = NULL; 
		 
		// Increment the total number of DeckLink cards found 
		numDevices++; 
		if (numDevices > 1) 
			printf("\n\n");	 
		 
		// *** Print the model name of the DeckLink card 
		result = deckLink->GetModelName(&deviceNameBSTR); 
		if (result == S_OK) 
		{	
			_bstr_t deviceName(deviceNameBSTR);		

			printf("Found Blackmagic device: %s\n", (char*)deviceName);
			attributeResult = deckLink->QueryInterface(IID_IDeckLinkAttributes, (void**)&deckLinkAttributes);
			if (attributeResult != S_OK)
			{
				fprintf(stderr, "Could not obtain the IDeckLinkAttributes interface");
				return 1;
			}
			else
			{
				attributeResult = deckLinkAttributes->GetFlag(BMDDeckLinkSupportsInternalKeying, &keyingSupported);	// is keying supported on this device?
				if (attributeResult == S_OK && keyingSupported)			
				{
					IDeckLinkDisplayModeIterator* displayModeIterator = NULL;
					IDeckLinkDisplayMode* deckLinkDisplayMode = NULL;

					attributeResult = deckLinkAttributes->GetFlag(BMDDeckLinkSupportsHDKeying, &HDkeyingSupported);
					if (attributeResult == S_OK && HDkeyingSupported)
						printf("HD Mode keying supported.\n");
					else
						printf("SD Mode Keying supported.\n");
					// check if automode detection support - if so, use it for autodetection				
					if (CheckFormatDetect(deckLinkAttributes) == 0)
					{
						fprintf(stderr, "Input mode detection not supported\n");

						if (deckLink->QueryInterface(IID_IDeckLinkOutput, (void**)&deckLinkOutput) != S_OK)
						{
							fprintf(stderr, "Could not obtain the IDeckLinkOutput interface\n");
						}
						else
						{
							int		index = 0;
							if (deckLinkOutput->GetDisplayModeIterator(&displayModeIterator) != S_OK)
							{
								fprintf(stderr, "Could not obtain the display mode iterator\n");
							}
							else
							{
								printf("\n");
								while (displayModeIterator->Next(&deckLinkDisplayMode) == S_OK)
								{
									BSTR			displayModeBSTR = NULL;
									int				modeWidth;
									int				modeHeight;
									BMDTimeValue	frameRateDuration;
									BMDTimeScale	frameRateScale;

									// Obtain the display mode's properties
									modeWidth = deckLinkDisplayMode->GetWidth();
									modeHeight = deckLinkDisplayMode->GetHeight();
									deckLinkDisplayMode->GetFrameRate(&frameRateDuration, &frameRateScale);
									if ((deckLinkDisplayMode->GetWidth() > 720) && !HDkeyingSupported)
										continue;

									if (deckLinkDisplayMode->GetName(&displayModeBSTR) == S_OK)
									{
										_bstr_t			modeName(displayModeBSTR, false);
										// Skip HD modes on cards such as DeckLink SDI (only PAL/NTSC are supported for keying)
										printf("%d %-20s \t %d x %d \t %g FPS\n", index, (char*)modeName, modeWidth, modeHeight, (double)frameRateScale / (double)frameRateDuration);					
									}
									deckLinkDisplayMode->Release();
									index++;
								}
								displayModeIterator->Release();

								printf("Select Mode (0-%d):\n", index-1);

								scanf_s("%d", &selectedMode);
								printf("Mode selected: %d\n", selectedMode);
								if(selectedMode < index)
								{
									int modeCount = 0;
									if (deckLinkOutput->GetDisplayModeIterator(&displayModeIterator) != S_OK)
									{
										fprintf(stderr, "Could not obtain the display mode iterator\n");
									}
									else
									{
										while(displayModeIterator->Next(&deckLinkDisplayMode) == S_OK)
										{
											if (selectedMode == modeCount)
											{
												OutputGraphic(deckLinkDisplayMode);
												deckLinkDisplayMode->Release();
												break;
											}
											deckLinkDisplayMode->Release();
											modeCount++;
										}										
										displayModeIterator->Release();
									}									
								}
								else
								{
									printf("Illegal video mode selected\n");
								}
							}

							deckLinkOutput->Release();
						}
					}
				}

				deckLinkAttributes->Release();
				printf("Press Enter key to exit.\n");
				_getch();
			}		
		}		 
		deckLink->Release(); // Release the IDeckLink instance when we've finished with it to prevent leaks
 	} 

	if (deckLinkIterator != NULL)
		deckLinkIterator->Release();

	// If no DeckLink cards were found in the system, inform the users
	if (numDevices == 0) 
		printf("No Blackmagic Design devices were found.\n");

	// Uninitalize COM on this thread
	CoUninitialize();
	return 0;
}
int QGeoSatelliteInfoSourceGypsy::init()
{
    GError *error = NULL;
    char *path;
    GConfClient* client;
    gchar* device_name;

    g_type_init ();
    createEngine();

    client = m_engine->eng_gconf_client_get_default();
    if (!client) {
        qWarning ("QGeoSatelliteInfoSourceGypsy client creation failed.");
        return -1;
    }
    device_name = m_engine->eng_gconf_client_get_string(client, "/apps/geoclue/master/org.freedesktop.Geoclue.GPSDevice", NULL);
    g_object_unref(client);
    QString deviceName(QString::fromAscii(device_name));
    if (deviceName.isEmpty() ||
            (deviceName.trimmed().at(0) == '/' && !QFile::exists(deviceName.trimmed()))) {
        qWarning ("QGeoSatelliteInfoSourceGypsy Empty/nonexistent GPS device name detected.");
        qWarning ("Use gconftool-2 to set it, e.g. on terminal: ");
        qWarning ("gconftool-2 -t string -s /apps/geoclue/master/org.freedesktop.Geoclue.GPSDevice /dev/ttyUSB0");
        m_engine->eng_g_free(device_name);
        return -1;
    }
    GypsyControl *control = NULL;
    control = m_engine->eng_gypsy_control_get_default();
    if (!control) {
        qWarning("QGeoSatelliteInfoSourceGypsy unable to create Gypsy control.");
        m_engine->eng_g_free(device_name);
        return -1;
    }
    // (path is the DBus path)
    path = m_engine->eng_gypsy_control_create (control, device_name, &error);
    m_engine->eng_g_free(device_name);
    g_object_unref(control);
    if (!path) {
        qWarning ("QGeoSatelliteInfoSourceGypsy error creating client.");
        if (error) {
            qWarning ("error message: %s", error->message);
            g_error_free (error);
        }
        return -1;
    }
    m_device = m_engine->eng_gypsy_device_new (path);
    m_satellite = m_engine->eng_gypsy_satellite_new (path);
    m_engine->eng_g_free(path);
    if (!m_device || !m_satellite) {
        qWarning ("QGeoSatelliteInfoSourceGypsy error creating satellite device.");
        qWarning ("Is GPS device set correctly? If not, use gconftool-2 to set it, e.g.: ");
        qWarning ("gconftool-2 -t string -s /apps/geoclue/master/org.freedesktop.Geoclue.GPSDevice /dev/ttyUSB0");
        if (m_device)
            g_object_unref(m_device);
        if (m_satellite)
            g_object_unref(m_satellite);
        return -1;
    }
    m_engine->eng_gypsy_device_start (m_device, &error);
    if (error) {
        qWarning ("QGeoSatelliteInfoSourceGypsy error starting device: %s ",
                   error->message);
        g_error_free(error);
        g_object_unref(m_device);
        g_object_unref(m_satellite);
        return -1;
    }
    return 0;
}
Exemplo n.º 27
0
io_object_t HIDDevice::getHIDDevice ( Misc::ConfigurationFile& configFile )
{
	io_object_t device ( NULL );

	// First option - Open device by vendor ID / product ID
	if ( ! device )
	{
		std::string deviceVendorProductId ( configFile . retrieveString ( "./deviceVendorProductId", "" ) ) ;
		if ( deviceVendorProductId != "" )
		{
			// Split ID string into vendor ID and product ID
			char* colonPtr ;
			int vendorId ( strtol ( deviceVendorProductId . c_str ( ) , &colonPtr , 16 ) ) ;
			char* endPtr ;
			int productId ( strtol ( colonPtr + 1, &endPtr, 16 ) ) ;
			if ( *colonPtr != ':' || *endPtr != '\0' || vendorId < 0 || productId < 0 )
				Misc::throwStdErr ( "HIDDevice: Malformed vendorId:productId string \"%s\"",
				                    deviceVendorProductId.c_str ( ) ) ;
			#ifdef VERBOSE
			printf ( "HIDDevice: Searching for device %04x:%04x\n", vendorId, productId ) ;
			fflush ( stdout ) ;
			#endif
			device = findHIDDeviceByVendorIdAndProductId ( vendorId, productId ) ;
			if ( ! device )
				Misc::throwStdErr ( "HIDDevice: No device with vendorId:productId %04x:%04x found",
				                    vendorId, productId ) ;
		}
	}

	// Second option - Open device by device name
	if ( ! device )
	{
		std::string deviceName ( configFile . retrieveString ( "./deviceName", "" ) ) ;
		if ( deviceName != "" )
		{
			#ifdef VERBOSE
			printf ( "HIDDevice: Searching for device \"%s\"\n", deviceName . c_str ( ) ) ;
			fflush ( stdout ) ;
			#endif
			device = findHIDDeviceByName ( deviceName . c_str ( ) ) ;
			if ( ! device )
				Misc::throwStdErr ( "HIDDevice: No device with name \"%s\" found",
				                    deviceName . c_str ( ) ) ;
		}
	}

	// Third option - Open device by explicit event device file name
	// NOTE: This is not supported on Mac OS X
	if ( ! device )
	{
		std::string deviceFileName ( configFile . retrieveString ( "./deviceFileName", "" ) ) ;
		if ( deviceFileName != "" )
		{
			Misc::throwStdErr ( "HIDDevice: Unable to open device file \"%s\"",
			                    deviceFileName . c_str ( ) ) ;
		}
	}

	// Bail out if no device was found
	if ( ! device )
		Misc::throwStdErr ( "HIDDevice: No device specified" ) ;

	return device ;
}