Exemplo n.º 1
0
bool QSerialPort::open(int block)
{
	if( block== 1) portDesc = ::open(portName.toAscii(),O_RDWR);
	else portDesc = ::open(portName.toAscii(),O_RDWR | O_NONBLOCK );
	if(portDesc == -1)
	{
		return false;
	}
	portOpen = true;

	tcgetattr(portDesc, &portConfig);
	
	portConfig.c_cflag|=(CLOCAL | CREAD);
	portConfig.c_lflag&=(~(ICANON|ECHO|ECHOE|ECHOK|ECHONL|ISIG));
	portConfig.c_iflag&=(~(IGNBRK|BRKINT|PARMRK|ISTRIP |INLCR| IGNCR|ICRNL|IXON)); //  (~(INPCK|IGNPAR|PARMRK|ISTRIP|IXANY));
	portConfig.c_iflag&=~(ICRNL);

	portConfig.c_oflag&=(~OPOST);
	
	tcsetattr(portDesc, TCSANOW, &portConfig);

	setBaudRate(settings.baudRate);
	setDataBits(settings.dataBits);
	setFlowControl(settings.flowControl);
	setParity(settings.parity);
	setStopBits(settings.stopBits);
	setDtr();
	setRts();

	connect(&portFile, SIGNAL(readyRead()), this, SLOT(slotNotifierActivated()));

	return true;
}
Exemplo n.º 2
0
/*!
\fn bool Posix_QextSerialPort::open(int=0)
Opens a serial port.  Note that this function does not specify which device to open.  If you need
to open a device by name, see Posix_QextSerialPort::open(const char*).  This function has no 
effect if the port associated with the class is already open.  The port is also configured to the 
current settings, as stored in the Settings structure.
*/
bool Posix_QextSerialPort::open(int) {
    LOCK_MUTEX();
    if (!portOpen) {

        /*open the port*/
        Posix_File->setName(portName);
        if (Posix_File->open(IO_Async|IO_Raw|IO_ReadWrite)) {
            portOpen=true;
        }

        /*configure port settings*/
        tcgetattr(Posix_File->handle(), &Posix_CommConfig);

        /*set up other port settings*/
        Posix_CommConfig.c_cflag|=CREAD|CLOCAL;
        Posix_CommConfig.c_lflag&=(~(ICANON|ECHO|ECHOE|ECHOK|ECHONL|ISIG));
        Posix_CommConfig.c_iflag&=(~(INPCK|IGNPAR|PARMRK|ISTRIP|IXANY));
        Posix_CommConfig.c_oflag&=(~OPOST);
        Posix_CommConfig.c_cc[VMIN]=0;
        Posix_CommConfig.c_cc[VINTR] = _POSIX_VDISABLE; 
        Posix_CommConfig.c_cc[VQUIT] = _POSIX_VDISABLE; 
        Posix_CommConfig.c_cc[VSTART] = _POSIX_VDISABLE; 
        Posix_CommConfig.c_cc[VSTOP] = _POSIX_VDISABLE; 
        Posix_CommConfig.c_cc[VSUSP] = _POSIX_VDISABLE; 
        setBaudRate(Settings.BaudRate);
        setDataBits(Settings.DataBits);
        setStopBits(Settings.StopBits);
        setParity(Settings.Parity);
        setFlowControl(Settings.FlowControl);
        setTimeout(Posix_Copy_Timeout.tv_sec, Posix_Copy_Timeout.tv_usec);
        tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig);
    }
    UNLOCK_MUTEX();
    return portOpen;
}
Exemplo n.º 3
0
/**
 * Инициализация COM порта
 */
