⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 phycom.cpp

📁 linux 环境下的 RS232通信源代码
💻 CPP
字号:
#include "const.h"
#include "phycom.h"

#if (ACTUAL_OS == OS_LINUX) || (ACTUAL_OS == OS_UCLINUX) || (ACTUAL_OS == OS_UNIX)

PhysicalCom::PhysicalCom(PhyChnlConfig* pConfig,EscInt poolSize):PhysicalLayer(poolSize)
{
      fd = open( pConfig->dev, O_RDWR);
       phyConfig=pConfig;
	InitDev(fd,pConfig->speed,pConfig->databits,pConfig->stopbits,pConfig->parity,pConfig->timeout);
       chnlOpend=ESC_FALSE;
	//maxConnetTime = 3;
}
//////////////////////////////////////////////////////////////////////

EscInt PhysicalCom::InitDev(EscInt fd,EscInt speed, EscInt databits, EscInt stopbits, EscInt parity, EscInt timeout)

{
	
	setSpeed(fd,speed);
	if (setParity(fd, databits, stopbits, parity, timeout) < 0) 
	{
		//printf("Set Parity Error\n");
		initialized = ESC_FALSE;
		return -1;
	}
	setRawIo( fd );
    initialized = ESC_TRUE;
    //printf("Set Parity right %d\n",initialized);
	return 0;
}

//////////////////////////////////////////////////////////////////////
void PhysicalCom::setSpeed(EscInt fd, EscInt speed)

{
     EscInt speedArr[]={B57600,B38400,B19200,B9600,B4800,B2400,B1200, B300, B57600, B38400, B19200, B9600, B4800, B2400, B1200, B300};
     EscInt nameArr[]={57600, 38400, 19200, 9600, 4800, 2400, 1200, 300,57600, 38400, 19200,9600, 4800, 2400, 1200, 300};
	EscInt   i;
	EscInt   status;
	struct termios   Opt;
	tcgetattr(fd, &Opt);
	for ( i= 0;  i < sizeof(speedArr) / sizeof(int);  i++)
	{
		if  (speed == nameArr[i])
		{
			tcflush(fd, TCIOFLUSH);
			cfsetispeed(&Opt, speedArr[i]);
			cfsetospeed(&Opt, speedArr[i]);
			status = tcsetattr(fd, TCSANOW, &Opt);
			if  (status != 0)
			{
				initialized = ESC_FALSE;
				//perror("tcsetattr fd1");
			}
			return;
		}
		tcflush(fd,TCIOFLUSH);
	}
}

//////////////////////////////////////////////////////////////////////

EscInt PhysicalCom::setParity(EscInt fd,EscInt databits,EscInt stopbits,EscInt parity, EscInt timeout)
{
	struct termios options;
	if( tcgetattr( fd,&options)  !=  0)
	{
		//perror("SetupSerial 1");
		return -1;
	}
  
  
  options.c_cflag &= ~CSIZE;
  switch (databits) /*璁剧疆鏁版嵁浣嶆暟*/
  {
  	case 7:
  		options.c_cflag |= CS7;
  		break;
  	case 8:
		options.c_cflag |= CS8;
		break;
	default:
		//fprintf(stderr,"Unsupported data size\n");
		return -1;
	}
  switch (parity)
  {
  	      case 'n':
	      case 'N':
			options.c_cflag &= ~PARENB;   /* Clear parity enable */
			options.c_iflag &= ~INPCK;     /* Enable parity checking */
			break;
		case 'o':
		case 'O':
			options.c_cflag |= (PARODD | PARENB);  /* 璁剧疆涓哄

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -