Esempio n. 1
0
QPpsObject::~QPpsObject()
{
    // RAII - ensure file gets closed
    if (isOpen())
        close();
}
Esempio n. 2
0
	bool File::open(const char* filename, bool create, bool append, bool lock)
	{
		// Make sure no other file is open
		if (isOpen())
		{
			close();

			ali::dealloc(this->filename);
		}

		// If append == true, attempt to open file for appending
		int access = GENERIC_READ | GENERIC_WRITE;
		
		if (append)
			access |= FILE_APPEND_DATA;

		// If create == true, create file if nonexistent
		int creation = 0;
		if (create)
		{
			if (File::exists(filename))
			{
				creation = OPEN_ALWAYS;
			}
			else
			{
				creation = CREATE_NEW;
			}
		}
		else
		{
			creation = OPEN_ALWAYS;
		}

		// If lock == true, lock file for reading/writing/deletion
		int security = (lock ? 0 : FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE);

		file = CreateFile(	filename,				// The filename
							access,					// Preferred access
							security,				// Whether to lock file
							NULL,
							creation,				// Whether to create if not existent
							FILE_ATTRIBUTE_NORMAL,	// Normal attributes
							NULL);

		if (file == INVALID_HANDLE_VALUE)
		{
			// Reinitialize handle
			file = NULL;

			throw OpenFileException();

			return false;
		}
		else
		{
			opened = true;

			// Save filename
			int size = strlen(filename) + 1;
			this->filename = (char*)ali::alloc(size);
			ali::copy(this->filename, (char*)filename, size);
		}

		return true;
	}
/*!
\fn Posix_QextSerialPort::~Posix_QextSerialPort()
Standard destructor.
*/
Posix_QextSerialPort::~Posix_QextSerialPort()
{
    if (isOpen()) {
        close();
    }
}
Esempio n. 4
0
/*! sets the backlog for the listener socket.
 * \note must NOT be called if socket is already open.
 */
void ServerSocket::setBacklog(int value)
{
	assert(isOpen() == false);
	backlog_ = value;
}
 void mouseDoubleClick (const MouseEvent& e)
 {
     if (e.y < titleHeight)
         setOpen (! isOpen());
 }
Esempio n. 6
0
/*------------------------------------------------------------------------------
 *  Open an encoding session
 *----------------------------------------------------------------------------*/
bool
VorbisLibEncoder :: open ( void )
                                                            throw ( Exception )
{
    int     ret;

    if ( isOpen() ) {
        close();
    }

    vorbis_info_init( &vorbisInfo);

    if ( isVBR() ) {

        if ( (ret = vorbis_encode_init_vbr( &vorbisInfo,
                                            getInChannel(),
                                            getOutSampleRate(),
                                            getOutQuality() )) ) {
            throw Exception( __FILE__, __LINE__,
                             "vorbis encode init error", ret);
        }
    } else {
#ifdef VORBIS_LIB_RC3
        if ( (ret = vorbis_encode_init( &vorbisInfo,
                                        getInChannel(),
                                        getOutSampleRate(),
                                        getOutBitrate() * 1024,
                                        getOutBitrate() * 1024,
                                        -1 )) ) {
            throw Exception( __FILE__, __LINE__,
                             "vorbis encode init error", ret);
        }
#else
        if ( (ret = vorbis_encode_init( &vorbisInfo,
                                        getInChannel(),
                                        getOutSampleRate(),
                                        -1,
                                        getOutBitrate() * 1024,
                                        -1 )) ) {
            throw Exception( __FILE__, __LINE__,
                             "vorbis encode init error", ret);
        }
#endif
    }

    if ( (ret = vorbis_analysis_init( &vorbisDspState, &vorbisInfo)) ) {
        throw Exception( __FILE__, __LINE__, "vorbis analysis init error", ret);
    }

    if ( (ret = vorbis_block_init( &vorbisDspState, &vorbisBlock)) ) {
        throw Exception( __FILE__, __LINE__, "vorbis block init error", ret);
    }

    if ( (ret = ogg_stream_init( &oggStreamState, 0)) ) {
        throw Exception( __FILE__, __LINE__, "ogg stream init error", ret);
    }

    // open the underlying sink
    if ( !sink->open() ) {
        throw Exception( __FILE__, __LINE__,
                         "vorbis lib opening underlying sink error");
    }

    // create an empty vorbis_comment structure
    vorbis_comment_init( &vorbisComment);

    // create the vorbis stream headers and send them to the underlying sink
    ogg_packet      header;
    ogg_packet      commentHeader;
    ogg_packet      codeHeader;

    if ( (ret = vorbis_analysis_headerout( &vorbisDspState,
                                           &vorbisComment,
                                           &header,
                                           &commentHeader,
                                           &codeHeader )) ) {
        throw Exception( __FILE__, __LINE__, "vorbis header init error", ret);
    }

    ogg_stream_packetin( &oggStreamState, &header);
    ogg_stream_packetin( &oggStreamState, &commentHeader);
    ogg_stream_packetin( &oggStreamState, &codeHeader);

    ogg_page        oggPage;
    while ( ogg_stream_flush( &oggStreamState, &oggPage) ) {
        sink->write( oggPage.header, oggPage.header_len);
        sink->write( oggPage.body, oggPage.body_len);
    }

    vorbis_comment_clear( &vorbisComment );

    // initialize the resampling coverter if needed
    if ( converter ) {
        converter->initialize( resampleRatio, getInChannel());
    }

    encoderOpen = true;

    return true;
}
Esempio n. 7
0
uint32_t TPipe::read(uint8_t* buf, uint32_t len) {
  if (!isOpen())
    throw TTransportException(TTransportException::NOT_OPEN, "Called read on non-open pipe");
  return impl_->read(buf, len);
}
Esempio n. 8
0
void SerialPort::configure(int baudrate, int databits, EParity parity, EStopBits stopbits)
{
    if (!isOpen())
        return;
#ifdef __WIN32__
    DCB dcb;
    memset(&dcb, 0, sizeof(DCB));
    if (!GetCommState(handle, &dcb))
    {
        LOG(ERROR) << "GetCommState failed!";
        return;
    }
    dcb.BaudRate = baudrate;
    dcb.ByteSize = databits;
    switch(parity)
    {
    case NoParity:
        dcb.Parity = NOPARITY;
        break;
    case OddParity:
        dcb.Parity = ODDPARITY;
        break;
    case EvenParity:
        dcb.Parity = EVENPARITY;
        break;
    case MarkParity:
        dcb.Parity = MARKPARITY;
        break;
    }
    switch(stopbits)
    {
    case OneStopBit:
        dcb.StopBits = ONESTOPBIT;
        break;
    case OneAndAHalfStopBit:
        dcb.StopBits = ONE5STOPBITS;
        break;
    case TwoStopbits:
        dcb.StopBits = TWOSTOPBITS;
        break;
    }

    //Do not handle parity errors.
    dcb.fParity = false;

    //Do not discard null chars.
    dcb.fNull = false;

    //Abort on error. Need to call ClearCommError when an error is returned.
    dcb.fAbortOnError = true;

    //Disable all flow control settings, so we can control the DTR and RTS lines manually.
    dcb.fOutxCtsFlow = false;
    dcb.fOutxDsrFlow = false;
    dcb.fDsrSensitivity = false;
    dcb.fRtsControl = RTS_CONTROL_DISABLE;
    dcb.fDtrControl = DTR_CONTROL_DISABLE;
    dcb.fTXContinueOnXoff = false;

    if(!SetCommState(handle, &dcb))
    {
        LOG(ERROR) << "SetCommState failed!";
    }
#endif
#ifdef __gnu_linux__
    struct termios2 tio;
    ioctl(handle, TCGETS2, &tio);

	// Clear handshake, parity, stopbits and size
    tio.c_cflag |= CLOCAL;
	tio.c_cflag &= ~CRTSCTS;
	tio.c_cflag &= ~PARENB;
	tio.c_cflag &= ~CSTOPB;
	tio.c_cflag &= ~CSIZE;

    // Set the baudrate
    tio.c_cflag &= ~CBAUD;
    tio.c_cflag |= BOTHER;
    tio.c_ispeed = baudrate;
    tio.c_ospeed = baudrate;

	// Enable the receiver
	tio.c_cflag |= CREAD;

    switch (databits)
	{
	case 5:
		tio.c_cflag |= CS5;
		break;
	case 6:
		tio.c_cflag |= CS6;
		break;
	case 7:
		tio.c_cflag |= CS7;
		break;
	default:
	case 8:
		tio.c_cflag |= CS8;
		break;
	}

    switch(parity)
    {
    case NoParity:
        break;
    case OddParity:
        tio.c_cflag |= PARENB | PARODD;
        break;
    case EvenParity:
        tio.c_cflag |= PARENB;
        break;
    case MarkParity:
        tio.c_cflag |= PARENB | PARODD | CMSPAR;
        break;
    }
    switch(stopbits)
    {
    case OneStopBit:
        break;
    case OneAndAHalfStopBit:
        LOG(WARNING) << "OneAndAHalfStopBit not supported on linux!";
        break;
    case TwoStopbits:
        tio.c_cflag |= CSTOPB;
        break;
    }

    ioctl(handle, TCSETS2, &tio);
#endif
#if defined(__APPLE__) && defined(__MACH__)
    struct termios tio;
    tcgetattr(handle, &tio);

	// Clear handshake, parity, stopbits and size
    tio.c_cflag |= CLOCAL;
	tio.c_cflag &= ~CRTSCTS;
	tio.c_cflag &= ~PARENB;
	tio.c_cflag &= ~CSTOPB;
	tio.c_cflag &= ~CSIZE;

	// Enable the receiver
	tio.c_cflag |= CREAD;

    switch (databits)
	{
	case 5:
		tio.c_cflag |= CS5;
		break;
	case 6:
		tio.c_cflag |= CS6;
		break;
	case 7:
		tio.c_cflag |= CS7;
		break;
	default:
	case 8:
		tio.c_cflag |= CS8;
		break;
	}

    switch(parity)
    {
    case NoParity:
        tio.c_cflag &= (tcflag_t) ~(PARENB | PARODD);
        break;
    case OddParity:
        tio.c_cflag |= PARENB | PARODD;
        break;
    case EvenParity:
        tio.c_cflag |= PARENB;
        break;
    case MarkParity:
        tio.c_cflag |= PARENB | PARODD | PARMRK;
        break;
    }

    switch(stopbits)
    {
    case OneStopBit:
        break;
    case OneAndAHalfStopBit:
        LOG(WARNING) << "OneAndAHalfStopBit not supported on posix!";
        break;
    case TwoStopbits:
        tio.c_cflag |= CSTOPB;
        break;
    }

    tcsetattr(handle, TCSANOW, &tio);

    // setting nonstandard baud rate
    speed_t speed = baudrate;
    if (ioctl (handle, IOSSIOSPEED, &speed, 1) < 0) {
        LOG(ERROR) << "setting baud rate failed. errno:" << errno;
    }

#endif
}
Esempio n. 9
0
 void close() {
   if (isOpen()) {
     lame_close(m_gf);
     m_gf = 0;
   }
 }