int FtdiDevices::Initialization() {

  int state = 0;

  if ( !openDSUSession() )          state = 1;
  if ( !reset() )                   state = 1;
  if ( !setSpeed(115200) )          state = 1;
  if ( !setDataCharacteristics() )  state = 1;
  if ( !getModemStatus() )          state = 1;

  setEventNotification();
  setDtrRts();
  purge();

  if ( !setFlowControl() ) state = 1;

  QString msg;
  int type;

  if ( state == 1 ) {
    msg  = "Не могу открыть устройство( COM порт A )!" ;
    type = appLogger.ERROR_MSG_TYPE;
  }
  else {
    msg  = "Устройство открыто успешно( COM порт A )!";
    type = appLogger.INFO_MSG_TYPE;
  }

  /* Запись в лог сообщения */
  appLogger.sendDataToViewer( type, msg, appLogger.SYSTEM_LOGGER );

  return state;
}
Exemplo n.º 4
0
/* uploadFile() - uploads a file to a FTP server
 *
 * This function uploads a file to a FTP server
 *
 * Returns '1' on success and '0' if error
*/
uint8_t WaspGPRS::downloadFile(char* file, char* path, char* user, char* passw, char* ftp_server, uint8_t ftp_port)
{
	char command[70];
	long previous=0;
	uint8_t answer=0;
	char aux='"';
	uint16_t index=0;
	uint16_t i=0;
	uint8_t end=0;
	char* aux2;
	uint8_t j=0;
	uint8_t id=0;
	
	if(!setFlowControl()) return 0;
			
	if(!configureGPRS()) return 0;
		
	// Connect to FTP Server
	sprintf(command,"AT%s,%c%s%c,%c%s%c,%c%s%c,%u,1%c%c",AT_FTP_PARAM,aux,ftp_server,aux,aux,user,aux,aux,passw,aux,ftp_port,'\r','\n');
	printString(command,PORT_USED);
	previous=millis();
	while( (!serialAvailable(PORT_USED)) && ((millis()-previous)<10000) );
	delay(10);
	answer=waitForData("+KFTPCFG: ",20,0,0);
	if(answer!=1) return 0;
		
	id=serialRead(PORT_USED);
	
	if( !readDataFTP(file, path, id) ) return 0;
	
	return 1;
}
/*!
\fn bool Win_QextSerialPort::open(OpenMode mode)
Opens a serial port.  Note that this function does not specify which device to open.  If you need
to open a device by name, see Win_QextSerialPort::open(const char*).  This function has no effect
if the port associated with the class is already open.  The port is also configured to the current
settings, as stored in the Settings structure.
*/
bool Win_QextSerialPort::open(OpenMode mode) {
	unsigned long confSize = sizeof(COMMCONFIG);
	Win_CommConfig.dwSize = confSize;
	DWORD dwFlagsAndAttributes = 0;
	if (queryMode() == QextSerialBase::EventDriven)
		dwFlagsAndAttributes += FILE_FLAG_OVERLAPPED;

    LOCK_MUTEX();
    if (mode == QIODevice::NotOpen)
        return isOpen();
    if (!isOpen()) {
        /*open the port*/
        Win_Handle=CreateFileA(port.toLatin1(), GENERIC_READ|GENERIC_WRITE,
                              FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, dwFlagsAndAttributes, NULL);
        if (Win_Handle!=INVALID_HANDLE_VALUE)
        {
            /*configure port settings*/
            GetCommConfig(Win_Handle, &Win_CommConfig, &confSize);
            GetCommState(Win_Handle, &(Win_CommConfig.dcb));

            /*set up parameters*/
            Win_CommConfig.dcb.fBinary=TRUE;
            Win_CommConfig.dcb.fInX=FALSE;
            Win_CommConfig.dcb.fOutX=FALSE;
            Win_CommConfig.dcb.fAbortOnError=FALSE;
            Win_CommConfig.dcb.fNull=FALSE;
            setBaudRate(Settings.BaudRate);
            setDataBits(Settings.DataBits);
            setStopBits(Settings.StopBits);
            setParity(Settings.Parity);
            setFlowControl(Settings.FlowControl);
            setTimeout(Settings.Timeout_Millisec);
            SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG));

            //init event driven approach
			if (queryMode() == QextSerialBase::EventDriven) {
		        Win_CommTimeouts.ReadIntervalTimeout = MAXDWORD;
		        Win_CommTimeouts.ReadTotalTimeoutMultiplier = 0;
		        Win_CommTimeouts.ReadTotalTimeoutConstant = 0;
				Win_CommTimeouts.WriteTotalTimeoutMultiplier = 0;
				Win_CommTimeouts.WriteTotalTimeoutConstant = 0;
				SetCommTimeouts(Win_Handle, &Win_CommTimeouts);
            	if (!SetCommMask( Win_Handle, EV_TXEMPTY | EV_RXCHAR | EV_DSR)) {
            		qWarning("Failed to set Comm Mask. Error code: %ld", GetLastError());
					UNLOCK_MUTEX();
            		return false;
            	}
            	overlapThread->start();
            }
			QIODevice::open(mode);
        }
    } else {
		UNLOCK_MUTEX();
    	return false;
    }
    UNLOCK_MUTEX();
    return isOpen();
}
Exemplo n.º 6
0
/*! \brief SerialDevice::stopDevice Is the serial interface's implementation of setDefaults.
 * Sets the serial devices to the default values. (Rate=9600, Parity=None, Flow=None, Data=8, Stop=1)
 */
