File: serial.c

package info (click to toggle)
linuxptp 4.2-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 1,536 kB
  • sloc: ansic: 26,119; sh: 92; makefile: 87
file content (105 lines) | stat: -rw-r--r-- 2,006 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/**
 * @file serial.c
 * @note Copyright (C) 2020 Richard Cochran <richardcochran@gmail.com>
 * @note SPDX-License-Identifier: GPL-2.0+
 */
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <termios.h>

#include "print.h"
#include "serial.h"

#define CANONICAL 1

static int open_serial_baud(const char *name, tcflag_t baud, int icrnl, int hwfc)
{
	struct termios nterm;
	int fd;

	fd = open(name, O_RDWR | O_NOCTTY);
	if (fd < 0) {
		pr_err("cannot open %s : %m", name);
		return fd;
	}
	memset(&nterm, 0, sizeof(nterm));

	/* Input Modes */
	nterm.c_iflag = IGNPAR; /* Ignore framing errors and parity errors */
	if (icrnl) {
		/* Translate carriage return to newline on input */
		nterm.c_iflag |= ICRNL;
	}

	/* Output Modes */
	nterm.c_oflag = 0;

	/* Control Modes */
	nterm.c_cflag = baud;
	nterm.c_cflag |= CS8;    /* Character size */
	nterm.c_cflag |= CLOCAL; /* Ignore modem control lines */
	nterm.c_cflag |= CREAD;  /* Enable receiver */
	if (hwfc) {
		/* Enable RTS/CTS (hardware) flow control */
		nterm.c_cflag |= CRTSCTS;
	}

	/* Local Modes */
	if (CANONICAL) {
		nterm.c_lflag = ICANON; /* Enable canonical mode */
	}

	nterm.c_cc[VTIME] = 10;   /* timeout is 10 deciseconds */
	nterm.c_cc[VMIN] = 1;     /* blocking read until N chars received */
	tcflush(fd, TCIFLUSH);
	tcsetattr(fd, TCSANOW, &nterm);
	return fd;
}

int serial_open(const char *name, int bps, int icrnl, int hwfc)
{
	tcflag_t baud;

	switch (bps) {
	case 1200:
		baud = B1200;
		break;
	case 1800:
		baud = B1800;
		break;
	case 2400:
		baud = B2400;
		break;
	case 4800:
		baud = B4800;
		break;
	case 9600:
		baud = B9600;
		break;
	case 19200:
		baud = B19200;
		break;
	case 38400:
		baud = B38400;
		break;
	case 57600:
		baud = B57600;
		break;
	case 115200:
		baud = B115200;
		break;
	case 230400:
		baud = B230400;
		break;
	case 460800:
		baud = B460800;
		break;
	case 921600:
		baud = B921600;
		break;
	default:
		return -1;
	}
	return open_serial_baud(name, baud, icrnl, hwfc);
}