summaryrefslogtreecommitdiff
path: root/hw/mcu/native/src/hal_uart.c
blob: c30a414839b8f74ec0a060ba81f3ba51b21c7f4d (plain)
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

#include "os/os.h"
#include "hal/hal_uart.h"
#include "bsp/bsp.h"

#ifdef MN_LINUX
#include <pty.h>
#endif
#ifdef MN_OSX
#include <util.h>
#endif
#include <ctype.h>
#include <stdio.h>
#include <fcntl.h>
#include <assert.h>
#include <unistd.h>
#include <string.h>

#define UART_MAX_BYTES_PER_POLL	64
#define UART_POLLER_STACK_SZ	OS_STACK_ALIGN(1024)
#define UART_POLLER_PRIO	0

struct uart {
    int u_open;
    int u_fd;
    int u_tx_run;
    int u_rx_char;
    hal_uart_rx_char u_rx_func;
    hal_uart_tx_char u_tx_func;
    hal_uart_tx_done u_tx_done;
    void *u_func_arg;
};

/*
 * XXXX should try to use O_ASYNC/SIGIO for byte arrival notification,
 * so we wouldn't need an OS for pseudo ttys.
 */
char *native_uart_log_file = NULL;
static int uart_log_fd = -1;

static struct uart uarts[UART_CNT];
static int uart_poller_running;
static struct os_task uart_poller_task;
static os_stack_t uart_poller_stack[UART_POLLER_STACK_SZ];

static void
uart_open_log(void)
{
    if (native_uart_log_file && uart_log_fd < 0) {
        uart_log_fd = open(native_uart_log_file, O_WRONLY | O_CREAT | O_TRUNC,
          0666);
        assert(uart_log_fd >= 0);
    }
}

static void
uart_log_data(struct uart *u, int istx, uint8_t data)
{
    static struct {
        struct uart *uart;
        int istx;
        uint32_t time;
        int chars_in_line;
    } state = {
        .uart = NULL,
        .istx = 0
    };
    uint32_t now;
    char tmpbuf[32];
    int len;

    if (uart_log_fd < 0) {
        return;
    }
    now = os_time_get();
    if (state.uart) {
        if (u != state.uart || now != state.time || istx != state.istx) {
            /*
             * End current printout.
             */
            if (write(uart_log_fd, "\n", 1) != 1) {
                assert(0);
            }
            state.uart = NULL;
        } else {
            if (state.chars_in_line == 8) {
                if (write(uart_log_fd, "\n\t", 2) != 2) {
                    assert(0);
                }
                state.chars_in_line = 0;
            }
            len = snprintf(tmpbuf, sizeof(tmpbuf), "%c (%02x) ",
              isalnum(data) ? data : '?', data);
            if (write(uart_log_fd, tmpbuf, len) != len) {
                assert(0);
            }
            state.chars_in_line++;
        }
    }
    if (u && state.uart == NULL) {
        len = snprintf(tmpbuf, sizeof(tmpbuf), "%u:uart%d %s\n\t%c (%02x) ",
          now, u - uarts, istx ? "tx" : "rx", isalnum(data) ? data : '?', data);
        if (write(uart_log_fd, tmpbuf, len) != len) {
            assert(0);
        }
        state.chars_in_line = 1;
        state.uart = u;
        state.istx = istx;
        state.time = now;
    }
}

static int
uart_transmit_char(struct uart *uart)
{
    int sr;
    int rc;
    char ch;

    OS_ENTER_CRITICAL(sr);
    rc = uart->u_tx_func(uart->u_func_arg);
    if (rc < 0) {
        /*
         * No more data to send.
         */
        uart->u_tx_run = 0;
        if (uart->u_tx_done) {
            uart->u_tx_done(uart->u_func_arg);
        }
        OS_EXIT_CRITICAL(sr);
        return 0;
    }
    uart_log_data(uart, 1, ch);
    OS_EXIT_CRITICAL(sr);
    ch = rc;
    rc = write(uart->u_fd, &ch, 1);
    if (rc <= 0) {
        /* XXX EOF/error, what now? */
        return -1;
    }
    return 0;
}