void SerialDevice::setDefaults()
{
    statusReady = false;
    setBaudRate(9600);
    setParity(0);
    setFlowControl(0);
    setDataBits(8);
    setStopBits(1);
}
Exemplo n.º 7
0
/*!
		\fn Win_QextSerialPort::Win_QextSerialPort(const PortSettings& settings)
			Constructs a port with default name and specified settings.
*/
Win_QextSerialPort::Win_QextSerialPort(const PortSettings& settings) {
	Win_Handle=INVALID_HANDLE_VALUE;
	setBaudRate(settings.BaudRate);
	setDataBits(settings.DataBits);
	setStopBits(settings.StopBits);
	setParity(settings.Parity);
	setFlowControl(settings.FlowControl);
	setTimeout(settings.Timeout_Sec, settings.Timeout_Millisec);
}
Exemplo n.º 8
0
/*!
Sets the port settigns.
*/
void QextSerialPort::setPortSetting(const PortSettings& settings)
{
    setBaudRate(settings.BaudRate);
    setDataBits(settings.DataBits);
    setParity(settings.Parity);
    setStopBits(settings.StopBits);
    setFlowControl(settings.FlowControl);
    setTimeout(settings.Timeout_Millisec);
}
Exemplo n.º 9
0
/*!
Opens a serial port.  Note that this function does not specify which device to open.  If you need
to open a device by name, see QextSerialPort::open(const char*).  This function has no effect
if the port associated with the class is already open.  The port is also configured to the current
settings, as stored in the Settings structure.
*/
bool QextSerialPort::open(OpenMode mode) {
    unsigned long confSize = sizeof(COMMCONFIG);
    Win_CommConfig.dwSize = confSize;
    DWORD dwFlagsAndAttributes = 0;
    if (queryMode() == QextSerialPort::EventDriven)
        dwFlagsAndAttributes += FILE_FLAG_OVERLAPPED;

    QMutexLocker lock(mutex);
    if (mode == QIODevice::NotOpen)
        return isOpen();
    if (!isOpen()) {
        /*open the port*/
        Win_Handle=CreateFileA(port.toAscii(), GENERIC_READ|GENERIC_WRITE,
                              0, NULL, OPEN_EXISTING, dwFlagsAndAttributes, NULL);
        if (Win_Handle!=INVALID_HANDLE_VALUE) {
            QIODevice::open(mode);
            /*configure port settings*/
            GetCommConfig(Win_Handle, &Win_CommConfig, &confSize);
            GetCommState(Win_Handle, &(Win_CommConfig.dcb));

            /*set up parameters*/
            Win_CommConfig.dcb.fBinary=TRUE;
            Win_CommConfig.dcb.fInX=FALSE;
            Win_CommConfig.dcb.fOutX=FALSE;
            Win_CommConfig.dcb.fAbortOnError=FALSE;
            Win_CommConfig.dcb.fNull=FALSE;
            setBaudRate(Settings.BaudRate);
            setDataBits(Settings.DataBits);
            setStopBits(Settings.StopBits);
            setParity(Settings.Parity);
            setFlowControl(Settings.FlowControl);
            setTimeout(Settings.Timeout_Millisec);
            SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG));

            //init event driven approach
            if (queryMode() == QextSerialPort::EventDriven) {
                Win_CommTimeouts.ReadIntervalTimeout = MAXDWORD;
                Win_CommTimeouts.ReadTotalTimeoutMultiplier = 0;
                Win_CommTimeouts.ReadTotalTimeoutConstant = 0;
                Win_CommTimeouts.WriteTotalTimeoutMultiplier = 0;
                Win_CommTimeouts.WriteTotalTimeoutConstant = 0;
                SetCommTimeouts(Win_Handle, &Win_CommTimeouts);
                if (!SetCommMask( Win_Handle, EV_TXEMPTY | EV_RXCHAR | EV_DSR)) {
                    qWarning() << "failed to set Comm Mask. Error code:", GetLastError();
                    return false;
                }
                winEventNotifier = new QWinEventNotifier(overlap.hEvent, this);
                connect(winEventNotifier, SIGNAL(activated(HANDLE)), this, SLOT(onWinEvent(HANDLE)));
                WaitCommEvent(Win_Handle, &eventMask, &overlap);
            }
        }
    } else {
        return false;
    }
    return isOpen();
}
Exemplo n.º 10
0
/*!
Opens the serial port associated to this class.
This function has no effect if the port associated with the class is already open.
The port is also configured to the current settings, as stored in the Settings structure.
*/
bool QextSerialPort::open(OpenMode mode)
{
    QMutexLocker lock(mutex);
    if (mode == QIODevice::NotOpen)
        return isOpen();
    if (!isOpen()) {
        qDebug() << "trying to open file" << port.toAscii();
        //note: linux 2.6.21 seems to ignore O_NDELAY flag
        if ((fd = ::open(port.toAscii() ,O_RDWR | O_NOCTTY | O_NDELAY)) != -1) {
            qDebug("file opened succesfully");

            setOpenMode(mode);              // Flag the port as opened
            tcgetattr(fd, &old_termios);    // Save the old termios
            Posix_CommConfig = old_termios; // Make a working copy


            /* the equivelent of cfmakeraw() to enable raw access */
#ifdef HAVE_CFMAKERAW
            cfmakeraw(&Posix_CommConfig);   // Enable raw access
#else
            Posix_CommConfig.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP
                                    | INLCR | IGNCR | ICRNL | IXON);
            Posix_CommConfig.c_oflag &= ~OPOST;
            Posix_CommConfig.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
            Posix_CommConfig.c_cflag &= ~(CSIZE | PARENB);
            Posix_CommConfig.c_cflag |= CS8;
#endif

            /*set up other port settings*/
            Posix_CommConfig.c_cflag|=CREAD|CLOCAL;
            Posix_CommConfig.c_lflag&=(~(ICANON|ECHO|ECHOE|ECHOK|ECHONL|ISIG));
            Posix_CommConfig.c_iflag&=(~(INPCK|IGNPAR|PARMRK|ISTRIP|ICRNL|IXANY));
            Posix_CommConfig.c_oflag&=(~OPOST);
            Posix_CommConfig.c_cc[VMIN]= 0;
#ifdef _POSIX_VDISABLE  // Is a disable character available on this system?
            // Some systems allow for per-device disable-characters, so get the
            //  proper value for the configured device
            const long vdisable = fpathconf(fd, _PC_VDISABLE);
            Posix_CommConfig.c_cc[VINTR] = vdisable;
            Posix_CommConfig.c_cc[VQUIT] = vdisable;
            Posix_CommConfig.c_cc[VSTART] = vdisable;
            Posix_CommConfig.c_cc[VSTOP] = vdisable;
            Posix_CommConfig.c_cc[VSUSP] = vdisable;
#endif //_POSIX_VDISABLE
            setBaudRate(Settings.BaudRate);
            setDataBits(Settings.DataBits);
            setParity(Settings.Parity);
            setStopBits(Settings.StopBits);
            setFlowControl(Settings.FlowControl);
            setTimeout(Settings.Timeout_Millisec);
            tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);

            if (queryMode() == QextSerialPort::EventDriven) {
                readNotifier = new QSocketNotifier(fd, QSocketNotifier::Read, this);
                connect(readNotifier, SIGNAL(activated(int)), this, SIGNAL(readyRead()));
            }
Exemplo n.º 11
0
/*!
\fn Posix_QextSerialPort::Posix_QextSerialPort(const char* name, const PortSettings& settings)
Constructs a port with specified name and settings.
*/
Posix_QextSerialPort::Posix_QextSerialPort(const char* name, const PortSettings& settings)
                     :QextSerialBase(name) {
    construct();
    setBaudRate(settings.BaudRate);
    setDataBits(settings.DataBits);
    setStopBits(settings.StopBits);
    setParity(settings.Parity);
    setFlowControl(settings.FlowControl);
    setTimeout(settings.Timeout_Sec, settings.Timeout_Millisec);
}
/*!
\fn bool Posix_QextSerialPort::open(OpenMode mode)
Opens the serial port associated to this class.
This function has no effect if the port associated with the class is already open.
The port is also configured to the current settings, as stored in the Settings structure.
*/
bool Posix_QextSerialPort::open(OpenMode mode)
{
    LOCK_MUTEX();
    if (mode == QIODevice::NotOpen)
    {
        UNLOCK_MUTEX();
        return isOpen();
    }

    if (!isOpen())
    {
        /*open the port*/
        Posix_File->setFileName(port);
        QueueReceiveSignals = 10;
        if (Posix_File->open(QIODevice::ReadWrite | QIODevice::Unbuffered))
        {
            /*set open mode*/
            QIODevice::open(mode);

            /*configure port settings*/
            tcgetattr(Posix_File->handle(), &Posix_CommConfig);

            /*set up other port settings*/
            Posix_CommConfig.c_cflag|=CREAD|CLOCAL;
            Posix_CommConfig.c_lflag&=(~(ICANON|ECHO|ECHOE|ECHOK|ECHONL|ISIG));
            Posix_CommConfig.c_iflag&=(~(INPCK|IGNPAR|IGNBRK|PARMRK|ISTRIP|ICRNL|IXANY));
            Posix_CommConfig.c_oflag&=(~OPOST);
            Posix_CommConfig.c_cc[VMIN]=0;
            Posix_CommConfig.c_cc[VINTR] = _POSIX_VDISABLE;
            Posix_CommConfig.c_cc[VQUIT] = _POSIX_VDISABLE;
            Posix_CommConfig.c_cc[VSTART] = _POSIX_VDISABLE;
            Posix_CommConfig.c_cc[VSTOP] = _POSIX_VDISABLE;
            Posix_CommConfig.c_cc[VSUSP] = _POSIX_VDISABLE;
            setBaudRate(Settings.BaudRate);
            setDataBits(Settings.DataBits);
            setParity(Settings.Parity);
            setStopBits(Settings.StopBits);
            setFlowControl(Settings.FlowControl);
            //setTimeout(Settings.Timeout_Sec, Settings.Timeout_Millisec);
            setTimeout(Settings.Timeout_Millisec);
            tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig);

            handle = Posix_File->handle();
            readerThread->handle = handle;
            readerThread->shutdown = false;
            readerThread->start();
        }
        else
        {
            qDebug("Could not open File! Error code : %d", Posix_File->error());
        }
    }
    UNLOCK_MUTEX();
    return isOpen();
}
Exemplo n.º 13
0
/*!
 * \brief SerialDev::configPort - Parametri per configurare la porta seriale
 * \return true se riesce a configurare correttamente la porta seriale
 */
