网关--串口接收数据转送到网口发送到PC机

    先上代码吧:

/*--------------------------------------------------------------
日期:2012/1/1
功能:串口接收转发到网络
--------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "rs232.h"



#include <errno.h>

#include <sys/wait.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <signal.h>



#define PORT 3000
//#define PACKET_SIZE 8192 
#define PACKET_SIZE 6 


static int count=0;
static unsigned int second;
static unsigned int sum;

void display()
{
	printf("\n");
	printf("Transfer complete !\n");
	printf("Total size:%d !\n",sum);
	printf("Speed:%d Mbps\n",8*sum/second/0x100000);
	exit(0);
}

/*-----------------------------------------
client 192.168.2.111 –t 1 –p 1
argv[0] = client 
argv[1] = 172.16.22.155
argv[2] = –t
argv[3] = 1
argv[4] = -p
argv[5] = 1
------------------------------------------*/
void Tcp()
{
	int argc_data;
	char *argv_data[6];
	int sockfd;
	int recv_bytes;
	//unsigned int buf[PACKET_SIZE];
	unsigned int *Tcp_buf;
	struct hostent *he;
	struct sockaddr_in srvaddr;
	unsigned int uiip;
	unsigned int nsecond,packet_size;
	sum=0;

	argc_data = 6;
	argv_data[0] = "client";
	argv_data[1] = "172.16.22.155";
	argv_data[2] = "-t";
	argv_data[3] = "1";
	argv_data[4] = "-p";
	argv_data[5] = "1";
	
	
	if(argc_data< 4 ){
		perror("Usage: client <hostIP>  -t time -p PACKET_SIZE\n");
		exit(2);
	}
	packet_size=PACKET_SIZE;
	
	second=atoi(argv_data[3]);	
	if(argc_data==6)
	    packet_size=atoi(argv_data[5]);	
	printf("packet_size=%d\n",packet_size);
	Tcp_buf = malloc(packet_size);

	he=gethostbyname(argv_data[1]);
	sockfd=socket(AF_INET,SOCK_STREAM,0);
	bzero(&srvaddr,sizeof(srvaddr));
	srvaddr.sin_family=AF_INET;
	srvaddr.sin_port=htons(PORT);
	srvaddr.sin_addr=*((struct in_addr *)he->h_addr);
	//aiptoi(argv[1],&uiip);
	//srvaddr.sin_addr.s_addr=uiip;

	if(connect(sockfd,
		(struct sockaddr *) &srvaddr, sizeof(struct sockaddr))== -1){
		perror("Connect error!\n");
		exit(1);
	}
        //	nsecond = htonl(second);

      	nsecond = 0x01020304;
	if(write(sockfd,&nsecond,sizeof(nsecond))== -1){
		perror("Error when send second!\n");
		exit(1);
	}
	printf("Data Transfering!\n");

/*	while (1){ 
		if((recv_bytes=read(sockfd,buf,packet_size))<=0){
			printf("Connection closed!\n");
			break;
		}	
		sum+=recv_bytes;
	}
*/
	while(1)
	{
		write(sockfd, &nsecond, sizeof(nsecond));
		sleep(5);
	}
	close(sockfd);
	free(Tcp_buf);
	display();
	//return 0;
}




