Root/cngt/serial.c

1/*
2 * serial.c - Send data to a Modela MDX-15/20
3 *
4 * Written 2009 by Werner Almesberger
5 * Copyright 2009 Werner Almesberger
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 */
12
13
14#include <stdarg.h>
15#include <stdlib.h>
16#include <stdio.h>
17#include <unistd.h>
18#include <string.h>
19#include <fcntl.h>
20#include <termios.h>
21#include <sys/types.h>
22
23#include "serial.h"
24
25
26static int tty;
27static struct termios old;
28
29
30static void reset_tty(void)
31{
32    if (tty >= 0)
33        if (tcsetattr(tty, TCSADRAIN, &old) < 0)
34            perror("tcsetattr");
35}
36
37
38void serial_open(const char *name)
39{
40    struct termios new;
41
42
43    tty = open(name, O_WRONLY | O_NOCTTY);
44    if (tty < 0) {
45        perror(name);
46        exit(1);
47    }
48
49    if (tcgetattr(tty, &old) < 0) {
50        perror("tcgetattr");
51        exit(1);
52    }
53    atexit(reset_tty);
54
55    new = old;
56    cfmakeraw(&new);
57    cfsetospeed(&new, B9600);
58    new.c_iflag |= IXON;
59    new.c_cflag |= CLOCAL | CRTSCTS;
60    new.c_lflag &= ~ECHO;
61    if (tcsetattr(tty, TCSAFLUSH, &new) < 0) {
62        perror("tcsetattr");
63        exit(1);
64    }
65}
66
67
68void serial_close(void)
69{
70    reset_tty();
71    (void) close(tty);
72    tty = -1;
73}
74
75
76void serial_printf(const char *fmt, ...)
77{
78    char buf[10000]; /* more than enough :) */
79    va_list ap;
80    int len;
81    ssize_t wrote;
82
83    va_start(ap, fmt);
84    len = vsnprintf(buf, sizeof(buf), fmt, ap);
85    va_end(ap);
86    if (len >= sizeof(buf)-1) {
87        fprintf(stderr, "buffer too small\n");
88        exit(1);
89    }
90    wrote = write(tty, buf, strlen(buf));
91    if (wrote < 0) {
92        perror("write");
93        exit(1);
94    }
95    if (wrote != len) {
96        fprintf(stderr, "short write: %d < %d\n",
97            (int) wrote, (int) len);
98        exit(1);
99    }
100}
101

Archive Download this file

Branches:
master



interactive