bool SerialDev::configPort (const QString &name)
{
    bool debugVal = m_debug;
    m_debug = true;
    setPortName(name);

    if (!open(QIODevice::ReadWrite)) {
        QString testo = QString("Can't open %1, error code %2")
                    .arg(portName()).arg(error());
        debug(testo);
        return false;
    }

    if (!setBaudRate(QSerialPort::Baud115200)) {
        QString testo = QString("Can't set rate 115200 baud to port %1, error code %2")
                     .arg(portName()).arg(error());
        debug(testo);
        return false;
    }

    if (!setDataBits(QSerialPort::Data8)) {
        QString testo = QString("Can't set 8 data bits to port %1, error code %2")
                     .arg(portName()).arg(error());
        debug(testo);
        return false;
    }

    if (!setParity(QSerialPort::NoParity)) {
        QString testo = QString("Can't set no patity to port %1, error code %2")
                     .arg(portName()).arg(error());
        debug(testo);
        return false;
    }

    if (!setStopBits(QSerialPort::OneStop)) {
        QString testo = QString("Can't set 1 stop bit to port %1, error code %2")
                     .arg(portName()).arg(error());
        debug(testo);
        return false;
    }

    if (!setFlowControl(QSerialPort::NoFlowControl)) {
        QString testo = QString("Can't set no flow control to port %1, error code %2")
                     .arg(portName()).arg(error());
        debug(testo);
        return false;
    }

    connect(this, SIGNAL(error(QSerialPort::SerialPortError)),
            this, SLOT(errorSlot(QSerialPort::SerialPortError)));
    connect(this, SIGNAL(readyRead()), this, SLOT(fromDeviceSlot()));

    m_debug = debugVal;
   return true;
}
Exemplo n.º 14
0
/*!
\fn Win_QextSerialPort::Win_QextSerialPort(const PortSettings& settings)
Constructs a port with default name and specified settings.
*/
Win_QextSerialPort::Win_QextSerialPort(const PortSettings& settings, QextSerialBase::QueryMode mode) {
    Win_Handle=INVALID_HANDLE_VALUE;
    setBaudRate(settings.BaudRate);
    setDataBits(settings.DataBits);
    setStopBits(settings.StopBits);
    setParity(settings.Parity);
    setFlowControl(settings.FlowControl);
    setTimeout(settings.Timeout_Millisec);
    setQueryMode(mode);
    init();
}
Exemplo n.º 15
0
/*!
\fn Posix_QextSerialPort::Posix_QextSerialPort(const PortSettings& settings)
Constructs a port with default name and specified settings.
*/
Posix_QextSerialPort::Posix_QextSerialPort(const PortSettings& settings)
 : QextSerialBase()
{
    setBaudRate(settings.BaudRate);
    setDataBits(settings.DataBits);
    setParity(settings.Parity);
    setStopBits(settings.StopBits);
    setFlowControl(settings.FlowControl);

    Posix_File=new QFile();
    setTimeout(settings.Timeout_Sec, settings.Timeout_Millisec);
}
Exemplo n.º 16
0
void QextSerialPortPrivate::setPortSettings(const PortSettings &settings, bool update)
{
    setBaudRate(settings.BaudRate, false);
    setDataBits(settings.DataBits, false);
    setStopBits(settings.StopBits, false);
    setParity(settings.Parity, false);
    setFlowControl(settings.FlowControl, false);
    setTimeout(settings.Timeout_Millisec, false);
    settingsDirtyFlags = DFE_ALL;
    if (update && q_func()->isOpen())
        updatePortSettings();
}
/*!
\fn Posix_QextSerialPort::Posix_QextSerialPort(const PortSettings& settings)
Constructs a port with default name and specified settings.
*/
Posix_QextSerialPort::Posix_QextSerialPort(const PortSettings& settings, QextSerialBase::QueryMode mode)
    : QextSerialBase()
{
    setBaudRate(settings.BaudRate);
    setDataBits(settings.DataBits);
    setParity(settings.Parity);
    setStopBits(settings.StopBits);
    setFlowControl(settings.FlowControl);

    setTimeout(settings.Timeout_Millisec);
    setQueryMode(mode);
    init();
}
Exemplo n.º 18
0
/*!
Constructs a port with default name and specified settings.
*/
QextSerialPort::QextSerialPort(const PortSettings& settings, QextSerialPort::QueryMode mode)
    : QIODevice()
{
    construct();
    setBaudRate(settings.BaudRate);
    setDataBits(settings.DataBits);
    setParity(settings.Parity);
    setStopBits(settings.StopBits);
    setFlowControl(settings.FlowControl);
    setTimeout(settings.Timeout_Millisec);
    setQueryMode(mode);
    platformSpecificInit();
}
Exemplo n.º 19
0
SerialPortSettings::SerialPortSettings(QSerialPortInfo serialPortInfo,
                                       QSerialPort::DataBits dataBits,
                                       QSerialPort::StopBits stopBits,
                                       QSerialPort::Parity parityBits,
                                       QSerialPort::BaudRate baudRate,
                                       QSerialPort::FlowControl flowControl)
{
    setSerialPortInfo(serialPortInfo);
    setDataBits(dataBits);
    setStopBits(stopBits);
    setParityBits(parityBits);
    setBaudRate(baudRate);
    setFlowControl(flowControl);
}
Exemplo n.º 20
0
/*!
\fn Posix_QextSerialPort::construct(void)
Common constructor function, called by all versions of 
Posix_QextSerialPort::Posix_QextSerialPort().  Sets up default port settings (115200 8N1 
Hardware flow control where supported, otherwise no flow control, and 500 ms timeout).
*/
void Posix_QextSerialPort::construct(void) {
    QextSerialBase::construct();
#ifdef NOQFILE
    m_fdFile=-1;
#else
    Posix_File=new QFile();
#endif
    setBaudRate(BAUD115200);
    setDataBits(DATA_8);
    setStopBits(STOP_1);
    setParity(PAR_NONE);
    setFlowControl(FLOW_HARDWARE);
    setTimeout(0, 500);
}
/*!
\fn bool Posix_QextSerialPort::open(OpenMode mode)
Opens the serial port associated to this class.
This function has no effect if the port associated with the class is already open.
The port is also configured to the current settings, as stored in the Settings structure.
*/
bool Posix_QextSerialPort::open(OpenMode mode)
{
    LOCK_MUTEX();
    if (mode == QIODevice::NotOpen)
        return isOpen();
    if (!isOpen()) {
        /*open the port*/
        qDebug("trying to open file");
        //note: linux 2.6.21 seems to ignore O_NDELAY flag
        if ((fd = ::open(port.toAscii() ,O_RDWR | O_NOCTTY | O_NDELAY)) != -1) {
            qDebug("file opened succesfully");

            setOpenMode(mode);			// Flag the port as opened
            tcgetattr(fd, &old_termios);	// Save the old termios
            Posix_CommConfig = old_termios;	// Make a working copy
            cfmakeraw(&Posix_CommConfig);	// Enable raw access

            /*set up other port settings*/
            Posix_CommConfig.c_cflag|=CREAD|CLOCAL;
            Posix_CommConfig.c_lflag&=(~(ICANON|ECHO|ECHOE|ECHOK|ECHONL|ISIG));
            Posix_CommConfig.c_iflag&=(~(INPCK|IGNPAR|PARMRK|ISTRIP|ICRNL|IXANY));
            Posix_CommConfig.c_oflag&=(~OPOST);
            Posix_CommConfig.c_cc[VMIN]= 0;
#ifdef _POSIX_VDISABLE	// Is a disable character available on this system?
            // Some systems allow for per-device disable-characters, so get the
            //  proper value for the configured device
            const long vdisable = fpathconf(fd, _PC_VDISABLE);
            Posix_CommConfig.c_cc[VINTR] = vdisable;
            Posix_CommConfig.c_cc[VQUIT] = vdisable;
            Posix_CommConfig.c_cc[VSTART] = vdisable;
            Posix_CommConfig.c_cc[VSTOP] = vdisable;
            Posix_CommConfig.c_cc[VSUSP] = vdisable;
#endif //_POSIX_VDISABLE
            setBaudRate(Settings.BaudRate);
            setDataBits(Settings.DataBits);
            setParity(Settings.Parity);
            setStopBits(Settings.StopBits);
            setFlowControl(Settings.FlowControl);
            setTimeout(Settings.Timeout_Millisec);
            tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
        } else {
            qDebug("could not open file: %s", strerror(errno));
        }
    }
    UNLOCK_MUTEX();
    return isOpen();
}
Exemplo n.º 22
0
/*!
 * \brief Rs232DevicePrivate::configPort - Parametri per configurare la porta seriale
 * \return true se riesce a configurare correttamente la porta seriale
 */