main(int argc, char *argv[])
{

	int ret,portno,nWritten,nRead;
	char buf[5] = "hell";

	
	/*网口实现部分*/
		int argc_data;
	char *argv_data[6];
	int sockfd;
	int recv_bytes;
	//unsigned int buf[PACKET_SIZE];
	unsigned int *Tcp_buf;
	struct hostent *he;
	struct sockaddr_in srvaddr;
	unsigned int uiip;
	unsigned int nsecond,packet_size;
	sum=0;

	argc_data = 6;
	argv_data[0] = "client";
	argv_data[1] = "172.16.22.155";
	argv_data[2] = "-t";
	argv_data[3] = "1";
	argv_data[4] = "-p";
	argv_data[5] = "1";
	
		portno=0;
	if(argc_data< 4 ){
		perror("Usage: client <hostIP>  -t time -p PACKET_SIZE\n");
		exit(2);
	}
	packet_size=PACKET_SIZE;
	
	second=atoi(argv_data[3]);	
	if(argc_data==6)
	    packet_size=atoi(argv_data[5]);	
	printf("packet_size=%d\n",packet_size);
	Tcp_buf = malloc(packet_size);

	he=gethostbyname(argv_data[1]);
	sockfd=socket(AF_INET,SOCK_STREAM,0);
	bzero(&srvaddr,sizeof(srvaddr));
	srvaddr.sin_family=AF_INET;
	srvaddr.sin_port=htons(PORT);
	srvaddr.sin_addr=*((struct in_addr *)he->h_addr);
	//aiptoi(argv[1],&uiip);
	//srvaddr.sin_addr.s_addr=uiip;

	if(connect(sockfd,
		(struct sockaddr *) &srvaddr, sizeof(struct sockaddr))== -1){
		perror("Connect error!\n");
		exit(1);
	}
        //	nsecond = htonl(second);

  /*    	
	nsecond = 0x01020304;
	if(write(sockfd,&nsecond,sizeof(nsecond))== -1){
		perror("Error when send second!\n");
		exit(1);
	}
	printf("Data Transfering!\n");
	*/

/*	while (1){ 
		if((recv_bytes=read(sockfd,buf,packet_size))<=0){
			printf("Connection closed!\n");
			break;
		}	
		sum+=recv_bytes;
	}
*/
	/*while(1)
	{
		write(sockfd, &nsecond, sizeof(nsecond));
		sleep(5);
	}
	close(sockfd);
	free(Tcp_buf);
	display();
	*/
	//return 0;
	/*--------------------------------------------------------------------*/
	
	
	
	
	while(1)
	{
		ret=OpenCom(portno,"/dev/ttyS1",115200);
		if(ret==-1)
		{
			perror("The /dev/ttyS1 open error.");
			exit(1);
		}
	/*	while(1)
		{
			nWritten=ComWrt(portno,"abc",3);
		}
	*/
		printf("\n/dev/ttyS1 has send %d chars!\n",nWritten);
		printf("\nRecieving data!***\n");
		fflush(stdout);
		//buf[5] = "hell";
		while(1)
		{
			/*nRead=ComRd(0,buf,256,3000);
			if(nRead>0)
			{
				printf("*****OK\n");
				nWritten = ComWrt(portno, buf, sizeof(buf));
				
			}*/
			printf("******start***********\n");
			printf("*****ComRd*****\n");
			//ComRd(0, buf, 256, 3000);
			nRead = ComRd(0, buf, 256, 3000);
			if(nRead > 0)
			{
				printf("The Rddata is: %s\n",buf);
				/*---串口部分-----*/
				ComWrt(portno, buf, sizeof(buf));
				printf("The ComWrt data is: %s\n",buf);
				
				/*网口部分*/
					//nsecond = 0x01020304;
					if(write(sockfd,buf,sizeof(buf))== -1)
					{
						perror("Error when send second!\n");
						exit(1);
					}
					//printf("Data Transfering!\n");
				
				
				write(sockfd, buf, sizeof(buf));
				printf("send to sockfd :%s\n",buf);
				sleep(1);
				
				printf("*****************end*****************\n");
			}
		/*	else
				printf("Timeout\n");
		*/
		}
		if((ret=CloseCom(portno)==-1))
		{
			perror("Close com");
			exit(1);
		}
		printf("\n\n");
	}
	printf("Exit now.\n");
	
	
	/*网口部分*/
	close(sockfd);
	//free(Tcp_buf);
	display();
	/*----------------------------------*/
	
	return;
}

 上面就是全部的主程序代码了

还有一个是RS232串口部分的代码:

/*
** File: rs232.c
**
** Description:
**      Provides an RS-232 interface that is very similar to the CVI provided
**      interface library
*/
#include <stdio.h>
#include <assert.h>
#include "rs232.h" 
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>

#define DEBUG

struct PortInfo ports[MAX_PORTS];

/*
** Function: OpenCom
**
** Description:
**    Opens a serial port with default parameters
**
** Arguments:
**    portNo - handle used for further access
**    deviceName - the name of the device to open
**
** Returns:
**    -1 on failure
*/
int OpenCom(int portNo, const char deviceName[],long baudRate)
{
    return OpenComConfig(portNo, deviceName, baudRate, 1, 8, 1, 0, 0);
}

/*

*/
long GetBaudRate(long baudRate)
{
    long BaudR;
    switch(baudRate)
    {
	case 115200:
		BaudR=B115200;
		break;
	case 57600:
		BaudR=B57600;
		break;
	case 19200:
		BaudR=B19200;
		break;
	case 9600:
		BaudR=B9600;
		break;
	default:
		BaudR=B0;
    }
    return BaudR;
}

/*
** Function: OpenComConfig
**
** Description:
**    Opens a serial port with the specified parameters
**
** Arguments:
**    portNo - handle used for further access
**    deviceName - the name of the device to open
**    baudRate - rate to open (57600 for example)
**    parity - 0 for no parity
**    dataBits - 7 or 8
**    stopBits - 1 or 2
**    iqSize - ignored
**    oqSize - ignored
**
** Returns:
**    -1 on failure
**
** Limitations:
**    parity, stopBits, iqSize, and oqSize are ignored
*/
int OpenComConfig(int port,
                  const char deviceName[],
                  long baudRate,
                  int parity,
                  int dataBits,
                  int stopBits,
                  int iqSize,
                  int oqSize)
{
    struct termios newtio;
    long BaudR;

    ports[port].busy = 1;
    strcpy(ports[port].name,deviceName);
    if ((ports[port].handle = open(deviceName, O_RDWR, 0666)) == -1)
    {
        perror("open");
       // assert(0);
    }

    /* set the port to raw I/O */
    newtio.c_cflag = CS8 | CLOCAL | CREAD ;
    newtio.c_iflag = IGNPAR;
//    newtio.c_oflag = 0;
//    newtio.c_lflag = 0;
    newtio.c_oflag = ~OPOST;
    newtio.c_lflag = ~(ICANON | ECHO | ECHOE | ISIG);

    newtio.c_cc[VINTR]    = 0;
    newtio.c_cc[VQUIT]    = 0;
    newtio.c_cc[VERASE]   = 0;
    newtio.c_cc[VKILL]    = 0;
    newtio.c_cc[VEOF]     = 4;
    newtio.c_cc[VTIME]    = 0;
    newtio.c_cc[VMIN]     = 1;
    newtio.c_cc[VSWTC]    = 0;
    newtio.c_cc[VSTART]   = 0;
    newtio.c_cc[VSTOP]    = 0;
    newtio.c_cc[VSUSP]    = 0;
    newtio.c_cc[VEOL]     = 0;
    newtio.c_cc[VREPRINT] = 0;
    newtio.c_cc[VDISCARD] = 0;
    newtio.c_cc[VWERASE]  = 0;
    newtio.c_cc[VLNEXT]   = 0;
    newtio.c_cc[VEOL2]    = 0;
    cfsetospeed(&newtio, GetBaudRate(baudRate));
    cfsetispeed(&newtio, GetBaudRate(baudRate));
    tcsetattr(ports[port].handle, TCSANOW, &newtio);
    return 0;
}

