ser_read(): Make buffer argument void * for consistency with ANSI C and ser_write()
[bertos.git] / drv / ser.c
1 /*!
2  * \file
3  * <!--
4  * Copyright 2003, 2004 Develer S.r.l. (http://www.develer.com/)
5  * Copyright 2000 Bernardo Innocenti <bernie@codewiz.org>
6  * This file is part of DevLib - See devlib/README for information.
7  * -->
8  *
9  * \brief Buffered serial I/O driver
10  *
11  * The serial rx interrupt buffers incoming data in a software FIFO
12  * to decouple the higher level protocols from the line speed.
13  * Outgoing data is buffered as well for better performance.
14  * This driver is not optimized for best performance, but it
15  * has proved to be fast enough to handle transfer rates up to
16  * 38400bps on a 16MHz 80196.
17  *
18  * MODULE CONFIGURATION
19  *
20  *  \li \c CONFIG_SER_HWHANDSHAKE - set to 1 to enable RTS/CTS handshake.
21  *         Support is incomplete/untested.
22  *  \li \c CONFIG_SER_TXTIMEOUT - Enable software serial transmission timeouts
23  *
24  *
25  * \version $Id$
26  * \author Bernardo Innocenti <bernie@develer.com>
27  */
28
29 /*
30  * $Log$
31  * Revision 1.13  2004/08/24 16:20:48  bernie
32  * ser_read(): Make buffer argument void * for consistency with ANSI C and ser_write()
33  *
34  * Revision 1.12  2004/08/24 13:49:39  bernie
35  * Fix thinko.
36  *
37  * Revision 1.11  2004/08/15 05:32:22  bernie
38  * ser_resync(): New function.
39  *
40  * Revision 1.10  2004/08/10 06:29:50  bernie
41  * Rename timer_gettick() to timer_ticks().
42  *
43  * Revision 1.9  2004/08/08 06:06:20  bernie
44  * Use new-style CONFIG_ idiom; Fix module-wide documentation.
45  *
46  * Revision 1.8  2004/07/29 22:57:09  bernie
47  * ser_drain(): New function; Make Serial::is_open a debug-only feature; Switch to new-style CONFIG_* macros.
48  *
49  * Revision 1.7  2004/07/18 21:49:03  bernie
50  * Make CONFIG_SER_DEFBAUDRATE optional.
51  *
52  * Revision 1.6  2004/06/07 15:56:28  aleph
53  * Remove cast-as-lvalue extension abuse
54  *
55  * Revision 1.5  2004/06/06 16:41:44  bernie
56  * ser_putchar(): Use fifo_push_locked() to fix potential race on 8bit processors.
57  *
58  * Revision 1.4  2004/06/03 11:27:09  bernie
59  * Add dual-license information.
60  *
61  * Revision 1.3  2004/06/02 21:35:24  aleph
62  * Serial enhancements: interruptible receive handler and 8 bit serial status for AVR; remove volatile attribute to FIFOBuffer, useless for new fifobuf routens
63  *
64  * Revision 1.2  2004/05/23 18:21:53  bernie
65  * Trim CVS logs and cleanup header info.
66  *
67  */
68
69 #include <mware/formatwr.h>
70 #include <drv/kdebug.h>
71 #include "ser.h"
72 #include "ser_p.h"
73 #include "hw.h"
74
75 #ifdef CONFIG_KERNEL
76         #include <kern/proc.h>
77 #endif
78 #if CONFIG_SER_TXTIMEOUT != -1 || CONFIG_SER_RXTIMEOUT != -1
79         #include <drv/timer.h>
80 #endif
81
82
83 /* Serial configuration parameters */
84 #define SER_CTSDELAY        70  /*!< CTS line retry interval (ms) */
85 #define SER_TXPOLLDELAY      2  /*!< Transmit buffer full retry interval (ms) */
86 #define SER_RXPOLLDELAY      2  /*!< Receive buffer empty retry interval (ms) */
87
88
89 struct Serial ser_handles[SER_CNT];
90
91
92 /*!
93  * Inserisce il carattere c nel buffer di trasmissione.
94  * Questa funzione mette il processo chiamante in attesa
95  * quando il buffer e' pieno.
96  *
97  * \return EOF in caso di errore o timeout, altrimenti
98  *         il carattere inviato.
99  */
100 int ser_putchar(int c, struct Serial *port)
101 {
102         if (fifo_isfull_locked(&port->txfifo))
103         {
104 #if CONFIG_SER_TXTIMEOUT != -1
105                 time_t start_time = timer_ticks();
106 #endif
107
108                 /* Attende finche' il buffer e' pieno... */
109                 do
110                 {
111 #if defined(CONFIG_KERN_SCHED) && CONFIG_KERN_SCHED
112                         /* Give up timeslice to other processes. */
113                         proc_switch();
114 #endif
115 #if CONFIG_SER_TXTIMEOUT != -1
116                         if (timer_ticks() - start_time >= port->txtimeout)
117                         {
118                                 port->status |= SERRF_TXTIMEOUT;
119                                 return EOF;
120                         }
121 #endif /* CONFIG_SER_TXTIMEOUT */
122                 }
123                 while (fifo_isfull_locked(&port->txfifo));
124         }
125
126         fifo_push_locked(&port->txfifo, (unsigned char)c);
127
128         /* (re)trigger tx interrupt */
129         port->hw->table->enabletxirq(port->hw);
130
131         /* Avoid returning signed estended char */
132         return (int)((unsigned char)c);
133 }
134
135
136 /*!
137  * Preleva un carattere dal buffer di ricezione.
138  * Questa funzione mette il processo chiamante in attesa
139  * quando il buffer e' vuoto. L'attesa ha un timeout
140  * di ser_rxtimeout millisecondi.
141  *
142  * \return EOF in caso di errore o timeout, altrimenti
143  *         il carattere ricevuto.
144  */
145 int ser_getchar(struct Serial *port)
146 {
147         int result;
148
149         if (fifo_isempty_locked(&port->rxfifo))
150         {
151 #if CONFIG_SER_RXTIMEOUT != -1
152                 time_t start_time = timer_ticks();
153 #endif
154                 /* Wait while buffer is empty */
155                 do
156                 {
157 #if defined(CONFIG_KERN_SCHED) && CONFIG_KERN_SCHED
158                         /* Give up timeslice to other processes. */
159                         proc_switch();
160 #endif
161 #if CONFIG_SER_RXTIMEOUT != -1
162                         if (timer_ticks() - start_time >= port->rxtimeout)
163                         {
164                                 port->status |= SERRF_RXTIMEOUT;
165                                 return EOF;
166                         }
167 #endif /* CONFIG_SER_RXTIMEOUT */
168                 }
169                 while (fifo_isempty_locked(&port->rxfifo));
170         }
171
172         /*
173          * Get a byte from the FIFO (avoiding sign-extension),
174          * re-enable RTS, then return result.
175          */
176         result = (int)(unsigned char)fifo_pop(&port->rxfifo);
177         return port->status ? EOF : result;
178 }
179
180
181 /*!
182  * Preleva un carattere dal buffer di ricezione.
183  * Se il buffer e' vuoto, ser_getchar_nowait() ritorna
184  * immediatamente EOF.
185  */
186 int ser_getchar_nowait(struct Serial *port)
187 {
188         if (fifo_isempty_locked(&port->rxfifo))
189                 return EOF;
190
191         /* NOTE: the double cast prevents unwanted sign extension */
192         return (int)(unsigned char)fifo_pop(&port->rxfifo);
193 }
194
195
196 #if CONFIG_SER_GETS
197 /*!
198  * Read a line long at most as size and puts it
199  * in buf.
200  * \return number of chars read or EOF in case
201  *         of error.
202  */
203 int ser_gets(struct Serial *port, char *buf, int size)
204 {
205         return ser_gets_echo(port, buf, size, false);
206 }
207
208
209 /*!
210  * Read a line long at most as size and put it
211  * in buf, with optional echo.
212  *
213  * \return number of chars read, or EOF in case
214  *         of error.
215  */
216 int ser_gets_echo(struct Serial *port, char *buf, int size, bool echo)
217 {
218         int i = 0;
219         int c;
220
221         for (;;)
222         {
223                 if ((c = ser_getchar(port)) == EOF)
224                 {
225                         buf[i] = '\0';
226                         return -1;
227                 }
228
229                 /* FIXME */
230                 if (c == '\r' || c == '\n' || i >= size-1)
231                 {
232                         buf[i] = '\0';
233                         if (echo)
234                                 ser_print(port, "\r\n");
235                         break;
236                 }
237                 buf[i++] = c;
238                 if (echo)
239                         ser_putchar(c, port);
240         }
241
242         return i;
243 }
244 #endif /* !CONFIG_SER_GETS */
245
246
247 /*!
248  * Read at most size bytes and puts them
249  * in buf.
250  * \return number of bytes read or EOF in case
251  *         of error.
252  */
253 int ser_read(struct Serial *port, void *buf, size_t size)
254 {
255         size_t i = 0;
256         int c;
257
258         while (i < size)
259         {
260                 if ((c = ser_getchar(port)) == EOF)
261                         return EOF;
262                 buf[i++] = c;
263         }
264
265         return i;
266 }
267
268
269 /*!
270  * Write a string to serial.
271  * \return 0 if OK, EOF in case of error.
272  */
273 int ser_print(struct Serial *port, const char *s)
274 {
275         while (*s)
276         {
277                 if (ser_putchar(*s++, port) == EOF)
278                         return EOF;
279         }
280         return 0;
281 }
282
283
284 /*!
285  * \brief Write a buffer to serial.
286  *
287  * \return 0 if OK, EOF in case of error.
288  *
289  * \todo Optimize with fifo_pushblock()
290  */
291 int ser_write(struct Serial *port, const void *_buf, size_t len)
292 {
293         const char *buf = _buf;
294
295         while (len--)
296         {
297                 if (ser_putchar(*buf++, port) == EOF)
298                         return EOF;
299         }
300         return 0;
301 }
302
303
304 #if CONFIG_PRINTF
305 /*!
306  * Formatted write
307  */
308 int ser_printf(struct Serial *port, const char *format, ...)
309 {
310         va_list ap;
311         int len;
312
313         ser_setstatus(port, 0);
314         va_start(ap, format);
315         len = _formatted_write(format, (void (*)(char, void *))ser_putchar, port, ap);
316         va_end(ap);
317
318         return len;
319 }
320 #endif /* CONFIG_PRINTF */
321
322
323 #if CONFIG_SER_RXTIMEOUT != -1 || CONFIG_SER_TXTIMEOUT != -1
324 void ser_settimeouts(struct Serial *port, time_t rxtimeout, time_t txtimeout)
325 {
326         port->rxtimeout = rxtimeout;
327         port->txtimeout = txtimeout;
328 }
329 #endif /* CONFIG_SER_RXTIMEOUT || CONFIG_SER_TXTIMEOUT */
330
331 #if CONFIG_SER_RXTIMEOUT != -1
332 /*!
333  * Discard input to resynchronize with remote end
334  *
335  * Discard incoming data until the port stops receiving
336  * characters for at least \a delay milliseconds.
337  *
338  * \note Serial errors are reset before and after executing the purge.
339  */
340 void ser_resync(struct Serial *port, time_t delay)
341 {
342         time_t old_rxtimeout = port->rxtimeout;
343
344         ser_settimeouts(delay, ser->txtimeout);
345         do
346         {
347                 ser_setstatus(port, 0);
348                 ser_getchar(port);
349         }
350         while (!(ser_getstatus(port) & SERRF_RXTIMEOUT));
351
352         /* Restore port to an usable status */
353         ser_setstatus(port, 0);
354         ser_settimeouts(old_rxtimeout, ser->txtimeout);
355 }
356 #endif /* CONFIG_SER_RXTIMEOUT */
357
358
359 void ser_setbaudrate(struct Serial *port, unsigned long rate)
360 {
361         port->hw->table->setbaudrate(port->hw, rate);
362 }
363
364
365 void ser_setparity(struct Serial *port, int parity)
366 {
367         port->hw->table->setparity(port->hw, parity);
368 }
369
370
371 /*!
372  * Flush both the RX and TX buffers.
373  */
374 void ser_purge(struct Serial *port)
375 {
376         fifo_flush_locked(&port->rxfifo);
377         fifo_flush_locked(&port->txfifo);
378 }
379
380
381 /*!
382  * Wait until all pending output is completely
383  * transmitted to the other end.
384  *
385  * \note The current implementation only checks the
386  *       software transmission queue. Any hardware
387  *       FIFOs are ignored.
388  */
389 void ser_drain(struct Serial *ser)
390 {
391         while (!fifo_isempty(&ser->txfifo))
392         {
393 #if defined(CONFIG_KERN_SCHED) && CONFIG_KERN_SCHED
394                         /* Give up timeslice to other processes. */
395                         proc_switch();
396 #endif
397         }
398 }
399
400
401 /*!
402  * Initialize serial
403  */
404 struct Serial *ser_open(unsigned int unit)
405 {
406         struct Serial *port;
407
408         ASSERT(unit < countof(ser_handles));
409         port = &ser_handles[unit];
410
411         ASSERT(!port->is_open);
412         DB(port->is_open = true;)
413
414         port->unit = unit;
415
416         /* Initialize circular buffer */
417         fifo_init(&port->rxfifo, port->rxbuffer, sizeof(port->rxbuffer));
418         fifo_init(&port->txfifo, port->txbuffer, sizeof(port->txbuffer));
419
420         port->hw = ser_hw_getdesc(unit);
421         port->hw->table->init(port->hw, port);
422
423         /* Set default values */
424 #if CONFIG_SER_RXTIMEOUT != -1 || CONFIG_SER_TXTIMEOUT != -1
425         ser_settimeouts(port, CONFIG_SER_RXTIMEOUT, CONFIG_SER_TXTIMEOUT);
426 #endif
427 #if CONFIG_SER_DEFBAUDRATE
428         ser_setbaudrate(port, CONFIG_SER_DEFBAUDRATE);
429 #endif
430
431         return port;
432 }
433
434
435 /*!
436  * Clean up serial port, disabling the associated hardware.
437  */
438 void ser_close(struct Serial *port)
439 {
440         ASSERT(port->is_open);
441         DB(port->is_open = false;)
442
443         port->hw->table->cleanup(port->hw);
444         port->hw = NULL;
445 }