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

📄 comport.c

📁 Serial port function for linux
💻 C
字号:
/******************************************************************* * *    DESCRIPTION: *			Linux COM Port wrapper functions * *    AUTHOR: *			Suriyan Laohaprapanon * *    HISTORY: * *******************************************************************/#define COMPORT_MODULE_TEST		1/** include files **/#include <stdio.h>#if defined __CYGWIN__    #define _WIN32#endif#if defined _WIN32    #include <windows.h>#endif#if defined __linux__    #include <sys/ioctl.h>    #include <sys/timeb.h>    #include <errno.h>    #include <fcntl.h>    #include <unistd.h>    #include <asm/ioctls.h>    #include <termios.h>#define TIOCM_OUT2	0x4000      /* Manually define because cannot include <asm/termios.h> and <termios.h> */#endif#include "debug.h"/** local definitions **/#define MAX_COMPORT		(2)/** default settings **//** external functions **//** external data **//** internal functions **//** public data **//** private data **/#if defined _WIN32static HANDLE fd[MAX_COMPORT];static DCB olddcb[MAX_COMPORT];static COMMTIMEOUTS oldtimeouts[MAX_COMPORT];#elsestatic struct termios oldtio[MAX_COMPORT];static int fd[MAX_COMPORT];#endif/** public functions **//* *  FUNCTION: comport_open() * *  PARAMETERS: *			comno		COM Port Number (1 to MAX_COMPORT) *			baud		baud rate * *  DESCRIPTION: *			Initialize COM port and open it for ready to use * *  RETURNS:  *			-1			Failed to open *			0			Success * */int comport_open(int comno, long baud){    char devicename[80];#if defined _WIN32    DCB dcb;    COMMTIMEOUTS sTimeouts;#else    struct termios newtio;    long rate;#endif    if ((comno < 1) || (comno > MAX_COMPORT)) {        return -1;    }#ifdef _WIN32    //    // Create the device name for the given serial port.    //    sprintf(devicename, "\\\\.\\CNCA%d", comno - 1);    //    // Open the serial port.    //    fd[comno - 1] = CreateFile(devicename, GENERIC_READ | GENERIC_WRITE, 0, 0,                               OPEN_EXISTING, 0, 0);    if (fd[comno - 1] == INVALID_HANDLE_VALUE) {        fprintf(stderr, "Could not open serial port %s.\r\n", devicename);        return -1;    }    //    // Purge any pending characters in the serial port.    //    PurgeComm(fd[comno - 1], (PURGE_TXABORT | PURGE_RXABORT |                              PURGE_TXCLEAR | PURGE_RXCLEAR));    GetCommState(fd[comno - 1], &olddcb[comno - 1]);    //    // Fill in the device control block.    //    dcb.DCBlength = sizeof(DCB);    dcb.BaudRate = baud;    dcb.fBinary = TRUE;    dcb.fParity = TRUE;    dcb.fOutxCtsFlow = TRUE; // FALSE    dcb.fOutxDsrFlow = TRUE; // FALSE    dcb.fDtrControl = DTR_CONTROL_ENABLE; // DISABLE    dcb.fDsrSensitivity = FALSE;    dcb.fTXContinueOnXoff = TRUE;    dcb.fOutX = FALSE;    dcb.fInX = FALSE;    dcb.fErrorChar = FALSE;    dcb.fNull = FALSE;    dcb.fRtsControl = RTS_CONTROL_ENABLE; // DISABLE    dcb.fAbortOnError = FALSE;    dcb.XonLim = 0;    dcb.XoffLim = 0;    dcb.ByteSize = 8;    dcb.Parity = ODDPARITY;    dcb.StopBits = ONESTOPBIT;    dcb.XonChar = 17;    dcb.XoffChar = 19;    dcb.ErrorChar = 0;    dcb.EofChar = 0;    dcb.EvtChar = 0;    dcb.wReserved = 0;    //    // Set the new serial port configuration.    //    SetCommState(fd[comno - 1], &dcb);    //    // Get and store the timeout.    //    GetCommTimeouts(fd[comno - 1], &oldtimeouts[comno - 1]);    //    // Fill in the timeout structure based on the timeout requested for this    // read.    //    sTimeouts.ReadIntervalTimeout = 50;    sTimeouts.ReadTotalTimeoutMultiplier = 0;    sTimeouts.ReadTotalTimeoutConstant = 50;    sTimeouts.WriteTotalTimeoutMultiplier = 0;    sTimeouts.WriteTotalTimeoutConstant = 0;    //    // Set the timeout for this read.    //    SetCommTimeouts(fd[comno - 1], &sTimeouts);    return comno;#else    int status;    sprintf(devicename, "/dev/ttyUSB%d", comno - 1);    /* open the device(com port) to be non-blocking (read will return immediately) */    fd[comno - 1] = open(devicename, O_RDWR | O_NOCTTY | O_NONBLOCK);    if (fd[comno - 1] < 0) {        return -1;    }    //    // Get the baud rate.    //    switch (baud) {    case 9600:        {            rate = B9600;            break;        }    case 19200:        {            rate = B19200;            break;        }    case 38400:        {            rate = B38400;            break;        }    case 57600:        {            rate = B57600;            break;        }    case 115200:        {            rate = B115200;            break;        }    case 230400:	{	    rate = B230400;	    break;        }    }    tcgetattr(fd[comno - 1],&oldtio[comno - 1]); /* save current port settings */    /* set new port settings for canonical input processing */    newtio.c_cflag = rate | CRTSCTS | CS8 | CLOCAL | CREAD;    newtio.c_iflag = IGNPAR;    newtio.c_oflag = 0;    newtio.c_lflag = 0;    newtio.c_cc[VMIN]=1;    newtio.c_cc[VTIME]=0;    tcflush(fd[comno - 1], TCIFLUSH);    tcsetattr(fd[comno - 1],TCSANOW,&newtio);    status = 0;    if (comno == 1) {//        status |= TIOCM_OUT2;        status |= TIOCM_RTS;	status |= TIOCM_DTR;     }    if (ioctl(fd[comno - 1], TIOCMSET, &status) == 0) {        DPRINTF(DEBUG_INFO, ("ioctl set ok, status = %X", status));    } else {        DPRINTF(DEBUG_ERROR, ("ioctl set failed"));    }    return comno;#endif}/* *  FUNCTION: comport_getc() * *  PARAMETERS: *			comno		COM Port Number (1 to MAX_COMPORT) *			*c			got character * *  DESCRIPTION: *			Initialize COM port and open it for ready to use * *  RETURNS:  *			-1			Failed to get *			0			a character not available *			1			get a character * */int comport_getc(int comno, char *c){    if ((comno < 1) || (comno > MAX_COMPORT)) {        return -1;    }#ifdef _WIN32    DWORD dwLen;    //    // Read a character.    //    if (!ReadFile(fd[comno - 1], c, 1, &dwLen, NULL)) {        //        // The read failed, so set the read character to a NULL.        //        return 0;    }    //    // If we did not read a character, then set the character to NULL.    //    if (dwLen != 1) {        return 0;    }    //    // Return the character we read.    //    return 1;#else    if (read(fd[comno - 1], c, 1) > 0) {        return 1;    } else {        return 0;    }#endif}/* *  FUNCTION: comport_putc() * *  PARAMETERS: *			comno		COM Port Number (1 to MAX_COMPORT) *			c			a character to put * *  DESCRIPTION: *			Write out a character to COM port * *  RETURNS:  *			-1			comno out-of-range *			0			Success * */int comport_putc(int comno, char c){    if ((comno < 1) || (comno > MAX_COMPORT)) {        return -1;    }#if defined _WIN32    DWORD dwLen;    //    // Send this character to the serial port.    //    WriteFile(fd[comno - 1], &c, 1, &dwLen, NULL);#else    write(fd[comno - 1], &c, 1);#endif    return 0;}int comport_mdm_get(int comno){    int status;    ioctl(fd[comno - 1], TIOCMGET, &status);    return status;}int comport_mdm_set(int comno, int status){    return ioctl(fd[comno - 1], TIOCMSET, &status);//    return 0;}/* *  FUNCTION: comport_close() * *  PARAMETERS: *			comno		COM Port Number (1 to MAX_COMPORT) * *  DESCRIPTION: *			Close COM port * *  RETURNS:  *			-1			comno out-of-range *			0			Success * */int comport_close(int comno){    if ((comno < 1) || (comno > MAX_COMPORT)) {        return -1;    }#if defined _WIN32    SetCommTimeouts(fd[comno - 1], &oldtimeouts[comno - 1]);    SetCommState(fd[comno - 1], &olddcb[comno - 1]);    CloseHandle(fd[comno - 1]);#else    tcsetattr(fd[comno - 1],TCSANOW,&oldtio[comno - 1]);    close(fd[comno - 1]);#endif    return 0;}#if COMPORT_MODULE_TEST > 0    #include "kbhit.h"#include <string.h>/* *  FUNCTION: main() * *  PARAMETERS: *			none * *  DESCRIPTION: *			Main function of module test code * *  RETURNS:  *			0		always * */uint16_t debug_mask = 0;int comport_write(int port, unsigned char *buf, int len){	int i;		for (i = 0; i < len; i++) {		comport_putc(port, buf[i]);	}	return 0;}void comport_flush(int port){	char ch;	while (comport_getc(port, &ch) > 0) {		printf("%c", ch);		fflush(stdout);        }}int main(void){    int fd;    char ch = 0;    char atcipstart[] = "at+cipstart=\"tcp\",\"xpanda.mine.nu\",\"8000\"\r\n";    char http_get[] = "GET /m2mtrac-ol1.bin HTTP/1.1\r\nHost: xpanda.mine.nu\r\n\r\n";    FILE *outfile;    int count =0;    printf("COMPORT MODULE TEST start\r\n");    printf("Passthrough character between serial port and local console\r\n");    printf("ttyUSB0 @ 115200bps 8N1 (ESC to quit)\r\n");    set_tty_raw();    fd = comport_open(1, 57600);    comport_write(1, "AT\r\n", 4);    sleep(1);    comport_flush(1);    comport_write(1, "AT\r\n", 4);    sleep(1);    comport_flush(1);    comport_write(1, "AT\r\n", 4);    sleep(5);    comport_flush(1);    comport_write(1, atcipstart, strlen(atcipstart));    sleep(10);    comport_flush(1);    comport_write(1, http_get, strlen(http_get));        count = 0;    outfile = fopen("output.log", "wb");    while (ch != 27) {        ch = kb_getc();        if (ch > 0) {	    printf("%c", ch);	    fflush(stdout);            comport_putc(1, ch);//	    if (ch == 0x0d) {//		comport_putc(1, 0x0a);//	    }        }        while (comport_getc(1, &ch) > 0) {//            printf("%02X ", ch);//            fflush(stdout);              count++;              fwrite(&ch, 1, 1, outfile);	      ch = 0;        }	printf("count=%d\r\n", count);    }    set_tty_cooked();    fclose(outfile);    comport_close(1);    printf("COMPORT MODULE TEST end\r\n");    printf("Total count = %d\r\n", count);    return 0;}#endif

⌨️ 快捷键说明

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