bool Rs232DevicePrivate::configPort ()
{
    if (!open(QIODevice::ReadWrite)) {
        QString testo = QString("Can't open %1, error code %2")
                    .arg(portName()).arg(error());
        debug(testo);
        return false;
    }

    if (!setBaudRate(QSerialPort::Baud115200)) {
        QString testo = QString("Can't set rate 115200 baud to port %1, error code %2")
                     .arg(portName()).arg(error());
        debug(testo);
        return false;
    }

    if (!setDataBits(QSerialPort::Data8)) {
        QString testo = QString("Can't set 8 data bits to port %1, error code %2")
                     .arg(portName()).arg(error());
        debug(testo);
        return false;
    }

    if (!setParity(QSerialPort::NoParity)) {
        QString testo = QString("Can't set no patity to port %1, error code %2")
                     .arg(portName()).arg(error());
        debug(testo);
        return false;
    }

    if (!setStopBits(QSerialPort::OneStop)) {
        QString testo = QString("Can't set 1 stop bit to port %1, error code %2")
                     .arg(portName()).arg(error());
        debug(testo);
        return false;
    }

    if (!setFlowControl(QSerialPort::NoFlowControl)) {
        QString testo = QString("Can't set no flow control to port %1, error code %2")
                     .arg(portName()).arg(error());
        debug(testo);
        return false;
    }

    return true;
}
Exemplo n.º 23
0
bool SerialPort::initPort(const uchar initialBaudrate,
                                  const ulong timeout)
{
    uchar baudrate = initialBaudrate % 7;
    if (baudrate == 0)                // Adapt baud
    {
      setBaudRate(BAUD2400);
      qDebug() << "Baudrate" << "2.4k";
    }
    else if (baudrate == 1)
    {
      setBaudRate(BAUD4800);
      qDebug() << "Baudrate" << "4.8k";
    }
    else if (baudrate == 2)
    {
      setBaudRate(BAUD9600);
      qDebug() << "Baudrate" << "9.6k";
    }
    else if (baudrate == 3)
    {
      setBaudRate(BAUD19200);
      qDebug() << "Baudrate" << "19.2k";
    }
    else if (baudrate == 4)
    {
      setBaudRate(BAUD38400);
      qDebug() << "Baudrate" << "38.4k";
    }
    else if (baudrate == 5)
    {
      setBaudRate(BAUD57600);
      qDebug() << "Baudrate" << "57.6k";
    }
    else if (baudrate == 6)
    {
      setBaudRate(BAUD115200);
      qDebug() << "Baudrate" << "115.2k";
    }
    setFlowControl(FLOW_OFF);
    setParity(PAR_NONE);
    setDataBits(DATA_8);
    setStopBits(STOP_1);
    setTimeout(timeout);
    return open(QIODevice::ReadWrite);
}
/*!
 * \brief  功能概述 打开串口
 * \param  参数描述 strPortName_是串口名,strBaudNo_是波特率,strDataBits_是数据位,strStopBits_是停止位,strParity_是校验方式
 * \return 返回值描述 成功打开返回true,若打开失败则返回false
 * \author zzy
 * \date   2015/5/27
 */