void TeQtViewsListView::contentsMousePressEvent(QMouseEvent *e)
{
	rightMouseWasClicked_ = false;;
	if (e->button() == RightButton)
	{
		rightMouseWasClicked_ = true;
		popupMenu_->move(e->globalPos().x(), e->globalPos().y());
	}
	else if (e->button() == LeftButton)
	{
		QPoint p( contentsToViewport( e->pos() ) );
		pressedPosition_ = p;
		TeQtCheckListItem *item = (TeQtCheckListItem*)itemAt(p);
		if (item != 0)
		{
			if(item->getType() == TeQtCheckListItem::THEME)
			{
				// don?t drag, if the user clicked into the root decoration of the item
				int x = p.x();
				int len = treeStepSize() * (item->depth() + (rootIsDecorated() ? 1 : 0)) + itemMargin();
				if (x > len)
//				if (p.x() > treeStepSize() * (item->depth() + (rootIsDecorated() ? 1 : 0)) + itemMargin())
				{
					pressedThemeItem_ = (TeQtThemeItem*)item;
					themeOpen_ = isOpen(item);
				}
	
				// Item was pressed inside the visibility box
				if (x > len && x < len + 10)
				{
					if (e->state() & Qt::ShiftButton)
					{
						if (refThemeItemForVis_ == 0)
							refThemeItemForVis_ = (TeQtThemeItem*)item;
						else
						{
							TeQtThemeItem *themeItem = (TeQtThemeItem*)item;
							if ((themeItem == refThemeItemForVis_) ||
								(themeItem->parent() != refThemeItemForVis_->parent()))
								return;

							list<TeQtCheckListItem*> themeItemList;
							list<TeQtCheckListItem*>::iterator it;
							// find if the item pressed is below the reference item
							TeQtCheckListItem *itemBelow = (TeQtCheckListItem*)refThemeItemForVis_->itemBelow();
							while((itemBelow != 0) && (itemBelow->getType() == TeQtCheckListItem::THEME))
							{
								themeItemList.push_back(itemBelow);
								if (itemBelow == themeItem)
								{
									for (it = themeItemList.begin(); it != themeItemList.end(); ++it)
									{
										TeQtCheckListItem *thItem = *it;
										bool visible = refThemeItemForVis_->isOn();
										setOn(thItem, visible);
									}
									refThemeItemForVis_ = 0;
									return;
								}
								itemBelow = (TeQtCheckListItem*)itemBelow->itemBelow();
							}

							// find if the item pressed is above the reference item
							themeItemList.clear();
							TeQtCheckListItem *itemAbove = (TeQtCheckListItem*)refThemeItemForVis_->itemAbove();
							while((itemAbove != 0) && (itemAbove->getType() == TeQtCheckListItem::THEME))
							{
								themeItemList.push_back(itemAbove);
								if (itemAbove == themeItem)
								{
									for (it = themeItemList.begin(); it != themeItemList.end(); ++it)
									{
										TeQtCheckListItem* thItem = *it;
										bool visible = refThemeItemForVis_->isOn();
										setOn(thItem, visible);
									}
									refThemeItemForVis_ = 0;
									return;
								}
								itemAbove = (TeQtCheckListItem*)itemAbove->itemAbove();
							}
						}
					}
					else
						refThemeItemForVis_ = 0;
				}
			}
			else
			{
				item->setSelected(false);
				item->repaint();
				pressedThemeItem_ = 0;
			}
			leftButtonPressed_ = true;
		}
	}

	QListView::contentsMousePressEvent(e);
}
Esempio n. 11
0
bool KGPGFile::open(OpenMode mode)
{
  if (isOpen()) {
    return false;
  }

  if (d->m_fn.isEmpty()) {
    setOpenMode(NotOpen);
    return false;
  }

  if (!d->ctx) {
    setOpenMode(NotOpen);
    return false;
  }

  setOpenMode(mode);

  if (!(isReadable() || isWritable())) {
    setOpenMode(NotOpen);
    return false;
  }

  if (isWritable()) {

    if (d->m_recipients.empty()) {
      setOpenMode(NotOpen);
      return false;
    }

    // write out in ASCII armor mode
    d->ctx->setArmor(true);
    d->m_fileWrite = new QSaveFile;

  } else if (isReadable()) {
    d->m_fileRead = new QFile;
  }

  // open the 'physical' file
  // Since some of the methods in QFile are not virtual, we need to
  // differentiate here between the QFile* and the QSaveFile* case
  if (isReadable()) {
    d->m_fileRead->setFileName(d->m_fn);
    if (!d->m_fileRead->open(mode)) {
      setOpenMode(NotOpen);
      return false;
    }
    GpgME::Data dcipher(d->m_fileRead->handle());
    d->m_lastError = d->ctx->decrypt(dcipher, d->m_data).error();
    if (d->m_lastError.encodedError()) {
      return false;
    }
    d->m_data.seek(0, SEEK_SET);

  } else if (isWritable()) {
    d->m_fileWrite->setFileName(d->m_fn);
    if (!d->m_fileWrite->open(mode)) {
      setOpenMode(NotOpen);
      return false;
    }
  }

  return true;
}
Esempio n. 12
0
//---------------------------------------------------------------------------
void PacketFile::atClose (void)
{
	if (isOpen() && fileMode != READ)								// update filesize
	{
		long endPtr = getLength();
		
		//seek(sizeof(long));								//Move Past Version Marker
		//writeLong(endPtr);								//Write File length
	
		long tableEntry;
		currentPacket = numPackets;

		if (!seekTable)
		{
			while (--currentPacket >= 0)
			{
				seek(TABLE_ENTRY(currentPacket));
				tableEntry = readLong();
					
				if (GetPacketType(tableEntry) == STORAGE_TYPE_NUL)
				{
					seek(TABLE_ENTRY(currentPacket));
					writeLong(SetPacketType(endPtr,STORAGE_TYPE_NUL));
				}
				else
				{
					endPtr = GetPacketOffset(tableEntry);
				}
			}
		}
		else
		{
			while (--currentPacket >= 0)
			{
				tableEntry = seekTable[currentPacket];
					
				if (GetPacketType(tableEntry) == STORAGE_TYPE_NUL)
				{
					seekTable[currentPacket] = SetPacketType(endPtr,STORAGE_TYPE_NUL);
				}
				else
				{
					endPtr = GetPacketOffset(tableEntry);
				}
			}
		}

		//-----------------------------------------------------
		// If seekTable was being used, write it back to file
		if (seekTable)
		{
			seek(sizeof(long)*2);							//File Version & File Length
			write(MemoryPtr(seekTable),(numPackets*sizeof(long)));
		}

		//------------------------------------------------------
		// Is we were using a checkSum, calc it and write it to
		// the beginning of the file.
		if (usesCheckSum)
		{
			long checkSum = checkSumFile();
			seek(0);
			writeLong(checkSum);
		}
	}
	
	clear();
}
Esempio n. 13
0
bool MojDbIndex::canAnswer(const MojDbQuery& query) const
{
    LOG_TRACE("Entering function %s", __FUNCTION__);
	MojAssert(isOpen());
	MojAssert(!m_propNames.empty());

	// if this index is not ready yet, return false
	if (!m_ready)
		return false;

	// The goal here is to figure out whether the results for the query are contiguous in
	// the index. That will be the case if all the props referenced are contiguous in our
	// prop vector, any prop referenced by an inequality op comes at the end of the
	// range of referenced props, any unreferenced props in our vector are at the end,
	// and the order prop is either the last referenced prop or, if all ops are equality ops,
	// the prop following the last referenced prop.
	const MojDbQuery::WhereMap& map = query.where();
	MojSize numQueryProps = map.size();
	// if there are more props in the query than in our index, no can do
	if (numQueryProps > m_propNames.size())
		return false;
	// skip the first prop if we have an incDel index and the query does not reference the del prop
	StringVec::ConstIterator propName = m_propNames.begin();
	PropVec::ConstIterator prop = m_props.begin();
	if (m_includeDeleted && !map.contains(MojDb::DelKey)) {
		++propName;
		++prop;
	}
	// if there are no props in query, but the order matches our first prop, we're good
	const MojString& orderProp = query.order();
	if (numQueryProps == 0) {
		if (orderProp.empty()) {
			return isIdIndex();
		} else {
			return *propName == orderProp;
		}
	}
	// check all remaining props
	for (; propName != m_propNames.end(); ++propName, ++prop) {
		--numQueryProps;
		// ensure that the current prop is referenced in the query (no gaps)
		MojDbQuery::WhereMap::ConstIterator mapIter = map.find(*propName);
		if (mapIter == map.end())
			return false;
		// ensure that if it is an inequality op, it is at the end
		if (numQueryProps > 0 && mapIter->lowerOp() != MojDbQuery::OpEq)
			return false;
		// ensure that collation matches
		if (mapIter->collation() != (*prop)->collation())
			return false;
		// hooray, we made it through all the props in the query without failing any tests.
		// there may still be unreferenced props at the end of the vector, but that's ok.
		if (numQueryProps == 0) {
			// make sure that we can satisfy the ordering. if there is no ordering, or we are
			// ordering on a referenced prop, we're golden
			if (!orderProp.empty() && !map.contains(orderProp)) {
				// ensure that the order prop is next in our vec
				StringVec::ConstIterator next = propName + 1;
				if (next == m_propNames.end() || *next != orderProp)
					return false;
			}
			// can do!
			return true;
		}
	}
	return false;
}
Esempio n. 14
0
MojErr MojDbIndex::update(const MojObject* newObj, const MojObject* oldObj, MojDbStorageTxn* txn, bool forcedel)
{
    LOG_TRACE("Entering function %s", __FUNCTION__);
	MojAssert(isOpen());
	MojAssert(newObj || oldObj);

	// figure out which versions we include
	bool includeOld = includeObj(oldObj);
	bool includeNew = includeObj(newObj);

	if (includeNew && !includeOld) {
		// we include the new but not the old, so just put all the new keys
		MojAssert(newObj);
		KeySet newKeys;
		MojErr err = getKeys(*newObj, newKeys);
		MojErrCheck(err);
		err = insertKeys(newKeys, txn);
		MojErrCheck(err);
		err = notifyWatches(newKeys, txn);
		MojErrCheck(err);
        LOG_DEBUG("[db_mojodb] IndexAdd: %s; Keys= %zu \n", this->m_name.data(), newKeys.size());
	} else if (includeOld && !includeNew) {
		// we include the old but not the new objects, so del all the old keys
		MojAssert(oldObj);
		KeySet oldKeys;
		MojErr err = getKeys(*oldObj, oldKeys);
		MojErrCheck(err);
		err = delKeys(oldKeys, txn, forcedel);
		MojErrCheck(err);
		err = notifyWatches(oldKeys, txn);
		MojErrCheck(err);
        LOG_DEBUG("[db_mojodb] IndexDel: %s; Keys= %zu \n", this->name().data(), oldKeys.size());
	} else if (includeNew && includeOld) {
		// we include old and new objects
		MojAssert(newObj && oldObj);
		KeySet newKeys;
		MojErr err = getKeys(*newObj, newKeys);
		MojErrCheck(err);
		KeySet oldKeys;
		err = getKeys(*oldObj, oldKeys);
		MojErrCheck(err);
		// we need to put the keys that are in the new set, but not in the old
		KeySet keysToPut;
		err = newKeys.diff(oldKeys, keysToPut);
		MojErrCheck(err);
		// we need to del the keys that are in the old set, but not in the new
		KeySet keysToDel;
		err = oldKeys.diff(newKeys, keysToDel);
		MojErrCheck(err);
		err = insertKeys(keysToPut, txn);
		MojErrCheck(err);
		err = delKeys(keysToDel, txn, forcedel);
		
        LOG_DEBUG("[db_mojodb] IndexMerge: %s; OldKeys= %zu; NewKeys= %zu; Dropped= %zu; Added= %zu ; err = %d\n",
			this->name().data(), oldKeys.size(), newKeys.size(), keysToDel.size(), keysToPut.size(), (int)err);

		MojErrCheck(err);
		// notify on union of old and new keys
		err = newKeys.put(oldKeys);
		MojErrCheck(err);
		err = notifyWatches(newKeys, txn);
		MojErrCheck(err);
	
	}
	return MojErrNone;
}
Esempio n. 15
0
bool QFile::open( int m )
{
    if ( isOpen() ) {				// file already open
#if defined(CHECK_STATE)
	qWarning( "QFile::open: File already open" );
#endif
	return FALSE;
    }
    if ( fn.isNull() ) {			// no file name defined
#if defined(CHECK_NULL)
	qWarning( "QFile::open: No file name specified" );
#endif
	return FALSE;
    }
    init();					// reset params
    setMode( m );
    if ( !(isReadable() || isWritable()) ) {
#if defined(CHECK_RANGE)
	qWarning( "QFile::open: File access not specified" );
#endif
	return FALSE;
    }
    bool ok = TRUE;
    STATBUF st;
    if ( isRaw() ) {				// raw file I/O
	int oflags = OPEN_RDONLY;
	if ( isReadable() && isWritable() )
	    oflags = OPEN_RDWR;
	else if ( isWritable() )
	    oflags = OPEN_WRONLY;
	if ( flags() & IO_Append ) {		// append to end of file?
	    if ( flags() & IO_Truncate )
		oflags |= (OPEN_CREAT | OPEN_TRUNC);
	    else
		oflags |= (OPEN_APPEND | OPEN_CREAT);
	    setFlags( flags() | IO_WriteOnly ); // append implies write
	} else if ( isWritable() ) {		// create/trunc if writable
	    if ( flags() & IO_Truncate )
		oflags |= (OPEN_CREAT | OPEN_TRUNC);
	    else
		oflags |= OPEN_CREAT;
	}
#if defined(HAS_TEXT_FILEMODE)
	if ( isTranslated() )
	    oflags |= OPEN_TEXT;
	else
	    oflags |= OPEN_BINARY;
#endif
#if defined(HAS_ASYNC_FILEMODE)
	if ( isAsynchronous() )
	    oflags |= OPEN_ASYNC;
#endif
	fd = OPEN( QFile::encodeName(fn), oflags, 0666 );

	if ( fd != -1 ) {			// open successful
	    FSTAT( fd, &st ); // get the stat for later usage
	} else {
	    ok = FALSE;
	}
    } else {					// buffered file I/O
	QCString perm;
	char perm2[4];
	bool try_create = FALSE;
	if ( flags() & IO_Append ) {		// append to end of file?
	    setFlags( flags() | IO_WriteOnly ); // append implies write
	    perm = isReadable() ? "a+" : "a";
	} else {
	    if ( isReadWrite() ) {
		if ( flags() & IO_Truncate ) {
		    perm = "w+";
		} else {
		    perm = "r+";
		    try_create = TRUE;		// try to create if not exists
		}
	    } else if ( isReadable() ) {
		perm = "r";
	    } else if ( isWritable() ) {
		perm = "w";
	    }
	}
	qstrcpy( perm2, perm );
#if defined(HAS_TEXT_FILEMODE)
	if ( isTranslated() )
	    strcat( perm2, "t" );
	else
	    strcat( perm2, "b" );
#endif
	while (1) { // At most twice

	    fh = fopen( QFile::encodeName(fn), perm2 );

	    if ( !fh && try_create ) {
		perm2[0] = 'w';			// try "w+" instead of "r+"
		try_create = FALSE;
	    } else {
		break;
	    }
	}
	if ( fh ) {
	    FSTAT( FILENO(fh), &st ); // get the stat for later usage
	} else {
	    ok = FALSE;
	}
    }
    if ( ok ) {
	setState( IO_Open );
	// on successful open the file stat was got; now test what type
	// of file we have
	if ( (st.st_mode & STAT_MASK) != STAT_REG ) {
	    // non-seekable
	    setType( IO_Sequential );
	    length = INT_MAX;
	    ioIndex  = (flags() & IO_Append) == 0 ? 0 : length;
	} else {
	    length = (int)st.st_size;
	    ioIndex  = (flags() & IO_Append) == 0 ? 0 : length;
	    if ( !(flags()&IO_Truncate) && length == 0 && isReadable() ) {
		// try if you can read from it (if you can, it's a sequential
		// device; e.g. a file in the /proc filesystem)
		int c = getch();
		if ( c != -1 ) {
		    ungetch(c);
		    setType( IO_Sequential );
		    length = INT_MAX;
		}
	    }
	}
    } else {
	init();
	if ( errno == EMFILE )			// no more file handles/descrs
	    setStatus( IO_ResourceError );
	else
	    setStatus( IO_OpenError );
    }
    return ok;
}
Esempio n. 16
0
 void close() {
   if (isOpen()) {
     fclose(m_file_handle);
     m_file_handle = 0;
   }
 }