/*
** Function: CloseCom
**
** Description:
**    Closes a previously opened port
**
** Arguments:
**    The port handle to close
**
**    Returns:
**    -1 on failure
*/
int CloseCom(int portNo)
{
    if (ports[portNo].busy)
    {
        close(ports[portNo].handle);
        ports[portNo].busy = 0;
        return 0;
    }
    else
    {
        return -1;
    }
}

/*
** Function: ComRd
**
** Description:
**    Reads the specified number of bytes from the port.
**    Returns when these bytes have been read, or timeout occurs.
**
** Arguments:
**    portNo - the handle
**    buf - where to store the data
**    maxCnt - the maximum number of bytes to read
**
** Returns:
**    The actual number of bytes read
*/
int ComRd(int portNo, char buf[], int maxCnt,int Timeout)
{
    int actualRead = 0;
    fd_set rfds;
    struct timeval tv;
    int retval;

    if (!ports[portNo].busy)
    {
        assert(0);
    }

    /* camp on the port until data appears or 5 seconds have passed */
    FD_ZERO(&rfds);
    FD_SET(ports[portNo].handle, &rfds);
    tv.tv_sec = Timeout/1000;
    tv.tv_usec = (Timeout%1000)*1000;
    retval = select(16, &rfds, NULL, NULL, &tv);

    if (retval)
    {
        actualRead = read(ports[portNo].handle, buf, maxCnt);
    }
    
#ifdef DEBUG
	if(actualRead>0)
    {
        unsigned int i;
        for (i = 0; i < actualRead; ++i)
        {
            if ((buf[i] > 0x20) && (buf[i] < 0x7f))
            {
//                printf("<'%c'", buf[i]);
                  printf("%c",buf[i]);
            }
            else
            {
//                printf("<%02X", buf[i]);
                  printf("%02X",buf[i]);
            }
        }
	printf("\n");
    }
    fflush(stdout);
#endif /* DEBUG */

    return actualRead;
}

/*
** Function: ComWrt
**
** Description:
**    Writes out the specified bytes to the port
**
** Arguments:
**    portNo - the handle of the port
**    buf - the bytes to write
**    maxCnt - how many to write
**
** Returns:
**    The actual number of bytes written
*/
int ComWrt(int portNo, const char *buf, int maxCnt)
{
    int written;

    if (!ports[portNo].busy)
    {
        assert(0);
    }
#ifdef DEBUG
    {
        int i;
        for (i = 0; i < maxCnt; ++i)
        {
            if ((buf[i] > 0x20) && (buf[i] < 0x7f))
            {
//                printf(">'%c'", buf[i]);
                  printf("%c",buf[i]);
            }
            else
            {
//                printf(">%02X", buf[i]);
                  printf("%02X",buf[i]);
            }
        }
	printf("\n");
    }
    fflush(stdout);
#endif /* DEBUG */
    
    written = write(ports[portNo].handle, buf, maxCnt);
    return written;
}


 然后再看头文件:

#ifndef _RS232_H_
#define _RS232_H_

/* the maximum number of ports we are willing to open */
#define MAX_PORTS 4

/*this array hold information about each port we have opened */
struct PortInfo{
	int busy;
	char name[32];
	int handle;
};

int OpenCom(int portNo,const char deviceName[],long baudRate);
int CloseCom(int portNo);
int ComRd(int portNo,char buf[],int maxCnt,int Timeout);
int ComWrt(int portNo,const char * buf,int maxCnt);

//long GetBaudRate(long baudRate);
//int OpenComConfig(int port,
//                  const char deviceName[],
//                  long baudRate,
//                  int parity,
//                  int dataBits,
//                  int stopBits,
//                  int iqSize,
//                  int oqSize);

#endif

 再看效果图:

 

 

posted @ 2012-01-01 22:17  [无名]  阅读(4278)  评论(1编辑  收藏  举报