bool CSerialPort::OpenSerialPort(const QString strPortName_, const QString strBaudNo_,
                                 const QString strDataBits_, const QString strStopBits_, const QString strParity_)
{
    InitBaudNo(strBaudNo_);
    InitDataBits(strDataBits_);
    InitStopBits(strStopBits_);
    InitParity(strParity_);

    ///打开串口
    QString tempPortName = strPortName_;
    setPortName(strPortName_);
    if (!open(QIODevice::ReadWrite)) {
        qDebug()<<QString("Can't open %1, error code %2").arg(portName()).arg(error());
        int nPortNumber = tempPortName.remove("COM").toInt();
        QString strPortName2 = tr("ttyS%1").arg(nPortNumber);
        setPortName(strPortName2);
        if (!open(QIODevice::ReadWrite)) {
            qDebug()<<QString("Can't open %1, error code %2").arg(portName()).arg(error());
            QString strPortName3 = tr("ttyO%1").arg(nPortNumber);
            setPortName(strPortName3);
            if (!open(QIODevice::ReadWrite)) {
                qDebug()<<QString("Can't open %1, error code %2").arg(portName()).arg(error());
                return false;
            }
        }
    }
    ///  设置波特率
    setBaudRate((QSerialPort::BaudRate)m_nBaudNo);

    ///  设置数据位
    setDataBits((QSerialPort::DataBits)m_nDataBits);

    ///  设置停止位
    setStopBits((QSerialPort::StopBits)m_nStopBits);

    ///  设置校验方式
    setParity((QSerialPort::Parity)m_nParity);

    if (!setFlowControl(QSerialPort::NoFlowControl)) {
        qDebug()<<QString("Can't set no flow control to port %1, error code %2").arg(portName()).arg(error());
        return false;
    }
    return true;

}
Exemplo n.º 25
0
/* sendMail() - sends an email
 *
 * This function sends an email
 *
 * Returns '1' on success and '0' if error
*/
uint8_t WaspGPRS::sendMail(char* from, char* to, char* subject, char* body, char* user, char* passw, char* smtp_server, uint16_t port)
{
	uint8_t counter=0;
	char command[30];
	long previous=0;
	uint8_t answer=0;
	
	if(!setFlowControl()) return 0;
		
	if(!configureGPRS()) return 0;
		
	if(!setEmailParams(smtp_server, port, from)) return 0;
		
	if(!setEmailPwd(user, passw)) return 0;
		
	if(!setEmailDestination(to)) return 0;
		
	if(!setEmailSubject(subject)) return 0;
		
	while( body[counter]!='\0' ) counter++;
	counter+=2;
	
	serialFlush(PORT_USED);
	sprintf(command,"AT%s1,%u%c%c",AT_SMTP_SEND,counter,'\r','\n');
	printString(command,PORT_USED);
	previous=millis();
	while( (!serialAvailable(PORT_USED)) && ((millis()-previous)<10000) );
	delay(10);
	answer=waitForData("CONNECT",20,0,0);
	if(answer!=1) return 0;
	
	printString(body,PORT_USED);
	printByte('\r',PORT_USED);
	printByte('\n',PORT_USED);
	
	previous=millis();
	while( (!serialAvailable(PORT_USED)) && ((millis()-previous)<10000) );
	delay(10);
	answer=waitForData("OK",20,0,0);
	if(answer!=1) return 0;
	
	
	return 1;

}
Exemplo n.º 26
0
bool rs232_port::port_open(const QString & port_name, QSerialPort::BaudRate baud_rate, PORT_PROTOCOL_T prot)
{
    setPortName(port_name);
    setBaudRate(baud_rate); // 115200
    setFlowControl(NoFlowControl);
    setParity(NoParity);    // паритет отключен
    setDataBits(Data8);   // 8 бит
    setStopBits(OneStop);  // один стоповый
    if (!open(QIODevice::ReadWrite))
    {
        this -> port_name.clear();
        return false;
    }
    this -> port_name = port_name;
    this -> prot = prot;
    qDebug() << tr("RS232 %1 was opened").arg(port_name);
    return true;
}
Exemplo n.º 27
0
// ######################################################################
void SerialPort::enablePort(std::string DeviceName) {
  closePort();
  serialErrno = serialErrSuccess;  // clear the error flag

  openPort(DeviceName);  // open the device
  perror();

  setSpeed(itsBaud);  // Set the baud rate
  perror();

  setFlowControl(itsFlowHard, itsFlowSoft);  // Set flow control
  perror();

  setCharBits(itsCharBits);  // set no of bits in a char
  perror();

  setParity(itsUseParity, itsParityOdd);  // Set even or odd parity
  perror();

  setBlocking(itsBlocking);  // blocking mode?
  perror();
}
Exemplo n.º 28
0
/*!
		\fn bool Win_QextSerialPort::open(OpenMode mode)
			Opens a serial port.  Note that this function does not specify which device to open.  If you need
			to open a device by name, see Win_QextSerialPort::open(const char*).  This function has no effect
			if the port associated with the class is already open.  The port is also configured to the current
			settings, as stored in the Settings structure.
*/
bool Win_QextSerialPort::open(OpenMode mode) {
	unsigned long confSize = sizeof(COMMCONFIG);
	Win_CommConfig.dwSize = confSize;
	
	LOCK_MUTEX();
	if (mode == QIODevice::NotOpen)
		return isOpen();
	if (!isOpen()) {
		/*open the port*/
		Win_Handle=CreateFileA(port.toLatin1(), GENERIC_READ|GENERIC_WRITE,
				FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
		if (Win_Handle!=INVALID_HANDLE_VALUE) {
			/*set open mode*/
			QIODevice::open(mode);
			
			/*configure port settings*/
			GetCommConfig(Win_Handle, &Win_CommConfig, &confSize);
			GetCommState(Win_Handle, &(Win_CommConfig.dcb));
			
			/*set up parameters*/
			Win_CommConfig.dcb.fBinary=TRUE;
			Win_CommConfig.dcb.fInX=FALSE;
			Win_CommConfig.dcb.fOutX=FALSE;
			Win_CommConfig.dcb.fAbortOnError=FALSE;
			Win_CommConfig.dcb.fNull=FALSE;
			setBaudRate(Settings.BaudRate);
			setDataBits(Settings.DataBits);
			setStopBits(Settings.StopBits);
			setParity(Settings.Parity);
			setFlowControl(Settings.FlowControl);
			setTimeout(Settings.Timeout_Sec, Settings.Timeout_Millisec);
			SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG));
		}
	}
	UNLOCK_MUTEX();
	return isOpen();
}
Exemplo n.º 29
0
/*!
\fn bool Posix_QextSerialPort::open(int=0)
Opens a serial port.  Note that this function does not specify which device to open.  If you need
to open a device by name, see Posix_QextSerialPort::open(const char*).  This function has no 
effect if the port associated with the class is already open.  The port is also configured to the 
current settings, as stored in the Settings structure.
*/
bool Posix_QextSerialPort::open(int) {
    LOCK_MUTEX();
    if (!portOpen) {

        /*open the port*/
#ifdef NOQFILE
        if ((m_fdFile=::open((const char *)QFile::encodeName(portName),O_NOCTTY | O_RDWR | O_SYNC))!=-1) {
            portOpen=true;
#else
        Posix_File->setName(portName);
        if (Posix_File->open(/*IO_Async| */ IO_Raw| IO_ReadWrite)) {
            portOpen=true;
#endif
            /*configure port settings*/
#ifdef NOQFILE
            tcgetattr(m_fdFile, &Posix_CommConfig);
#else       
            tcgetattr(Posix_File->handle(), &Posix_CommConfig);
#endif
            /*set up other port settings*/
            Posix_CommConfig.c_cflag|=CREAD|CLOCAL;
            Posix_CommConfig.c_lflag&=(~(ICANON|ECHO|ECHOE|ECHOK|ECHONL|ISIG));
            Posix_CommConfig.c_iflag&=(~(INPCK|IGNPAR|PARMRK|ISTRIP|ICRNL|IXANY));
            Posix_CommConfig.c_oflag&=(~OPOST);
            Posix_CommConfig.c_cc[VMIN]=0;
            Posix_CommConfig.c_cc[VINTR] = _POSIX_VDISABLE; 
            Posix_CommConfig.c_cc[VQUIT] = _POSIX_VDISABLE; 
            Posix_CommConfig.c_cc[VSTART] = _POSIX_VDISABLE; 
            Posix_CommConfig.c_cc[VSTOP] = _POSIX_VDISABLE; 
            Posix_CommConfig.c_cc[VSUSP] = _POSIX_VDISABLE; 
#ifdef NOQFILE
            tcsetattr(m_fdFile, TCSAFLUSH, &Posix_CommConfig);
#else
            tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig);
#endif
            setBaudRate(Settings.BaudRate);
            setDataBits(Settings.DataBits);
            setStopBits(Settings.StopBits);
            setParity(Settings.Parity);
            setFlowControl(Settings.FlowControl);
            setTimeout(Posix_Copy_Timeout.tv_sec, Posix_Copy_Timeout.tv_usec);
        }
    }
    UNLOCK_MUTEX();
    return portOpen;
}