Esempio n. 17
0
void POP3Folder::fetchMessages(std::vector <ref <message> >& msg, const int options,
                               utility::progressListener* progress)
{
	ref <POP3Store> store = m_store.acquire();

	if (!store)
		throw exceptions::illegal_state("Store disconnected");
	else if (!isOpen())
		throw exceptions::illegal_state("Folder not open");

	const int total = msg.size();
	int current = 0;

	if (progress)
		progress->start(total);

	for (std::vector <ref <message> >::iterator it = msg.begin() ;
	     it != msg.end() ; ++it)
	{
		(*it).dynamicCast <POP3Message>()->fetch
			(thisRef().dynamicCast <POP3Folder>(), options);

		if (progress)
			progress->progress(++current, total);
	}

	if (options & FETCH_SIZE)
	{
		// Send the "LIST" command
		std::ostringstream command;
		command << "LIST";

		store->sendRequest(command.str());

		// Get the response
		ref <POP3Response> response =
			POP3Response::readMultilineResponse(store->m_socket, store->m_timeoutHandler);

		if (response->isSuccess())
		{
			// C: LIST
			// S: +OK
			// S: 1 47548
			// S: 2 12653
			// S: .
			std::map <int, string> result;
			POP3Utils::parseMultiListOrUidlResponse(response, result);

			for (std::vector <ref <message> >::iterator it = msg.begin() ;
			     it != msg.end() ; ++it)
			{
				ref <POP3Message> m = (*it).dynamicCast <POP3Message>();

				std::map <int, string>::const_iterator x = result.find(m->m_num);

				if (x != result.end())
				{
					int size = 0;

					std::istringstream iss((*x).second);
					iss >> size;

					m->m_size = size;
				}
			}
Esempio n. 18
0
Serial::~Serial()
{
    if( isOpen() )
        close();
}
Esempio n. 19
0
bool TPipe::peek() {
  return isOpen();
}
Esempio n. 20
0
/*!
Sets the number of data bits used by the serial port.  Possible values of dataBits are:
\verbatim
    DATA_5      5 data bits
    DATA_6      6 data bits
    DATA_7      7 data bits
    DATA_8      8 data bits
\endverbatim

\note
This function is subject to the following restrictions:
\par
    5 data bits cannot be used with 2 stop bits.
\par
    8 data bits cannot be used with space parity on POSIX systems.
*/
void QextSerialPort::setDataBits(DataBitsType dataBits)
{
    QMutexLocker lock(mutex);
    if (Settings.DataBits!=dataBits) {
        if ((Settings.StopBits==STOP_2 && dataBits==DATA_5) ||
            (Settings.StopBits==STOP_1_5 && dataBits!=DATA_5) ||
            (Settings.Parity==PAR_SPACE && dataBits==DATA_8)) {
        }
        else {
            Settings.DataBits=dataBits;
        }
    }
    if (isOpen()) {
        switch(dataBits) {

            /*5 data bits*/
            case DATA_5:
                if (Settings.StopBits==STOP_2) {
                    TTY_WARNING("QextSerialPort: 5 Data bits cannot be used with 2 stop bits.");
                }
                else {
                    Settings.DataBits=dataBits;
                    Posix_CommConfig.c_cflag&=(~CSIZE);
                    Posix_CommConfig.c_cflag|=CS5;
                    tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
                }
                break;

            /*6 data bits*/
            case DATA_6:
                if (Settings.StopBits==STOP_1_5) {
                    TTY_WARNING("QextSerialPort: 6 Data bits cannot be used with 1.5 stop bits.");
                }
                else {
                    Settings.DataBits=dataBits;
                    Posix_CommConfig.c_cflag&=(~CSIZE);
                    Posix_CommConfig.c_cflag|=CS6;
                    tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
                }
                break;

            /*7 data bits*/
            case DATA_7:
                if (Settings.StopBits==STOP_1_5) {
                    TTY_WARNING("QextSerialPort: 7 Data bits cannot be used with 1.5 stop bits.");
                }
                else {
                    Settings.DataBits=dataBits;
                    Posix_CommConfig.c_cflag&=(~CSIZE);
                    Posix_CommConfig.c_cflag|=CS7;
                    tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
                }
                break;

            /*8 data bits*/
            case DATA_8:
                if (Settings.StopBits==STOP_1_5) {
                    TTY_WARNING("QextSerialPort: 8 Data bits cannot be used with 1.5 stop bits.");
                }
                else {
                    Settings.DataBits=dataBits;
                    Posix_CommConfig.c_cflag&=(~CSIZE);
                    Posix_CommConfig.c_cflag|=CS8;
                    tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
                }
                break;
        }
    }
}
Esempio n. 21
0
void TPipe::write(const uint8_t* buf, uint32_t len) {
  if (!isOpen())
    throw TTransportException(TTransportException::NOT_OPEN, "Called write on non-open pipe");
  impl_->write(buf, len);
}
Esempio n. 22
0
/*!
Sets the parity associated with the serial port.  The possible values of parity are:
\verbatim
    PAR_SPACE       Space Parity
    PAR_MARK        Mark Parity
    PAR_NONE        No Parity
    PAR_EVEN        Even Parity
    PAR_ODD         Odd Parity
\endverbatim

\note
This function is subject to the following limitations:
\par
POSIX systems do not support mark parity.
\par
POSIX systems support space parity only if tricked into doing so, and only with
   fewer than 8 data bits.  Use space parity very carefully with POSIX systems.
*/
void QextSerialPort::setParity(ParityType parity)
{
    QMutexLocker lock(mutex);
    if (Settings.Parity!=parity) {
        if (parity==PAR_MARK || (parity==PAR_SPACE && Settings.DataBits==DATA_8)) {
        }
        else {
            Settings.Parity=parity;
        }
    }
    if (isOpen()) {
        switch (parity) {

            /*space parity*/
            case PAR_SPACE:
                if (Settings.DataBits==DATA_8) {
                    TTY_PORTABILITY_WARNING("QextSerialPort:  Space parity is only supported in POSIX with 7 or fewer data bits");
                }
                else {

                    /*space parity not directly supported - add an extra data bit to simulate it*/
                    Posix_CommConfig.c_cflag&=~(PARENB|CSIZE);
                    switch(Settings.DataBits) {
                        case DATA_5:
                            Settings.DataBits=DATA_6;
                            Posix_CommConfig.c_cflag|=CS6;
                            break;

                        case DATA_6:
                            Settings.DataBits=DATA_7;
                            Posix_CommConfig.c_cflag|=CS7;
                            break;

                        case DATA_7:
                            Settings.DataBits=DATA_8;
                            Posix_CommConfig.c_cflag|=CS8;
                            break;

                        case DATA_8:
                            break;
                    }
                    tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
                }
                break;

            /*mark parity - WINDOWS ONLY*/
            case PAR_MARK:
                TTY_WARNING("QextSerialPort: Mark parity is not supported by POSIX.");
                break;

            /*no parity*/
            case PAR_NONE:
                Posix_CommConfig.c_cflag&=(~PARENB);
                tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
                break;

            /*even parity*/
            case PAR_EVEN:
                Posix_CommConfig.c_cflag&=(~PARODD);
                Posix_CommConfig.c_cflag|=PARENB;
                tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
                break;

            /*odd parity*/
            case PAR_ODD:
                Posix_CommConfig.c_cflag|=(PARENB|PARODD);
                tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
                break;
        }
    }
}
Esempio n. 23
0
void ServerSocket::setReusePort(bool value)
{
	assert(isOpen() == false);
	reusePort_ = value;
}
Esempio n. 24
0
void CoreMidiOutputDevice::writeUniverse(const QByteArray& universe)
{
    if (isOpen() == false)
        return;

    Byte buffer[512]; // Should be enough for 128 channels
    MIDIPacketList* list = (MIDIPacketList*) buffer;
    MIDIPacket* packet = MIDIPacketListInit(list);

    /* Since MIDI devices can have only 128 real channels, we don't
       attempt to write more than that */
    for (Byte channel = 0; channel < MAX_MIDI_DMX_CHANNELS &&
                           channel < universe.size(); channel++)
    {
        Byte cmd[3];
        cmd[1] = channel;
        cmd[2] = DMX2MIDI(uchar(universe[channel]));

        /* Since MIDI is so slow, we only send values that are
           actually changed. */
        if (uchar(m_universe[channel]) == cmd[2])
            continue;

        /* Store the changed MIDI value. */
        m_universe[channel] = cmd[2];

        if (mode() == Note)
        {
            if (cmd[2] == 0)
            {
                /* Zero is sent as a note off command */
                cmd[0] = MIDI_NOTE_OFF;
            }
            else
            {
                /* 1-127 is sent as note on command */
                cmd[0] = MIDI_NOTE_ON;
            }
        }
        else if (mode() == ProgramChange)
        {
            /* Program change */
            cmd[0] = MIDI_PROGRAM_CHANGE;
        }
        else
        {
            /* Control change */
            cmd[0] = MIDI_CONTROL_CHANGE;
        }

        /* Encode MIDI channel to the command */
        cmd[0] |= (Byte) midiChannel();

        /* Add the MIDI command to the packet list */
        packet = MIDIPacketListAdd(list, sizeof(buffer), packet, 0, sizeof(cmd), cmd);
        if (packet == 0)
        {
            qWarning() << "MIDIOut buffer overflow";
            break;
        }
    }

    /* Send the MIDI packet list */
    OSStatus s = MIDISend(m_outPort, m_destination, list);
    if (s != 0)
        qWarning() << Q_FUNC_INFO << "Unable to send MIDI data to" << name();
}
 void paint (Graphics& g)
 {
     if (titleHeight > 0)
         getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
 }
Esempio n. 26
0
/*
   SQLite dbs have no user name, passwords, hosts or ports.
   just file names.
*/
bool QSQLiteDriver::open(const QString & db, const QString &, const QString &, const QString &, int, const QString &conOpts)
{
    if (isOpen())
        close();

    if (db.isEmpty())
        return false;
    bool sharedCache = false;
    int openMode = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, timeOut=5000;
    QStringList opts=QString(conOpts).remove(QLatin1Char(' ')).split(QLatin1Char(';'));
    foreach(const QString &option, opts) {
        if (option.startsWith(QLatin1String("QSQLITE_BUSY_TIMEOUT="))) {
            bool ok;
            int nt = option.mid(21).toInt(&ok);
            if (ok)
                timeOut = nt;
        }
        if (option == QLatin1String("QSQLITE_OPEN_READONLY"))
            openMode = SQLITE_OPEN_READONLY;
        if (option == QLatin1String("QSQLITE_ENABLE_SHARED_CACHE"))
            sharedCache = true;
    }

    sqlite3_enable_shared_cache(sharedCache);

#ifndef QT_WEBOS
    if (sqlite3_open_v2(db.toUtf8().constData(), &d->access, openMode, NULL) == SQLITE_OK) {
#else // QT_WEBOS
#if SQLITE_VERSION_NUMBER >= 3005000
    if (sqlite3_open_v2(db.toUtf8().constData(), &d->access, openMode, NULL) == SQLITE_OK) {
#else
	if (sqlite3_open(db.toUtf8().constData(), &d->access) == SQLITE_OK) {
#endif
#endif // QT_WEBOS
        sqlite3_busy_timeout(d->access, timeOut);
        setOpen(true);
        setOpenError(false);
        return true;
    } else {
        setLastError(qMakeError(d->access, tr("Error opening database"),
                     QSqlError::ConnectionError));
        setOpenError(true);
        return false;
    }
}

void QSQLiteDriver::close()
{
    if (isOpen()) {
        foreach (QSQLiteResult *result, d->results)
            result->d->finalize();

        if (sqlite3_close(d->access) != SQLITE_OK)
            setLastError(qMakeError(d->access, tr("Error closing database"),
                                    QSqlError::ConnectionError));
        d->access = 0;
        setOpen(false);
        setOpenError(false);
    }
}

QSqlResult *QSQLiteDriver::createResult() const
{
    return new QSQLiteResult(this);
}

bool QSQLiteDriver::beginTransaction()
{
    if (!isOpen() || isOpenError())
        return false;

    QSqlQuery q(createResult());
    if (!q.exec(QLatin1String("BEGIN"))) {
        setLastError(QSqlError(tr("Unable to begin transaction"),
                               q.lastError().databaseText(), QSqlError::TransactionError));
        return false;
    }

    return true;
}

bool QSQLiteDriver::commitTransaction()
{
    if (!isOpen() || isOpenError())
        return false;

    QSqlQuery q(createResult());
    if (!q.exec(QLatin1String("COMMIT"))) {
        setLastError(QSqlError(tr("Unable to commit transaction"),
                               q.lastError().databaseText(), QSqlError::TransactionError));
        return false;
    }

    return true;
}

bool QSQLiteDriver::rollbackTransaction()
{
    if (!isOpen() || isOpenError())
        return false;

    QSqlQuery q(createResult());
    if (!q.exec(QLatin1String("ROLLBACK"))) {
        setLastError(QSqlError(tr("Unable to rollback transaction"),
                               q.lastError().databaseText(), QSqlError::TransactionError));
        return false;
    }

    return true;
}

QStringList QSQLiteDriver::tables(QSql::TableType type) const
{
    QStringList res;
    if (!isOpen())
        return res;

    QSqlQuery q(createResult());
    q.setForwardOnly(true);

    QString sql = QLatin1String("SELECT name FROM sqlite_master WHERE %1 "
                                "UNION ALL SELECT name FROM sqlite_temp_master WHERE %1");
    if ((type & QSql::Tables) && (type & QSql::Views))
        sql = sql.arg(QLatin1String("type='table' OR type='view'"));
    else if (type & QSql::Tables)
        sql = sql.arg(QLatin1String("type='table'"));
    else if (type & QSql::Views)
        sql = sql.arg(QLatin1String("type='view'"));
    else
        sql.clear();

    if (!sql.isEmpty() && q.exec(sql)) {
        while(q.next())
            res.append(q.value(0).toString());
    }

    if (type & QSql::SystemTables) {
        // there are no internal tables beside this one:
        res.append(QLatin1String("sqlite_master"));
    }

    return res;
}

static QSqlIndex qGetTableInfo(QSqlQuery &q, const QString &tableName, bool onlyPIndex = false)
{
    QString schema;
    QString table(tableName);
    int indexOfSeparator = tableName.indexOf(QLatin1Char('.'));
    if (indexOfSeparator > -1) {
        schema = tableName.left(indexOfSeparator).append(QLatin1Char('.'));
        table = tableName.mid(indexOfSeparator + 1);
    }
    q.exec(QLatin1String("PRAGMA ") + schema + QLatin1String("table_info (") + _q_escapeIdentifier(table) + QLatin1String(")"));

    QSqlIndex ind;
    while (q.next()) {
        bool isPk = q.value(5).toInt();
        if (onlyPIndex && !isPk)
            continue;
        QString typeName = q.value(2).toString().toLower();
        QSqlField fld(q.value(1).toString(), qGetColumnType(typeName));
        if (isPk && (typeName == QLatin1String("integer")))
            // INTEGER PRIMARY KEY fields are auto-generated in sqlite
            // INT PRIMARY KEY is not the same as INTEGER PRIMARY KEY!
            fld.setAutoValue(true);
        fld.setRequired(q.value(3).toInt() != 0);
        fld.setDefaultValue(q.value(4));
        ind.append(fld);
    }
    return ind;
}
Esempio n. 27
0
void CRego6XXSerial::Do_Work()
{
	int sec_counter = 0;
	while (!m_stoprequested)
	{
		sleep_seconds(1);
		if (m_stoprequested)
			break;

		sec_counter++;

		if (sec_counter % 12 == 0) {
			m_LastHeartbeat=mytime(NULL);
		}

		if (!isOpen())
		{
			if (m_retrycntr==0)
			{
				_log.Log(LOG_STATUS,"Rego6XX: serial retrying in %d seconds...", Rego6XX_RETRY_DELAY);
			}
			m_retrycntr++;
			if (m_retrycntr>=Rego6XX_RETRY_DELAY)
			{
				m_retrycntr=0;
				m_pollcntr = 0;
				m_pollDelaycntr = 0;
				m_readBufferHead = 0;
				m_readBufferTail = 0;
				OpenSerialDevice();
			}
		}
		else if(m_errorcntr > Rego6XX_MAX_ERRORS_UNITL_RESTART)
        {
            // Reopen the port and clear the error counter.
			terminate();

		    _log.Log(LOG_ERROR,"Rego6XX: Reopening serial port");
		    sleep_seconds(2);

			m_retrycntr=0;
			m_pollcntr = 0;
			m_pollDelaycntr = 0;
			m_readBufferHead = 0;
			m_readBufferTail = 0;
            m_errorcntr = 0;

		    OpenSerialDevice();
        }
        else
		{
			m_pollDelaycntr++;

			if (m_pollDelaycntr>=Rego6XX_COMMAND_DELAY)
			{
                // Before issueing a new command, the recieve buffer must be empty.
                // It seems that there are errors sometimes and this will take care
                // of any problems even if it bypasses the circular buffer concept.
                // There should not be any data left to recieve anyway since commands
                // are sent with 5 seconds in between.
				m_readBufferHead = 0;
				m_readBufferTail = 0;

   				m_pollDelaycntr = 0;
				if(g_allRegisters[m_pollcntr].type != REGO_TYPE_NONE)
				{
					RegoCommand cmd;
					cmd.data.address = 0x81;
					cmd.data.command = 0x02;
                    switch(m_regoType)
                    {
                    case 0:
                        cmd.data.regNum[0] = (g_allRegisters[m_pollcntr].regNum_type1 & 0xC000) >> 14 ;
					    cmd.data.regNum[1] = (g_allRegisters[m_pollcntr].regNum_type1 & 0x3F80) >> 7 ;
					    cmd.data.regNum[2] = g_allRegisters[m_pollcntr].regNum_type1 & 0x007F;
                        break;
                    case 1:
                        cmd.data.regNum[0] = (g_allRegisters[m_pollcntr].regNum_type2 & 0xC000) >> 14 ;
					    cmd.data.regNum[1] = (g_allRegisters[m_pollcntr].regNum_type2 & 0x3F80) >> 7 ;
					    cmd.data.regNum[2] = g_allRegisters[m_pollcntr].regNum_type2 & 0x007F;
                        break;
                    case 2:
                        cmd.data.regNum[0] = (g_allRegisters[m_pollcntr].regNum_type3 & 0xC000) >> 14 ;
					    cmd.data.regNum[1] = (g_allRegisters[m_pollcntr].regNum_type3 & 0x3F80) >> 7 ;
					    cmd.data.regNum[2] = g_allRegisters[m_pollcntr].regNum_type3 & 0x007F;
                        break;
                    default:
		                _log.Log(LOG_ERROR,"Rego6XX: Unknown type!");
                        break;
                    }
					cmd.data.value[0] = 0;
					cmd.data.value[1] = 0;
					cmd.data.value[2] = 0;
					cmd.data.crc = 0;

					for ( int i = 2; i < 8; i++ )
						cmd.data.crc ^= cmd.raw[ i ];

					WriteToHardware((char*)cmd.raw, sizeof(cmd.raw));
				}
				else
				{
					m_pollcntr = 0;
				}
			}
Esempio n. 28
0
bool ossimHdfReader::open()
{
   static const char MODULE[] = "ossimHdfReader::open";

   if (traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << MODULE << " entered...\n"
         << "image: " << theImageFile << "\n";
   }

   bool result = false;

   if (!isSupportedExtension())
   {
      return false;
   }

   if (m_entryFileList.size() == 0)
   {
      if(isOpen())
      {
         close();
      }

      m_gdalTileSource = new ossimGdalTileSource;
      m_gdalTileSource->setFilename(theImageFile);

      if ( m_gdalTileSource->open() == false )
      {
         m_gdalTileSource = 0;
         return false;
      }

      std::vector<ossimString> entryStringList;
      if (m_gdalTileSource != 0)
      {
         m_gdalTileSource->getEntryNames(entryStringList);
      }
      
      // bool isSwathImage = false;
      if (entryStringList.size() > 0)
      {
         for (ossim_uint32 i = 0; i < entryStringList.size(); i++)
         {
            m_entryFileList.push_back(i);
         }
      }
      else
      {
        result = false;
      }
   }
      
   //set entry id for the gdal tile source
   if (m_currentEntryRender < m_entryFileList.size())
   {
      
      m_gdalTileSource->setCurrentEntry(m_currentEntryRender);
      m_numberOfBands = m_gdalTileSource->getNumberOfInputBands();

      m_tile = ossimImageDataFactory::instance()->create(this, this);
      m_tile->initialize();
      
      completeOpen();
      result = true;
   }
   else
   {
      result = false;
   }
   
   if (result == false)
   {
      close();
   }
   
   if (traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << MODULE << " exit status = " << (result?"true":"false\n")
         << std::endl;
   }
   
   return result;
}
/*!
\fn void Posix_QextSerialPort::setBaudRate(BaudRateType baudRate)
Sets the baud rate of the serial port.  Note that not all rates are applicable on
all platforms.  The following table shows translations of the various baud rate
constants on Windows(including NT/2000) and POSIX platforms.  Speeds marked with an *
are speeds that are usable on both Windows and POSIX.

\note
BAUD76800 may not be supported on all POSIX systems.  SGI/IRIX systems do not support
BAUD1800.

\verbatim

  RATE          Windows Speed   POSIX Speed
  -----------   -------------   -----------
   BAUD50                 110          50
   BAUD75                 110          75
  *BAUD110                110         110
   BAUD134                110         134.5
   BAUD150                110         150
   BAUD200                110         200
  *BAUD300                300         300
  *BAUD600                600         600
  *BAUD1200              1200        1200
   BAUD1800              1200        1800
  *BAUD2400              2400        2400
  *BAUD4800              4800        4800
  *BAUD9600              9600        9600
   BAUD14400            14400        9600
  *BAUD19200            19200       19200
  *BAUD38400            38400       38400
   BAUD56000            56000       38400
  *BAUD57600            57600       57600
   BAUD76800            57600       76800
  *BAUD115200          115200      115200
   BAUD128000          128000      115200
   BAUD230400          230400      115200
   BAUD256000          256000      115200
   BAUD460800          460800      115200
   BAUD921600          921600      115200
\endverbatim
*/
void Posix_QextSerialPort::setBaudRate(BaudRateType baudRate)
{
    LOCK_MUTEX();
    if (Settings.BaudRate!=baudRate) {
        switch (baudRate) {
        case BAUD14400:
            Settings.BaudRate=BAUD9600;
            break;

        case BAUD56000:
            Settings.BaudRate=BAUD38400;
            break;

        case BAUD76800:

#ifndef B76800
            Settings.BaudRate=BAUD57600;
#else
            Settings.BaudRate=baudRate;
#endif
            break;

        case BAUD128000:
        case BAUD230400:
        case BAUD460800:
        case BAUD921600:
        case BAUD256000:
            Settings.BaudRate=BAUD115200;
            break;

        default:
            Settings.BaudRate=baudRate;
            break;
        }
    }
    if (isOpen()) {
        switch (baudRate) {

            /*50 baud*/
        case BAUD50:
            TTY_PORTABILITY_WARNING("Posix_QextSerialPort Portability Warning: Windows does not support 50 baud operation.");
#ifdef CBAUD
            Posix_CommConfig.c_cflag&=(~CBAUD);
            Posix_CommConfig.c_cflag|=B50;
#else
            cfsetispeed(&Posix_CommConfig, B50);
            cfsetospeed(&Posix_CommConfig, B50);
#endif
            break;

            /*75 baud*/
        case BAUD75:
            TTY_PORTABILITY_WARNING("Posix_QextSerialPort Portability Warning: Windows does not support 75 baud operation.");
#ifdef CBAUD
            Posix_CommConfig.c_cflag&=(~CBAUD);
            Posix_CommConfig.c_cflag|=B75;
#else
            cfsetispeed(&Posix_CommConfig, B75);
            cfsetospeed(&Posix_CommConfig, B75);
#endif
            break;

            /*110 baud*/
        case BAUD110:
#ifdef CBAUD
            Posix_CommConfig.c_cflag&=(~CBAUD);
            Posix_CommConfig.c_cflag|=B110;
#else
            cfsetispeed(&Posix_CommConfig, B110);
            cfsetospeed(&Posix_CommConfig, B110);
#endif
            break;

            /*134.5 baud*/
        case BAUD134:
            TTY_PORTABILITY_WARNING("Posix_QextSerialPort Portability Warning: Windows does not support 134.5 baud operation.");
#ifdef CBAUD
            Posix_CommConfig.c_cflag&=(~CBAUD);
            Posix_CommConfig.c_cflag|=B134;
#else
            cfsetispeed(&Posix_CommConfig, B134);
            cfsetospeed(&Posix_CommConfig, B134);
#endif
            break;

            /*150 baud*/
        case BAUD150:
            TTY_PORTABILITY_WARNING("Posix_QextSerialPort Portability Warning: Windows does not support 150 baud operation.");
#ifdef CBAUD
            Posix_CommConfig.c_cflag&=(~CBAUD);
            Posix_CommConfig.c_cflag|=B150;
#else
            cfsetispeed(&Posix_CommConfig, B150);
            cfsetospeed(&Posix_CommConfig, B150);
#endif
            break;

            /*200 baud*/
        case BAUD200:
            TTY_PORTABILITY_WARNING("Posix_QextSerialPort Portability Warning: Windows does not support 200 baud operation.");
#ifdef CBAUD
            Posix_CommConfig.c_cflag&=(~CBAUD);
            Posix_CommConfig.c_cflag|=B200;
#else
            cfsetispeed(&Posix_CommConfig, B200);
            cfsetospeed(&Posix_CommConfig, B200);
#endif
            break;

            /*300 baud*/
        case BAUD300:
#ifdef CBAUD
            Posix_CommConfig.c_cflag&=(~CBAUD);
            Posix_CommConfig.c_cflag|=B300;
#else
            cfsetispeed(&Posix_CommConfig, B300);
            cfsetospeed(&Posix_CommConfig, B300);
#endif
            break;

            /*600 baud*/
        case BAUD600:
#ifdef CBAUD
            Posix_CommConfig.c_cflag&=(~CBAUD);
            Posix_CommConfig.c_cflag|=B600;
#else
            cfsetispeed(&Posix_CommConfig, B600);
            cfsetospeed(&Posix_CommConfig, B600);
#endif
            break;

            /*1200 baud*/
        case BAUD1200:
#ifdef CBAUD
            Posix_CommConfig.c_cflag&=(~CBAUD);
            Posix_CommConfig.c_cflag|=B1200;
#else
            cfsetispeed(&Posix_CommConfig, B1200);
            cfsetospeed(&Posix_CommConfig, B1200);
#endif
            break;

            /*1800 baud*/
        case BAUD1800:
            TTY_PORTABILITY_WARNING("Posix_QextSerialPort Portability Warning: Windows and IRIX do not support 1800 baud operation.");
#ifdef CBAUD
            Posix_CommConfig.c_cflag&=(~CBAUD);
            Posix_CommConfig.c_cflag|=B1800;
#else
            cfsetispeed(&Posix_CommConfig, B1800);
            cfsetospeed(&Posix_CommConfig, B1800);
#endif
            break;

            /*2400 baud*/
        case BAUD2400:
#ifdef CBAUD
            Posix_CommConfig.c_cflag&=(~CBAUD);
            Posix_CommConfig.c_cflag|=B2400;
#else
            cfsetispeed(&Posix_CommConfig, B2400);
            cfsetospeed(&Posix_CommConfig, B2400);
#endif
            break;

            /*4800 baud*/
        case BAUD4800:
#ifdef CBAUD
            Posix_CommConfig.c_cflag&=(~CBAUD);
            Posix_CommConfig.c_cflag|=B4800;
#else
            cfsetispeed(&Posix_CommConfig, B4800);
            cfsetospeed(&Posix_CommConfig, B4800);
#endif
            break;

            /*9600 baud*/
        case BAUD9600:
#ifdef CBAUD
            Posix_CommConfig.c_cflag&=(~CBAUD);
            Posix_CommConfig.c_cflag|=B9600;
#else
            cfsetispeed(&Posix_CommConfig, B9600);
            cfsetospeed(&Posix_CommConfig, B9600);
#endif
            break;

            /*14400 baud*/
        case BAUD14400:
            TTY_WARNING("Posix_QextSerialPort: POSIX does not support 14400 baud operation.  Switching to 9600 baud.");
#ifdef CBAUD
            Posix_CommConfig.c_cflag&=(~CBAUD);
            Posix_CommConfig.c_cflag|=B9600;
#else
            cfsetispeed(&Posix_CommConfig, B9600);
            cfsetospeed(&Posix_CommConfig, B9600);
#endif
            break;

            /*19200 baud*/
        case BAUD19200:
#ifdef CBAUD
            Posix_CommConfig.c_cflag&=(~CBAUD);
            Posix_CommConfig.c_cflag|=B19200;
#else
            cfsetispeed(&Posix_CommConfig, B19200);
            cfsetospeed(&Posix_CommConfig, B19200);
#endif
            break;

            /*38400 baud*/
        case BAUD38400:
#ifdef CBAUD
            Posix_CommConfig.c_cflag&=(~CBAUD);
            Posix_CommConfig.c_cflag|=B38400;
#else
            cfsetispeed(&Posix_CommConfig, B38400);
            cfsetospeed(&Posix_CommConfig, B38400);
#endif
            break;

            /*56000 baud*/
        case BAUD56000:
            TTY_WARNING("Posix_QextSerialPort: POSIX does not support 56000 baud operation.  Switching to 38400 baud.");
#ifdef CBAUD
            Posix_CommConfig.c_cflag&=(~CBAUD);
            Posix_CommConfig.c_cflag|=B38400;
#else
            cfsetispeed(&Posix_CommConfig, B38400);
            cfsetospeed(&Posix_CommConfig, B38400);
#endif
            break;

            /*57600 baud*/
        case BAUD57600:
#ifdef CBAUD
            Posix_CommConfig.c_cflag&=(~CBAUD);
            Posix_CommConfig.c_cflag|=B57600;
#else
            cfsetispeed(&Posix_CommConfig, B57600);
            cfsetospeed(&Posix_CommConfig, B57600);
#endif
            break;

            /*76800 baud*/
        case BAUD76800:
            TTY_PORTABILITY_WARNING("Posix_QextSerialPort Portability Warning: Windows and some POSIX systems do not support 76800 baud operation.");
#ifdef CBAUD
            Posix_CommConfig.c_cflag&=(~CBAUD);

#ifdef B76800
            Posix_CommConfig.c_cflag|=B76800;
#else
            TTY_WARNING("Posix_QextSerialPort: Posix_QextSerialPort was compiled without 76800 baud support.  Switching to 57600 baud.");
            Posix_CommConfig.c_cflag|=B57600;
#endif //B76800
#else  //CBAUD
#ifdef B76800
            cfsetispeed(&Posix_CommConfig, B76800);
            cfsetospeed(&Posix_CommConfig, B76800);
#else
            TTY_WARNING("Posix_QextSerialPort: Posix_QextSerialPort was compiled without 76800 baud support.  Switching to 57600 baud.");
            cfsetispeed(&Posix_CommConfig, B57600);
            cfsetospeed(&Posix_CommConfig, B57600);
#endif //B76800
#endif //CBAUD
            break;

            /*115200 baud*/
        case BAUD115200:
#ifdef CBAUD
            Posix_CommConfig.c_cflag&=(~CBAUD);
            Posix_CommConfig.c_cflag|=B115200;
#else
            cfsetispeed(&Posix_CommConfig, B115200);
            cfsetospeed(&Posix_CommConfig, B115200);
#endif
            break;

            /*128000 baud*/
        case BAUD128000:
            TTY_WARNING("Posix_QextSerialPort: POSIX does not support 128000 baud operation.  Switching to 115200 baud.");
#ifdef CBAUD
            Posix_CommConfig.c_cflag&=(~CBAUD);
            Posix_CommConfig.c_cflag|=B115200;
#else
            cfsetispeed(&Posix_CommConfig, B115200);
            cfsetospeed(&Posix_CommConfig, B115200);
#endif
            break;

            /*256000 baud*/
        case BAUD230400:
        case BAUD460800:
        case BAUD921600:
        case BAUD256000:
            TTY_WARNING("Posix_QextSerialPort: POSIX does not support baud rates above 115200 baud.  Switching to 115200 baud.");
#ifdef CBAUD
            Posix_CommConfig.c_cflag&=(~CBAUD);
            Posix_CommConfig.c_cflag|=B115200;
#else
            cfsetispeed(&Posix_CommConfig, B115200);
            cfsetospeed(&Posix_CommConfig, B115200);
#endif
            break;
        }
        tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
    }
    UNLOCK_MUTEX();
}
Esempio n. 30
0
QLCFTDI::~QLCFTDI()
{
    if (isOpen() == true)
        close();
}