Handle rx fifo overflow error.
[bertos.git] / bertos / net / afsk.c
1 /**
2  * \file
3  * <!--
4  * This file is part of BeRTOS.
5  *
6  * Bertos is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  * As a special exception, you may use this file as part of a free software
21  * library without restriction.  Specifically, if other files instantiate
22  * templates or use macros or inline functions from this file, or you compile
23  * this file and link it with other files to produce an executable, this
24  * file does not by itself cause the resulting executable to be covered by
25  * the GNU General Public License.  This exception does not however
26  * invalidate any other reasons why the executable file might be covered by
27  * the GNU General Public License.
28  *
29  * Copyright 2008 Develer S.r.l. (http://www.develer.com/)
30  *
31  * -->
32  *
33  * \brief AFSK1200 modem.
34  *
35  * \version $Id$
36  * \author Francesco Sacchi <asterix@develer.com>
37  */
38
39 #include "afsk.h"
40 #include <net/ax25.h>
41
42 #include "cfg/cfg_afsk.h"
43 #include "hw/hw_afsk.h"
44
45 #include <drv/timer.h>
46
47 #include <cfg/module.h>
48
49 #define LOG_LEVEL   AFSK_LOG_LEVEL
50 #define LOG_FORMAT  AFSK_LOG_FORMAT
51 #include <cfg/log.h>
52
53 #include <cpu/power.h>
54 #include <cpu/pgm.h>
55 #include <struct/fifobuf.h>
56
57 #include <string.h> /* memset */
58
59 #define PHASE_BIT    8
60 #define PHASE_INC    1
61
62 #define PHASE_MAX    (SAMPLEPERBIT * PHASE_BIT)
63 #define PHASE_THRES  (PHASE_MAX / 2) // - PHASE_BIT / 2)
64
65 // Modulator constants
66 #define MARK_FREQ  1200
67 #define MARK_INC   (uint16_t)(DIV_ROUND(SIN_LEN * (uint32_t)MARK_FREQ, CONFIG_AFSK_DAC_SAMPLERATE))
68
69 #define SPACE_FREQ 2200
70 #define SPACE_INC  (uint16_t)(DIV_ROUND(SIN_LEN * (uint32_t)SPACE_FREQ, CONFIG_AFSK_DAC_SAMPLERATE))
71
72 //Ensure sample rate is a multiple of bit rate
73 STATIC_ASSERT(!(CONFIG_AFSK_DAC_SAMPLERATE % BITRATE));
74
75 #define DAC_SAMPLEPERBIT (CONFIG_AFSK_DAC_SAMPLERATE / BITRATE)
76
77 /**
78  * Sine table for the first quarter of wave.
79  * The rest of the wave is computed from this first quarter.
80  * This table is used to generate the modulated data.
81  */
82 static const uint8_t PROGMEM sin_table[] =
83 {
84         128, 129, 131, 132, 134, 135, 137, 138, 140, 142, 143, 145, 146, 148, 149, 151,
85         152, 154, 155, 157, 158, 160, 162, 163, 165, 166, 167, 169, 170, 172, 173, 175,
86         176, 178, 179, 181, 182, 183, 185, 186, 188, 189, 190, 192, 193, 194, 196, 197,
87         198, 200, 201, 202, 203, 205, 206, 207, 208, 210, 211, 212, 213, 214, 215, 217,
88         218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233,
89         234, 234, 235, 236, 237, 238, 238, 239, 240, 241, 241, 242, 243, 243, 244, 245,
90         245, 246, 246, 247, 248, 248, 249, 249, 250, 250, 250, 251, 251, 252, 252, 252,
91         253, 253, 253, 253, 254, 254, 254, 254, 254, 255, 255, 255, 255, 255, 255, 255,
92 };
93
94 #define SIN_LEN 512 ///< Full wave length
95
96 STATIC_ASSERT(sizeof(sin_table) == SIN_LEN / 4);
97
98
99 /**
100  * Given the index, this function computes the correct sine sample
101  * based only on the first quarter of wave.
102  */
103 INLINE uint8_t sin_sample(uint16_t idx)
104 {
105         ASSERT(idx < SIN_LEN);
106         uint16_t new_idx = idx % (SIN_LEN / 2);
107         new_idx = (new_idx >= (SIN_LEN / 4)) ? (SIN_LEN / 2 - new_idx - 1) : new_idx;
108
109         #if CPU_HARVARD
110                 uint8_t data = pgm_read_char(&sin_table[new_idx]);
111         #else
112                 uint8_t data = sin_table[new_idx];
113         #endif
114
115         return (idx >= (SIN_LEN / 2)) ? (255 - data) : data;
116 }
117
118
119 #define BIT_DIFFER(bitline1, bitline2) (((bitline1) ^ (bitline2)) & 0x01)
120 #define EDGE_FOUND(bitline)            BIT_DIFFER((bitline), (bitline) >> 1)
121
122
123 static bool hdlc_parse(Hdlc *hdlc, bool bit, FIFOBuffer *fifo)
124 {
125         bool ret = true;
126
127         hdlc->demod_bits <<= 1;
128         hdlc->demod_bits |= bit ? 1 : 0;
129
130         /* HDLC Flag */
131         if (hdlc->demod_bits == HDLC_FLAG)
132         {
133                 if (!fifo_isfull(fifo))
134                 {
135                         fifo_push(fifo, HDLC_FLAG);
136                         hdlc->rxstart = true;
137                 }
138                 else
139                 {
140                         ret = false;
141                         hdlc->rxstart = false;
142                 }
143
144                 hdlc->currchar = 0;
145                 hdlc->bit_idx = 0;
146                 return ret;
147         }
148
149         /* Reset */
150         if ((hdlc->demod_bits & HDLC_RESET) == HDLC_RESET)
151         {
152                 hdlc->rxstart = false;
153                 return ret;
154         }
155
156         if (!hdlc->rxstart)
157                 return ret;
158
159         /* Stuffed bit */
160         if ((hdlc->demod_bits & 0x3f) == 0x3e)
161                 return ret;
162
163         if (hdlc->demod_bits & 0x01)
164                 hdlc->currchar |= 0x80;
165
166         if (++hdlc->bit_idx >= 8)
167         {
168                 if ((hdlc->currchar == HDLC_FLAG
169                         || hdlc->currchar == HDLC_RESET
170                         || hdlc->currchar == AX25_ESC))
171                 {
172                         if (!fifo_isfull(fifo))
173                                 fifo_push(fifo, AX25_ESC);
174                         else
175                         {
176                                 hdlc->rxstart = false;
177                                 ret = false;
178                         }
179                 }
180
181                 if (!fifo_isfull(fifo))
182                         fifo_push(fifo, hdlc->currchar);
183                 else
184                 {
185                         hdlc->rxstart = false;
186                         ret = false;
187                 }
188
189                 hdlc->currchar = 0;
190                 hdlc->bit_idx = 0;
191         }
192         else
193                 hdlc->currchar >>= 1;
194
195         return ret;
196 }
197
198
199 /**
200  * ADC ISR callback.
201  * This function has to be called by the ADC ISR when a sample of the configured
202  * channel is available.
203  * \param af Afsk context to operate one (\see Afsk).
204  * \param curr_sample current sample from the ADC.
205  */
206 void afsk_adc_isr(Afsk *af, int8_t curr_sample)
207 {
208         AFSK_STROBE_ON();
209
210         /*
211          * Frequency discriminator and LP IIR filter.
212          * This filter is designed to work
213          * at the given sample rate and bit rate.
214          */
215         STATIC_ASSERT(SAMPLERATE == 9600);
216         STATIC_ASSERT(BITRATE == 1200);
217
218         /*
219          * Frequency discrimination is achieved by simply multiplying
220          * the sample with a delayed sample of (samples per bit) / 2.
221          * Then the signal is lowpass filtered with a first order,
222          * 600 Hz filter. The filter implementation is selectable
223          * through the CONFIG_AFSK_FILTER config variable.
224          */
225
226         af->iir_x[0] = af->iir_x[1];
227
228         #if (CONFIG_AFSK_FILTER == AFSK_BUTTERWORTH)
229                 af->iir_x[1] = ((int8_t)fifo_pop(&af->delay_fifo) * curr_sample) >> 2;
230                 //af->iir_x[1] = ((int8_t)fifo_pop(&af->delay_fifo) * curr_sample) / 6.027339492;
231         #elif (CONFIG_AFSK_FILTER == AFSK_CHEBYSHEV)
232                 af->iir_x[1] = ((int8_t)fifo_pop(&af->delay_fifo) * curr_sample) >> 2;
233                 //af->iir_x[1] = ((int8_t)fifo_pop(&af->delay_fifo) * curr_sample) / 3.558147322;
234         #else
235                 #error Filter type not found!
236         #endif
237
238         af->iir_y[0] = af->iir_y[1];
239
240         #if CONFIG_AFSK_FILTER == AFSK_BUTTERWORTH
241                 /*
242                  * This strange sum + shift is an optimization for af->iir_y[0] * 0.668.
243                  * iir * 0.668 ~= (iir * 21) / 32 =
244                  * = (iir * 16) / 32 + (iir * 4) / 32 + iir / 32 =
245                  * = iir / 2 + iir / 8 + iir / 32 =
246                  * = iir >> 1 + iir >> 3 + iir >> 5
247                  */
248                 af->iir_y[1] = af->iir_x[0] + af->iir_x[1] + (af->iir_y[0] >> 1) + (af->iir_y[0] >> 3) + (af->iir_y[0] >> 5);
249                 //af->iir_y[1] = af->iir_x[0] + af->iir_x[1] + af->iir_y[0] * 0.6681786379;
250         #elif CONFIG_AFSK_FILTER == AFSK_CHEBYSHEV
251                 /*
252                  * This should be (af->iir_y[0] * 0.438) but
253                  * (af->iir_y[0] >> 1) is a faster approximation :-)
254                  */
255                 af->iir_y[1] = af->iir_x[0] + af->iir_x[1] + (af->iir_y[0] >> 1);
256                 //af->iir_y[1] = af->iir_x[0] + af->iir_x[1] + af->iir_y[0] * 0.4379097269;
257         #endif
258
259         /* Save this sampled bit in a delay line */
260         af->sampled_bits <<= 1;
261         af->sampled_bits |= (af->iir_y[1] > 0) ? 1 : 0;
262
263         /* Store current ADC sample in the af->delay_fifo */
264         fifo_push(&af->delay_fifo, curr_sample);
265
266         /* If there is an edge, adjust phase sampling */
267         if (EDGE_FOUND(af->sampled_bits))
268         {
269                 if (af->curr_phase < PHASE_THRES)
270                         af->curr_phase += PHASE_INC;
271                 else
272                         af->curr_phase -= PHASE_INC;
273         }
274         af->curr_phase += PHASE_BIT;
275
276         /* sample the bit */
277         if (af->curr_phase >= PHASE_MAX)
278         {
279                 af->curr_phase %= PHASE_MAX;
280
281                 /* Shift 1 position in the shift register of the found bits */
282                 af->found_bits <<= 1;
283
284                 /*
285                  * Determine bit value by reading the last 3 sampled bits.
286                  * If the number of ones is two or greater, the bit value is a 1,
287                  * otherwise is a 0.
288                  * This algorithm presumes that there are 8 samples per bit.
289                  */
290                 STATIC_ASSERT(SAMPLEPERBIT == 8);
291                 uint8_t bits = af->sampled_bits & 0x07;
292                 if (bits == 0x07 // 111, 3 bits set to 1
293                  || bits == 0x06 // 110, 2 bits
294                  || bits == 0x05 // 101, 2 bits
295                  || bits == 0x03 // 011, 2 bits
296                 )
297                         af->found_bits |= 1;
298
299                 /*
300                  * NRZI coding: if 2 consecutive bits have the same value
301                  * a 1 is received, otherwise it's a 0.
302                  */
303                 if (!hdlc_parse(&af->hdlc, !EDGE_FOUND(af->found_bits), &af->rx_fifo))
304                         af->status |= AFSK_RXFIFO_OVERRUN;
305         }
306
307
308         AFSK_STROBE_OFF();
309 }
310
311 static void afsk_txStart(Afsk *af)
312 {
313         if (!af->sending)
314         {
315                 af->phase_inc = MARK_INC;
316                 af->phase_acc = 0;
317                 af->stuff_cnt = 0;
318                 af->sending = true;
319                 af->preamble_len = DIV_ROUND(CONFIG_AFSK_PREAMBLE_LEN * BITRATE, 8000);
320                 AFSK_DAC_IRQ_START(af->dac_ch);
321         }
322         ATOMIC(af->trailer_len  = DIV_ROUND(CONFIG_AFSK_TRAILER_LEN  * BITRATE, 8000));
323 }
324
325 #define BIT_STUFF_LEN 5
326
327 #define SWITCH_TONE(inc)  (((inc) == MARK_INC) ? SPACE_INC : MARK_INC)
328
329 /**
330  * DAC ISR callback.
331  * This function has to be called by the DAC ISR when a sample of the configured
332  * channel has been converted out.
333  *
334  * \param af Afsk context to operate one (\see Afsk).
335  *
336  * \note The next DAC output sample is supplied by the Afsk driver through calling
337  *        the AFSK_DAC_SET() callback.
338  */
339 void afsk_dac_isr(Afsk *af)
340 {
341         /* Check if we are at a start of a sample cycle */
342         if (af->sample_count == 0)
343         {
344                 if (af->tx_bit == 0)
345                 {
346                         /* We have just finished transimitting a char, get a new one. */
347                         if (fifo_isempty(&af->tx_fifo) && af->trailer_len == 0)
348                         {
349                                 AFSK_DAC_IRQ_STOP(af->dac_ch);
350                                 af->sending = false;
351                                 return;
352                         }
353                         else
354                         {
355                                 /*
356                                  * If we have just finished sending an unstuffed byte,
357                                  * reset bitstuff counter.
358                                  */
359                                 if (!af->bit_stuff)
360                                         af->stuff_cnt = 0;
361
362                                 af->bit_stuff = true;
363
364                                 /*
365                                  * Handle preamble and trailer
366                                  */
367                                 if (af->preamble_len == 0)
368                                 {
369                                         if (fifo_isempty(&af->tx_fifo))
370                                         {
371                                                 af->trailer_len--;
372                                                 af->curr_out = HDLC_FLAG;
373                                         }
374                                         else
375                                                 af->curr_out = fifo_pop(&af->tx_fifo);
376                                 }
377                                 else
378                                 {
379                                         af->preamble_len--;
380                                         af->curr_out = HDLC_FLAG;
381                                 }
382
383                                 /* Handle char escape */
384                                 if (af->curr_out == AX25_ESC)
385                                 {
386                                         if (fifo_isempty(&af->tx_fifo))
387                                         {
388                                                 AFSK_DAC_IRQ_STOP(af->dac_ch);
389                                                 af->sending = false;
390                                                 return;
391                                         }
392                                         else
393                                                 af->curr_out = fifo_pop(&af->tx_fifo);
394                                 }
395                                 else if (af->curr_out == HDLC_FLAG || af->curr_out == HDLC_RESET)
396                                         /* If these chars are not escaped disable bit stuffing */
397                                         af->bit_stuff = false;
398                         }
399                         /* Start with LSB mask */
400                         af->tx_bit = 0x01;
401                 }
402
403                 /* check for bit stuffing */
404                 if (af->bit_stuff && af->stuff_cnt >= BIT_STUFF_LEN)
405                 {
406                         /* If there are more than 5 ones in a row insert a 0 */
407                         af->stuff_cnt = 0;
408                         /* switch tone */
409                         af->phase_inc = SWITCH_TONE(af->phase_inc);
410                 }
411                 else
412                 {
413                         /*
414                          * NRZI: if we want to transmit a 1 the modulated frequency will stay
415                          * unchanged; with a 0, there will be a change in the tone.
416                          */
417                         if (af->curr_out & af->tx_bit)
418                         {
419                                 /*
420                                  * Transmit a 1:
421                                  * - Stay on the previous tone
422                                  * - Increase bit stuff counter
423                                  */
424                                 af->stuff_cnt++;
425                         }
426                         else
427                         {
428                                 /*
429                                  * Transmit a 0:
430                                  * - Reset bit stuff counter
431                                  * - Switch tone
432                                  */
433                                 af->stuff_cnt = 0;
434                                 af->phase_inc = SWITCH_TONE(af->phase_inc);
435                         }
436
437                         /* Go to the next bit */
438                         af->tx_bit <<= 1;
439                 }
440                 af->sample_count = DAC_SAMPLEPERBIT;
441         }
442
443         /* Get new sample and put it out on the DAC */
444         af->phase_acc += af->phase_inc;
445         af->phase_acc %= SIN_LEN;
446
447         AFSK_DAC_SET(af->dac_ch, sin_sample(af->phase_acc));
448         af->sample_count--;
449 }
450
451
452 static size_t afsk_read(KFile *fd, void *_buf, size_t size)
453 {
454         Afsk *af = AFSK_CAST(fd);
455         uint8_t *buf = (uint8_t *)_buf;
456
457         #if CONFIG_AFSK_RXTIMEOUT == 0
458         while (size-- && !fifo_isempty_locked(&af->rx_fifo))
459         #else
460         while (size--)
461         #endif
462         {
463                 #if CONFIG_AFSK_RXTIMEOUT != -1
464                 ticks_t start = timer_clock();
465                 #endif
466
467                 while (fifo_isempty_locked(&af->rx_fifo));
468                 {
469                         cpu_relax();
470                         #if CONFIG_AFSK_RXTIMEOUT != -1
471                         if (timer_clock() - start > ms_to_ticks(CONFIG_AFSK_RXTIMEOUT))
472                                 return buf - (uint8_t *)_buf;
473                         #endif
474                 }
475
476                 *buf++ = fifo_pop_locked(&af->rx_fifo);
477         }
478
479         return buf - (uint8_t *)_buf;
480 }
481
482 static size_t afsk_write(KFile *fd, const void *_buf, size_t size)
483 {
484         Afsk *af = AFSK_CAST(fd);
485         const uint8_t *buf = (const uint8_t *)_buf;
486
487         while (size--)
488         {
489                 while (fifo_isfull_locked(&af->tx_fifo))
490                         cpu_relax();
491
492                 fifo_push_locked(&af->tx_fifo, *buf++);
493                 afsk_txStart(af);
494         }
495
496         return buf - (const uint8_t *)_buf;
497 }
498
499 static int afsk_flush(KFile *fd)
500 {
501         Afsk *af = AFSK_CAST(fd);
502         while (af->sending)
503                 cpu_relax();
504         return 0;
505 }
506
507 static int afsk_error(KFile *fd)
508 {
509         Afsk *af = AFSK_CAST(fd);
510         int err;
511
512         ATOMIC(err = af->status);
513         return err;
514 }
515
516 static void afsk_clearerr(KFile *fd)
517 {
518         Afsk *af = AFSK_CAST(fd);
519         ATOMIC(af->status = 0);
520 }
521
522
523 /**
524  * Initialize an AFSK1200 modem.
525  * \param af Afsk context to operate one (\see Afsk).
526  * \param adc_ch  ADC channel used by the demodulator.
527  * \param dac_ch  DAC channel used by the modulator.
528  */
529 void afsk_init(Afsk *af, int adc_ch, int dac_ch)
530 {
531         #if CONFIG_AFSK_RXTIMEOUT != -1
532         MOD_CHECK(timer);
533         #endif
534         memset(af, 0, sizeof(*af));
535         af->adc_ch = adc_ch;
536         af->dac_ch = dac_ch;
537
538         fifo_init(&af->delay_fifo, (uint8_t *)af->delay_buf, sizeof(af->delay_buf));
539         fifo_init(&af->rx_fifo, af->rx_buf, sizeof(af->rx_buf));
540
541         /* Fill sample FIFO with 0 */
542         for (int i = 0; i < SAMPLEPERBIT / 2; i++)
543                 fifo_push(&af->delay_fifo, 0);
544
545         fifo_init(&af->tx_fifo, af->tx_buf, sizeof(af->tx_buf));
546
547         AFSK_ADC_INIT(adc_ch, af);
548         AFSK_DAC_INIT(dac_ch, af);
549         AFSK_STROBE_INIT();
550         LOG_INFO("MARK_INC %d, SPACE_INC %d\n", MARK_INC, SPACE_INC);
551
552         DB(af->fd._type = KFT_AFSK);
553         af->fd.write = afsk_write;
554         af->fd.read = afsk_read;
555         af->fd.flush = afsk_flush;
556         af->fd.error = afsk_error;
557         af->fd.clearerr = afsk_clearerr;
558         af->phase_inc = MARK_INC;
559 }