librfn
An ad-hoc utility library
console_ring.c
Go to the documentation of this file.
1 /*
2  * console_ring.c
3  *
4  * Part of librfn (a general utility library from redfelineninja.org.uk)
5  *
6  * This file was derived from libopencm3's usart_irq_printf.c example.
7  *
8  * Copyright (C) 2009 Uwe Hermann <uwe@hermann-uwe.de>,
9  * Copyright (C) 2011 Piotr Esden-Tempski <piotr@esden.net>
10  * Copyright (C) 2014 Daniel Thompson <daniel@redfelineninja.org.uk>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU Lesser General Public License as published
14  * by the Free Software Foundation; either version 3 of the License, or
15  * (at your option) any later version.
16  */
17 
18 #include <stdio.h>
19 #include <errno.h>
20 
21 #include <libopencm3/stm32/rcc.h>
22 #include <libopencm3/stm32/gpio.h>
23 #include <libopencm3/stm32/usart.h>
24 #include <libopencm3/cm3/nvic.h>
25 #include <libopencm3/cm3/systick.h>
26 
27 #include <librfn/console.h>
28 
29 /* prototype functions not found in the headers (for -Wmissing-prototypes) */
30 int _write(int file, char *ptr, int len);
31 
32 static uint8_t logbuf[1024];
33 static ringbuf_t logring = RINGBUF_VAR_INIT(logbuf, sizeof(logbuf));
34 
35 static console_t *logcon;
36 
38 {
39  logcon = c;
40 }
41 
42 static void logchar(char ch)
43 {
44  if (ringbuf_put(&logring, ch))
45  return;
46 
47  /* ring buffer is full, discard characters until end-of-line */
48  int discard;
49  do {
50  discard = ringbuf_get(&logring);
51  } while (discard != -1 && discard != '\n');
52 
53  ringbuf_put(&logring, ch);
54 }
55 
56 int _write(int file, char *ptr, int len)
57 {
58  if (file == 1 || file == 2) {
59  for (int i=0; i<len; i++)
60  logchar(ptr[i]);
61  return 0;
62  }
63 
64  errno = EIO;
65  return -1;
66 }
struct charlie c
#define RINGBUF_VAR_INIT(bufp, buf_len)
Static initializer for a ring buffer descriptor.
Definition: ringbuf.h:48
Console descriptor.
Definition: console.h:66
void console_hwinit(console_t *c)
Platform dependant function that will be called during console_init().
Definition: console_ring.c:37
Ring buffer descriptor.
Definition: ringbuf.h:38
int ringbuf_get(ringbuf_t *rb)
Extract a byte from the ring buffer.
Definition: ringbuf.c:31
int _write(int file, char *ptr, int len)
Definition: console_ring.c:56
bool ringbuf_put(ringbuf_t *rb, uint8_t d)
Insert a byte into the ring buffer.
Definition: ringbuf.c:58