/*!
\fn void Posix_QextSerialPort::close()
Closes a serial port.  This function has no effect if the serial port associated with the class
is not currently open.
*/
void Posix_QextSerialPort::close() {
    LOCK_MUTEX();
#ifdef NOQFILE
    ::close(m_fdFile);
    m_fdFile=-1;
#else
    Posix_File->close();
#endif
    portOpen=false;
    UNLOCK_MUTEX();
}
Exemplo n.º 30
0
int readChannelMsg(ant_channel_type eChannel, ant_channel_info_t *pstChnlInfo)
{
   int iRet = -1;
   int iRxLenRead;
   int iCurrentHciPacketOffset;
   int iHciDataSize;
   ANT_FUNC_START();

   // Keep trying to read while there is an error, and that error is EAGAIN
   while (((iRxLenRead = read(pstChnlInfo->iFd, &aucRxBuffer[eChannel][iRxBufferLength[eChannel]], (sizeof(aucRxBuffer[eChannel]) - iRxBufferLength[eChannel]))) < 0)
                   && errno == EAGAIN)
      ;

   if (iRxLenRead < 0) {
      if (errno == ENODEV) {
         ANT_ERROR("%s not enabled, exiting rx thread",
               pstChnlInfo->pcDevicePath);

         goto out;
      } else if (errno == ENXIO) {
         ANT_ERROR("%s there is no physical ANT device connected",
               pstChnlInfo->pcDevicePath);

         goto out;
      } else {
         ANT_ERROR("%s read thread exiting, unhandled error: %s",
               pstChnlInfo->pcDevicePath, strerror(errno));

         goto out;
      }
   } else {
      ANT_SERIAL(aucRxBuffer[eChannel], iRxLenRead, 'R');

      iRxLenRead += iRxBufferLength[eChannel];   // add existing data on

      // if we didn't get a full packet, then just exit
      if (iRxLenRead < (aucRxBuffer[eChannel][ANT_HCI_SIZE_OFFSET] + ANT_HCI_HEADER_SIZE + ANT_HCI_FOOTER_SIZE)) {
         iRxBufferLength[eChannel] = iRxLenRead;
         iRet = 0;
         goto out;
      }

      iRxBufferLength[eChannel] = 0;    // reset buffer length here since we should have a full packet

#if ANT_HCI_OPCODE_SIZE == 1  // Check the different message types by opcode
      ANT_U8 opcode = aucRxBuffer[eChannel][ANT_HCI_OPCODE_OFFSET];

      if(ANT_HCI_OPCODE_COMMAND_COMPLETE == opcode) {
         // Command Complete, so signal a FLOW_GO
         if(setFlowControl(pstChnlInfo, ANT_FLOW_GO)) {
            goto out;
         }
      } else if(ANT_HCI_OPCODE_FLOW_ON == opcode) {
         // FLow On, so resend the last Tx
#ifdef ANT_FLOW_RESEND
         // Check if there is a message to resend
         if(pstChnlInfo->ucResendMessageLength > 0) {
            ant_tx_message_flowcontrol_none(eChannel, pstChnlInfo->ucResendMessageLength, pstChnlInfo->pucResendMessage);
         } else {
            ANT_DEBUG_D("Resend requested by chip, but tx request cancelled");
         }
#endif // ANT_FLOW_RESEND
      } else if(ANT_HCI_OPCODE_ANT_EVENT == opcode)
         // ANT Event, send ANT packet to Rx Callback
#endif // ANT_HCI_OPCODE_SIZE == 1
      {
      // Received an ANT packet
         iCurrentHciPacketOffset = 0;

         while(iCurrentHciPacketOffset < iRxLenRead) {

            // TODO Allow HCI Packet Size value to be larger than 1 byte
            // This currently works as no size value is greater than 255, and little endian
            iHciDataSize = aucRxBuffer[eChannel][iCurrentHciPacketOffset + ANT_HCI_SIZE_OFFSET];

            if ((iHciDataSize + ANT_HCI_HEADER_SIZE + ANT_HCI_FOOTER_SIZE + iCurrentHciPacketOffset) >
                  iRxLenRead) {
               // we don't have a whole packet
               iRxBufferLength[eChannel] = iRxLenRead - iCurrentHciPacketOffset;
               memcpy(aucRxBuffer[eChannel], &aucRxBuffer[eChannel][iCurrentHciPacketOffset], iRxBufferLength[eChannel]);
               // the increment at the end should push us out of the while loop
            } else
#ifdef ANT_MESG_FLOW_CONTROL
            if (aucRxBuffer[eChannel][iCurrentHciPacketOffset + ANT_HCI_DATA_OFFSET + ANT_MSG_ID_OFFSET] ==
                  ANT_MESG_FLOW_CONTROL) {
               // This is a flow control packet, not a standard ANT message
               if(setFlowControl(pstChnlInfo, \
                     aucRxBuffer[eChannel][iCurrentHciPacketOffset + ANT_HCI_DATA_OFFSET + ANT_MSG_DATA_OFFSET])) {
                  goto out;
               }
            } else
#endif // ANT_MESG_FLOW_CONTROL
            {
               ANT_U8 *msg = aucRxBuffer[eChannel] + iCurrentHciPacketOffset + ANT_HCI_DATA_OFFSET;
               ANT_BOOL bIsKeepAliveResponse = memcmp(msg, KEEPALIVE_RESP, sizeof(KEEPALIVE_RESP)/sizeof(ANT_U8)) == 0;
               if (bIsKeepAliveResponse) {
                  ANT_DEBUG_V("Filtered out keepalive response.");
               } else if (pstChnlInfo->fnRxCallback != NULL) {

                  // Loop through read data until all HCI packets are written to callback
                     pstChnlInfo->fnRxCallback(iHciDataSize, \
                           msg);
               } else {
                  ANT_WARN("%s rx callback is null", pstChnlInfo->pcDevicePath);
               }
            }

            iCurrentHciPacketOffset = iCurrentHciPacketOffset + ANT_HCI_HEADER_SIZE + ANT_HCI_FOOTER_SIZE + iHciDataSize;
         }
      }

      iRet = 0;
   }

out:
   ANT_FUNC_END();
   return iRet;
}