static void
uart_poller(void *arg)
{
    int i;
    int rc;
    int bytes;
    int sr;
    char ch;
    struct uart *uart;

    while (1) {
        for (i = 0; i < UART_CNT; i++) {
            if (!uarts[i].u_open) {
                continue;
            }
            uart = &uarts[i];

            for (bytes = 0; bytes < UART_MAX_BYTES_PER_POLL; bytes++) {
                if (uart->u_tx_run) {
                    uart_transmit_char(uart);
                }
            }
            for (bytes = 0; bytes < UART_MAX_BYTES_PER_POLL; bytes++) {
                if (uart->u_rx_char < 0) {
                    rc = read(uart->u_fd, &ch, 1);
                    if (rc == 0) {
                        /* XXX EOF, what now? */
                        assert(0);
                    } else if (rc < 0) {
                        break;
                    } else {
                        uart->u_rx_char = ch;
                    }
                }
                if (uart->u_rx_char >= 0) {
                    OS_ENTER_CRITICAL(sr);
                    uart_log_data(uart, 0, uart->u_rx_char);
                    rc = uart->u_rx_func(uart->u_func_arg, uart->u_rx_char);
                    /* Delivered */
                    if (rc >= 0) {
                        uart->u_rx_char = -1;
                    }
                    OS_EXIT_CRITICAL(sr);
                }
            }
        }
        uart_log_data(NULL, 0, 0);
        os_time_delay(10);
    }
}

static void
set_nonblock(int fd)
{
    int flags;

    flags = fcntl(fd, F_GETFL);
    if (flags == -1) {
        const char msg[] = "fcntl(F_GETFL) fail";
        write(1, msg, sizeof(msg));
        return;
    }
    if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0) {
        const char msg[] = "fcntl(F_SETFL) fail";
        write(1, msg, sizeof(msg));
        return;
    }
}

static int
uart_set_attr(int fd)
{
    struct termios tios;

    if (tcgetattr(fd, &tios)) {
        const char msg[] = "tcgetattr() failed";
        write(1, msg, sizeof(msg));
        return -1;
    }

    tios.c_cflag &= ~(CSIZE | CSTOPB | PARENB);
    tios.c_cflag |= CS8 | CREAD;
    tios.c_iflag = IGNPAR | IXON;
    tios.c_oflag = 0;
    tios.c_lflag = 0;
    if (tcsetattr(fd, TCSAFLUSH, &tios) < 0) {
        const char msg[] = "tcsetattr() failed";
        write(1, msg, sizeof(msg));
        return -1;
    }
    return 0;
}

static int
uart_pty(int port)
{
    int fd;
    int loop_slave;
    char pty_name[32];
    char msg[64];

    if (openpty(&fd, &loop_slave, pty_name, NULL, NULL) < 0) {
        const char msg[] = "openpty() failed";
        write(1, msg, sizeof(msg));
        return -1;
    }

    if (uart_set_attr(loop_slave)) {
        goto err;
    }

    snprintf(msg, sizeof(msg), "uart%d at %s\n", port, pty_name);
    write(1, msg, strlen(msg));
    return fd;
err:
    close(fd);
    close(loop_slave);
    return -1;
}

void
hal_uart_start_tx(int port)
{
    int sr;

    if (port >= UART_CNT || uarts[port].u_open == 0) {
        return;
    }
    OS_ENTER_CRITICAL(sr);
    uarts[port].u_tx_run = 1;
    if (!os_started()) {
        /*
         * XXX this is a hack.
         */
        uart_transmit_char(&uarts[port]);
    }
    OS_EXIT_CRITICAL(sr);
}

void
hal_uart_start_rx(int port)
{
    /* nothing to do here */
}

void
hal_uart_blocking_tx(int port, uint8_t data)
{
    if (port >= UART_CNT || uarts[port].u_open == 0) {
        return;
    }

    /* XXX: Count statistics and add error checking here. */
    (void) write(uarts[port].u_fd, &data, sizeof(data));
}

int
hal_uart_init_cbs(int port, hal_uart_tx_char tx_func, hal_uart_tx_done tx_done,
  hal_uart_rx_char rx_func, void *arg)
{
    struct uart *uart;
    int rc;

    if (port >= UART_CNT) {
        return -1;
    }

    uart = &uarts[port];
    if (uart->u_open) {
        return -1;
    }
    uart->u_tx_func = tx_func;
    uart->u_tx_done = tx_done;
    uart->u_rx_func = rx_func;
    uart->u_func_arg = arg;
    uart->u_rx_char = -1;

    if (!uart_poller_running) {
        uart_poller_running = 1;
        rc = os_task_init(&uart_poller_task, "uart_poller", uart_poller, NULL,
          UART_POLLER_PRIO, OS_WAIT_FOREVER, uart_poller_stack,
          UART_POLLER_STACK_SZ);
        assert(rc == 0);
    }
    return 0;
}

int
hal_uart_config(int port, int32_t baudrate, uint8_t databits, uint8_t stopbits,
  enum hal_uart_parity parity, enum hal_uart_flow_ctl flow_ctl)
{
    struct uart *uart;

    if (port >= UART_CNT) {
        return -1;
    }

    uart = &uarts[port];
    if (uart->u_open) {
        return -1;
    }

    uart->u_fd = uart_pty(port);
    if (uart->u_fd < 0) {
        return -1;
    }
    set_nonblock(uart->u_fd);

    uart_open_log();
    uart->u_open = 1;
    return 0;
}