altoslib: Don't record 'pad' state in FlightSeries
[fw/altos] / doc / altos.txt
1 = AltOS
2 :doctype: book
3 :toc:
4 :numbered:
5
6 == Overview
7
8         AltOS is a operating system built for a variety of
9         microcontrollers used in Altus Metrum devices. It has a simple
10         porting layer for each CPU while providing a convenient
11         operating enviroment for the developer. AltOS currently
12         supports three different CPUs:
13
14         * STM32L series from ST Microelectronics. This ARM Cortex-M3
15           based microcontroller offers low power consumption and a
16           wide variety of built-in peripherals. Altus Metrum uses this
17           in the TeleMega, MegaDongle and TeleLCO projects.
18
19         * CC1111 from Texas Instruments. This device includes a
20           fabulous 10mW digital RF transceiver along with an
21           8051-compatible processor core and a range of
22           peripherals. This is used in the TeleMetrum, TeleMini,
23           TeleDongle and TeleFire projects which share the need for a
24           small microcontroller and an RF interface.
25
26         * ATmega32U4 from Atmel. This 8-bit AVR microcontroller is one
27           of the many used to create Arduino boards. The 32U4 includes
28           a USB interface, making it easy to connect to other
29           computers. Altus Metrum used this in prototypes of the
30           TeleScience and TelePyro boards; those have been switched to
31           the STM32L which is more capable and cheaper.
32
33         Among the features of AltOS are:
34
35         * Multi-tasking. While microcontrollers often don't
36           provide separate address spaces, it's often easier to write
37           code that operates in separate threads instead of tying
38           everything into one giant event loop.
39
40         * Non-preemptive. This increases latency for thread
41           switching but reduces the number of places where context
42           switching can occur. It also simplifies the operating system
43           design somewhat. Nothing in the target system (rocket flight
44           control) has tight timing requirements, and so this seems like
45           a reasonable compromise.
46
47         * Sleep/wakeup scheduling. Taken directly from ancient
48           Unix designs, these two provide the fundemental scheduling
49           primitive within AltOS.
50
51         * Mutexes. As a locking primitive, mutexes are easier to
52           use than semaphores, at least in my experience.
53
54         * Timers. Tasks can set an alarm which will abort any
55           pending sleep, allowing operations to time-out instead of
56           blocking forever.
57
58         The device drivers and other subsystems in AltOS are
59         conventionally enabled by invoking their _init() function from
60         the 'main' function before that calls
61         ao_start_scheduler(). These functions initialize the pin
62         assignments, add various commands to the command processor and
63         may add tasks to the scheduler to handle the device. A typical
64         main program, thus, looks like:
65
66         ....
67         \void
68         \main(void)
69         \{
70         \       ao_clock_init();
71
72         \       /* Turn on the LED until the system is stable */
73         \       ao_led_init(LEDS_AVAILABLE);
74         \       ao_led_on(AO_LED_RED);
75         \       ao_timer_init();
76         \       ao_cmd_init();
77         \       ao_usb_init();
78         \       ao_monitor_init(AO_LED_GREEN, TRUE);
79         \       ao_rssi_init(AO_LED_RED);
80         \       ao_radio_init();
81         \       ao_packet_slave_init();
82         \       ao_packet_master_init();
83         \#if HAS_DBG
84         \       ao_dbg_init();
85         \#endif
86         \       ao_config_init();
87         \       ao_start_scheduler();
88         \}
89         ....
90
91         As you can see, a long sequence of subsystems are initialized
92         and then the scheduler is started.
93
94 == AltOS Porting Layer
95
96         AltOS provides a CPU-independent interface to various common
97         microcontroller subsystems, including GPIO pins, interrupts,
98         SPI, I2C, USB and asynchronous serial interfaces. By making
99         these CPU-independent, device drivers, generic OS and
100         application code can all be written that work on any supported
101         CPU. Many of the architecture abstraction interfaces are
102         prefixed with ao_arch.
103
104         === Low-level CPU operations
105
106                 These primitive operations provide the abstraction needed to
107                 run the multi-tasking framework while providing reliable
108                 interrupt delivery.
109
110                 ==== ao_arch_block_interrupts/ao_arch_release_interrupts
111
112                         ....
113                         static inline void
114                         ao_arch_block_interrupts(void);
115
116                         static inline void
117                         ao_arch_release_interrupts(void);
118                         ....
119
120                         These disable/enable interrupt delivery, they may not
121                         discard any interrupts. Use these for sections of code that
122                         must be atomic with respect to any code run from an
123                         interrupt handler.
124
125                 ==== ao_arch_save_regs, ao_arch_save_stack, ao_arch_restore_stack
126
127                         ....
128                         static inline void
129                         ao_arch_save_regs(void);
130
131                         static inline void
132                         ao_arch_save_stack(void);
133
134                         static inline void
135                         ao_arch_restore_stack(void);
136                         ....
137
138                         These provide all of the support needed to switch
139                         between tasks.. ao_arch_save_regs must save all CPU
140                         registers to the current stack, including the
141                         interrupt enable state. ao_arch_save_stack records the
142                         current stack location in the current ao_task
143                         structure. ao_arch_restore_stack switches back to the
144                         saved stack, restores all registers and branches to
145                         the saved return address.
146
147                 ==== ao_arch_wait_interupt
148
149                         ....
150                         #define ao_arch_wait_interrupt()
151                         ....
152
153                         This stops the CPU, leaving clocks and interrupts
154                         enabled. When an interrupt is received, this must wake up
155                         and handle the interrupt. ao_arch_wait_interrupt is entered
156                         with interrupts disabled to ensure that there is no gap
157                         between determining that no task wants to run and idling the
158                         CPU. It must sleep the CPU, process interrupts and then
159                         disable interrupts again. If the CPU doesn't have any
160                         reduced power mode, this must at the least allow pending
161                         interrupts to be processed.
162
163         === GPIO operations
164
165         These functions provide an abstract interface to configure and
166         manipulate GPIO pins.
167
168                 ==== GPIO setup
169
170                         These macros may be invoked at system
171                         initialization time to configure pins as
172                         needed for system operation. One tricky aspect
173                         is that some chips provide direct access to
174                         specific GPIO pins while others only provide
175                         access to a whole register full of pins. To
176                         support this, the GPIO macros provide both
177                         port+bit and pin arguments. Simply define the
178                         arguments needed for the target platform and
179                         leave the others undefined.
180
181                         ===== ao_enable_output
182
183                                 ....
184                                 #define ao_enable_output(port, bit, pin, value)
185                                 ....
186
187                                 Set the specified port+bit (also called 'pin')
188                                 for output, initializing to the specified
189                                 value. The macro must avoid driving the pin
190                                 with the opposite value if at all possible.
191
192                         ===== ao_enable_input
193
194                                 ....
195                                 #define ao_enable_input(port, bit, mode)
196                                 ....
197
198                                 Sets the specified port/bit to be an input
199                                 pin. 'mode' is a combination of one or more of
200                                 the following. Note that some platforms may
201                                 not support the desired mode. In that case,
202                                 the value will not be defined so that the
203                                 program will fail to compile.
204
205                                 * AO_EXTI_MODE_PULL_UP. Apply a pull-up to the
206                                   pin; a disconnected pin will read as 1.
207
208                                 * AO_EXTI_MODE_PULL_DOWN. Apply a pull-down to
209                                   the pin; a disconnected pin will read as 0.
210
211                                 * 0. Don't apply either a pull-up or
212                                   pull-down. A disconnected pin will read an
213                                   undetermined value.
214
215                 ==== Reading and writing GPIO pins
216
217                         These macros read and write individual GPIO pins.
218
219                         ===== ao_gpio_set
220
221                                 ....
222                                 #define ao_gpio_set(port, bit, pin, value)
223                                 ....
224
225                                 Sets the specified port/bit or pin to
226                                 the indicated value
227
228                         ===== ao_gpio_get
229
230                                 ....
231                                 #define ao_gpio_get(port, bit, pin)
232                                 ....
233
234                                 Returns either 1 or 0 depending on
235                                 whether the input to the pin is high
236                                 or low.
237 == Programming the 8051 with SDCC
238
239         The 8051 is a primitive 8-bit processor, designed in the mists
240         of time in as few transistors as possible. The architecture is
241         highly irregular and includes several separate memory
242         spaces. Furthermore, accessing stack variables is slow, and
243         the stack itself is of limited size. While SDCC papers over
244         the instruction set, it is not completely able to hide the
245         memory architecture from the application designer.
246
247         When built on other architectures, the various SDCC-specific
248         symbols are #defined as empty strings so they don't affect the
249         compiler.
250
251         === 8051 memory spaces
252
253                 The __data/__xdata/__code memory spaces below were completely
254                 separate in the original 8051 design. In the cc1111, this
255                 isn't true—they all live in a single unified 64kB address
256                 space, and so it's possible to convert any address into a
257                 unique 16-bit address. SDCC doesn't know this, and so a
258                 'global' address to SDCC consumes 3 bytes of memory, 1 byte as
259                 a tag indicating the memory space and 2 bytes of offset within
260                 that space. AltOS avoids these 3-byte addresses as much as
261                 possible; using them involves a function call per byte
262                 access. The result is that nearly every variable declaration
263                 is decorated with a memory space identifier which clutters the
264                 code but makes the resulting code far smaller and more
265                 efficient.
266
267                 ==== __data
268
269                         The 8051 can directly address these 128 bytes of
270                         memory. This makes them precious so they should be
271                         reserved for frequently addressed values. Oh, just to
272                         confuse things further, the 8 general registers in the
273                         CPU are actually stored in this memory space. There are
274                         magic instructions to 'bank switch' among 4 banks of
275                         these registers located at 0x00 - 0x1F. AltOS uses only
276                         the first bank at 0x00 - 0x07, leaving the other 24
277                         bytes available for other data.
278
279                 ==== __idata
280
281                         There are an additional 128 bytes of internal memory
282                         that share the same address space as __data but which
283                         cannot be directly addressed. The stack normally
284                         occupies this space and so AltOS doesn't place any
285                         static storage here.
286
287                 ==== __xdata
288
289                         This is additional general memory accessed through a
290                         single 16-bit address register. The CC1111F32 has 32kB
291                         of memory available here. Most program data should live
292                         in this memory space.
293
294                 ==== __pdata
295
296                         This is an alias for the first 256 bytes of __xdata
297                         memory, but uses a shorter addressing mode with
298                         single global 8-bit value for the high 8 bits of the
299                         address and any of several 8-bit registers for the low 8
300                         bits. AltOS uses a few bits of this memory, it should
301                         probably use more.
302
303                 ==== __code
304
305                         All executable code must live in this address space, but
306                         you can stick read-only data here too. It is addressed
307                         using the 16-bit address register and special 'code'
308                         access opcodes. Anything read-only should live in this space.
309
310                 ==== __bit
311
312                         The 8051 has 128 bits of bit-addressible memory that
313                         lives in the __data segment from 0x20 through
314                         0x2f. Special instructions access these bits
315                         in a single atomic operation. This isn't so much a
316                         separate address space as a special addressing mode for
317                         a few bytes in the __data segment.
318
319                 ==== __sfr, __sfr16, __sfr32, __sbit
320
321                         Access to physical registers in the device use this mode
322                         which declares the variable name, its type and the
323                         address it lives at. No memory is allocated for these
324                         variables.
325
326         === Function calls on the 8051
327
328                 Because stack addressing is expensive, and stack space
329                 limited, the default function call declaration in SDCC
330                 allocates all parameters and local variables in static global
331                 memory. Just like fortran. This makes these functions
332                 non-reentrant, and also consume space for parameters and
333                 locals even when they are not running. The benefit is smaller
334                 code and faster execution.
335
336                 ==== __reentrant functions
337
338                         All functions which are re-entrant, either due to recursion
339                         or due to a potential context switch while executing, should
340                         be marked as __reentrant so that their parameters and local
341                         variables get allocated on the stack. This ensures that
342                         these values are not overwritten by another invocation of
343                         the function.
344
345                         Functions which use significant amounts of space for
346                         arguments and/or local variables and which are not often
347                         invoked can also be marked as __reentrant. The resulting
348                         code will be larger, but the savings in memory are
349                         frequently worthwhile.
350
351                 ==== Non __reentrant functions
352
353                         All parameters and locals in non-reentrant functions can
354                         have data space decoration so that they are allocated in
355                         __xdata, __pdata or __data space as desired. This can avoid
356                         consuming __data space for infrequently used variables in
357                         frequently used functions.
358
359                         All library functions called by SDCC, including functions
360                         for multiplying and dividing large data types, are
361                         non-reentrant. Because of this, interrupt handlers must not
362                         invoke any library functions, including the multiply and
363                         divide code.
364
365                 ==== __interrupt functions
366
367                         Interrupt functions are declared with with an __interrupt
368                         decoration that includes the interrupt number. SDCC saves
369                         and restores all of the registers in these functions and
370                         uses the 'reti' instruction at the end so that they operate
371                         as stand-alone interrupt handlers. Interrupt functions may
372                         call the ao_wakeup function to wake AltOS tasks.
373
374                 ==== __critical functions and statements
375
376                         SDCC has built-in support for suspending interrupts during
377                         critical code. Functions marked as __critical will have
378                         interrupts suspended for the whole period of
379                         execution. Individual statements may also be marked as
380                         __critical which blocks interrupts during the execution of
381                         that statement. Keeping critical sections as short as
382                         possible is key to ensuring that interrupts are handled as
383                         quickly as possible. AltOS doesn't use this form in shared
384                         code as other compilers wouldn't know what to do. Use
385                         ao_arch_block_interrupts and ao_arch_release_interrupts instead.
386
387 == Task functions
388
389         This chapter documents how to create, destroy and schedule
390         AltOS tasks.
391
392         === ao_add_task
393
394                 ....
395                 \void
396                 \ao_add_task(__xdata struct ao_task * task,
397                 \           void (*start)(void),
398                 \           __code char *name);
399                 ....
400
401                 This initializes the statically allocated task structure,
402                 assigns a name to it (not used for anything but the task
403                 display), and the start address. It does not switch to the
404                 new task. 'start' must not ever return; there is no place
405                 to return to.
406
407         === ao_exit
408
409                 ....
410                 void
411                 ao_exit(void)
412                 ....
413
414                 This terminates the current task.
415
416         === ao_sleep
417
418                 ....
419                 void
420                 ao_sleep(__xdata void *wchan)
421                 ....
422
423                 This suspends the current task until 'wchan' is signaled
424                 by ao_wakeup, or until the timeout, set by ao_alarm,
425                 fires. If 'wchan' is signaled, ao_sleep returns 0, otherwise
426                 it returns 1. This is the only way to switch to another task.
427
428                 Because ao_wakeup wakes every task waiting on a particular
429                 location, ao_sleep should be used in a loop that first checks
430                 the desired condition, blocks in ao_sleep and then rechecks
431                 until the condition is satisfied. If the location may be
432                 signaled from an interrupt handler, the code will need to
433                 block interrupts around the block of code. Here's a complete
434                 example:
435
436                 ....
437                 \ao_arch_block_interrupts();
438                 \while (!ao_radio_done)
439                 \       ao_sleep(&ao_radio_done);
440                 \ao_arch_release_interrupts();
441                 ....
442
443         === ao_wakeup
444
445                 ....
446                 void
447                 ao_wakeup(__xdata void *wchan)
448                 ....
449
450                 Wake all tasks blocked on 'wchan'. This makes them
451                 available to be run again, but does not actually switch
452                 to another task. Here's an example of using this:
453
454                 ....
455                 \if (RFIF & RFIF_IM_DONE) {
456                 \       ao_radio_done = 1;
457                 \       ao_wakeup(&ao_radio_done);
458                 \       RFIF &= ~RFIF_IM_DONE;
459                 \}
460                 ....
461
462                 Note that this need not block interrupts as the
463                 ao_sleep block can only be run from normal mode, and
464                 so this sequence can never be interrupted with
465                 execution of the other sequence.
466
467         === ao_alarm
468
469                 ....
470                 void
471                 ao_alarm(uint16_t delay);
472
473                 void
474                 ao_clear_alarm(void);
475                 ....
476
477                 Schedules an alarm to fire in at least 'delay'
478                 ticks. If the task is asleep when the alarm fires, it
479                 will wakeup and ao_sleep will return 1. ao_clear_alarm
480                 resets any pending alarm so that it doesn't fire at
481                 some arbitrary point in the future.
482
483                 ....
484                 ao_alarm(ao_packet_master_delay);
485                 ao_arch_block_interrupts();
486                 while (!ao_radio_dma_done)
487                         if (ao_sleep(&ao_radio_dma_done) != 0)
488                                 ao_radio_abort();
489                 ao_arch_release_interrupts();
490                 ao_clear_alarm();
491                 ....
492
493                 In this example, a timeout is set before waiting for
494                 incoming radio data. If no data is received before the
495                 timeout fires, ao_sleep will return 1 and then this
496                 code will abort the radio receive operation.
497
498         === ao_start_scheduler
499
500                 ....
501                 void
502                 ao_start_scheduler(void);
503                 ....
504
505                 This is called from 'main' when the system is all
506                 initialized and ready to run. It will not return.
507
508         === ao_clock_init
509
510                 ....
511                 void
512                 ao_clock_init(void);
513                 ....
514
515                 This initializes the main CPU clock and switches to it.
516
517 == Timer Functions
518
519         AltOS sets up one of the CPU timers to run at 100Hz and
520         exposes this tick as the fundemental unit of time. At each
521         interrupt, AltOS increments the counter, and schedules any tasks
522         waiting for that time to pass, then fires off the sensors to
523         collect current data readings. Doing this from the ISR ensures
524         that the values are sampled at a regular rate, independent
525         of any scheduling jitter.
526
527         === ao_time
528
529                 ....
530                 uint16_t
531                 ao_time(void)
532                 ....
533
534                 Returns the current system tick count. Note that this is
535                 only a 16 bit value, and so it wraps every 655.36 seconds.
536
537         === ao_delay
538
539                 ....
540                 void
541                 ao_delay(uint16_t ticks);
542                 ....
543
544                 Suspend the current task for at least 'ticks' clock units.
545
546         === ao_timer_set_adc_interval
547
548                 ....
549                 void
550                 ao_timer_set_adc_interval(uint8_t interval);
551                 ....
552
553                 This sets the number of ticks between ADC samples. If set
554                 to 0, no ADC samples are generated. AltOS uses this to
555                 slow down the ADC sampling rate to save power.
556
557         === ao_timer_init
558
559                 ....
560                 void
561                 ao_timer_init(void)
562                 ....
563
564                 This turns on the 100Hz tick. It is required for any of the
565                 time-based functions to work. It should be called by 'main'
566                 before ao_start_scheduler.
567
568 == AltOS Mutexes
569
570         AltOS provides mutexes as a basic synchronization primitive. Each
571         mutexes is simply a byte of memory which holds 0 when the mutex
572         is free or the task id of the owning task when the mutex is
573         owned. Mutex calls are checked—attempting to acquire a mutex
574         already held by the current task or releasing a mutex not held
575         by the current task will both cause a panic.
576
577         === ao_mutex_get
578
579                 ....
580                 void
581                 ao_mutex_get(__xdata uint8_t *mutex);
582                 ....
583
584                 Acquires the specified mutex, blocking if the mutex is
585                 owned by another task.
586
587         === ao_mutex_put
588
589                 ....
590                 void
591                 ao_mutex_put(__xdata uint8_t *mutex);
592                 ....
593
594                 Releases the specified mutex, waking up all tasks waiting
595                 for it.
596
597 == DMA engine
598
599         The CC1111 and STM32L both contain a useful bit of extra
600         hardware in the form of a number of programmable DMA
601         engines. They can be configured to copy data in memory, or
602         between memory and devices (or even between two devices). AltOS
603         exposes a general interface to this hardware and uses it to
604         handle both internal and external devices.
605
606         Because the CC1111 and STM32L DMA engines are different, the
607         interface to them is also different. As the DMA engines are
608         currently used to implement platform-specific drivers, this
609         isn't yet a problem.
610
611         Code using a DMA engine should allocate one at startup
612         time. There is no provision to free them, and if you run out,
613         AltOS will simply panic.
614
615         During operation, the DMA engine is initialized with the
616         transfer parameters. Then it is started, at which point it
617         awaits a suitable event to start copying data. When copying data
618         from hardware to memory, that trigger event is supplied by the
619         hardware device. When copying data from memory to hardware, the
620         transfer is usually initiated by software.
621
622         === CC1111 DMA Engine
623
624                 ==== ao_dma_alloc
625
626                         ....
627                         uint8_t
628                         ao_dma_alloc(__xdata uint8_t *done)
629                         ....
630
631                         Allocate a DMA engine, returning the
632                         identifier.  'done' is cleared when the DMA is
633                         started, and then receives the AO_DMA_DONE bit
634                         on a successful transfer or the AO_DMA_ABORTED
635                         bit if ao_dma_abort was called. Note that it
636                         is possible to get both bits if the transfer
637                         was aborted after it had finished.
638
639                 ==== ao_dma_set_transfer
640
641                         ....
642                         void
643                         ao_dma_set_transfer(uint8_t id,
644                         void __xdata *srcaddr,
645                         void __xdata *dstaddr,
646                         uint16_t count,
647                         uint8_t cfg0,
648                         uint8_t cfg1)
649                         ....
650
651                         Initializes the specified dma engine to copy
652                         data from 'srcaddr' to 'dstaddr' for 'count'
653                         units. cfg0 and cfg1 are values directly out
654                         of the CC1111 documentation and tell the DMA
655                         engine what the transfer unit size, direction
656                         and step are.
657
658                 ==== ao_dma_start
659
660                         ....
661                         void
662                         ao_dma_start(uint8_t id);
663                         ....
664
665                         Arm the specified DMA engine and await a
666                         signal from either hardware or software to
667                         start transferring data.
668
669                 ==== ao_dma_trigger
670
671                         ....
672                         void
673                         ao_dma_trigger(uint8_t id)
674                         ....
675
676                         Trigger the specified DMA engine to start
677                         copying data.
678
679                 ==== ao_dma_abort
680
681                         ....
682                         void
683                         ao_dma_abort(uint8_t id)
684                         ....
685
686                         Terminate any in-progress DMA transaction,
687                         marking its 'done' variable with the
688                         AO_DMA_ABORTED bit.
689
690         === STM32L DMA Engine
691
692                 ==== ao_dma_alloc
693
694                         ....
695                         uint8_t ao_dma_done[];
696
697                         void
698                         ao_dma_alloc(uint8_t index);
699                         ....
700
701                         Reserve a DMA engine for exclusive use by one
702                         driver.
703
704                 ==== ao_dma_set_transfer
705
706                         ....
707                         void
708                         ao_dma_set_transfer(uint8_t id,
709                         void *peripheral,
710                         void *memory,
711                         uint16_t count,
712                         uint32_t ccr);
713                         ....
714
715                         Initializes the specified dma engine to copy
716                         data between 'peripheral' and 'memory' for
717                         'count' units. 'ccr' is a value directly out
718                         of the STM32L documentation and tells the DMA
719                         engine what the transfer unit size, direction
720                         and step are.
721
722                 ==== ao_dma_set_isr
723
724                         ....
725                         void
726                         ao_dma_set_isr(uint8_t index, void (*isr)(int))
727                         ....
728
729                         This sets a function to be called when the DMA
730                         transfer completes in lieu of setting the
731                         ao_dma_done bits. Use this when some work
732                         needs to be done when the DMA finishes that
733                         cannot wait until user space resumes.
734
735                 ==== ao_dma_start
736
737                         ....
738                         void
739                         ao_dma_start(uint8_t id);
740                         ....
741
742                         Arm the specified DMA engine and await a
743                         signal from either hardware or software to
744                         start transferring data.  'ao_dma_done[index]'
745                         is cleared when the DMA is started, and then
746                         receives the AO_DMA_DONE bit on a successful
747                         transfer or the AO_DMA_ABORTED bit if
748                         ao_dma_abort was called. Note that it is
749                         possible to get both bits if the transfer was
750                         aborted after it had finished.
751
752                 ==== ao_dma_done_transfer
753
754                         ....
755                         void
756                         ao_dma_done_transfer(uint8_t id);
757                         ....
758
759                         Signals that a specific DMA engine is done
760                         being used. This allows multiple drivers to
761                         use the same DMA engine safely.
762
763                 ==== ao_dma_abort
764
765                         ....
766                         void
767                         ao_dma_abort(uint8_t id)
768                         ....
769
770                         Terminate any in-progress DMA transaction,
771                         marking its 'done' variable with the
772                         AO_DMA_ABORTED bit.
773
774 == Stdio interface
775
776         AltOS offers a stdio interface over USB, serial and the RF
777         packet link. This provides for control of the device locally or
778         remotely. This is hooked up to the stdio functions by providing
779         the standard putchar/getchar/flush functions. These
780         automatically multiplex the available communication channels;
781         output is always delivered to the channel which provided the
782         most recent input.
783
784         === putchar
785
786                 ....
787                 void
788                 putchar(char c)
789                 ....
790
791                 Delivers a single character to the current console
792                 device.
793
794         === getchar
795
796                 ....
797                 char
798                 getchar(void)
799                 ....
800
801                 Reads a single character from any of the available
802                 console devices. The current console device is set to
803                 that which delivered this character. This blocks until
804                 a character is available.
805
806         === flush
807
808                 ....
809                 void
810                 flush(void)
811                 ....
812
813                 Flushes the current console device output buffer. Any
814                 pending characters will be delivered to the target device.
815
816         === ao_add_stdio
817
818                 ....
819                 void
820                 ao_add_stdio(char (*pollchar)(void),
821                                    void (*putchar)(char),
822                                    void (*flush)(void))
823                 ....
824
825                 This adds another console device to the available
826                 list.
827
828                 'pollchar' returns either an available character or
829                 AO_READ_AGAIN if none is available. Significantly, it does
830                 not block. The device driver must set 'ao_stdin_ready' to
831                 1 and call ao_wakeup(&ao_stdin_ready) when it receives
832                 input to tell getchar that more data is available, at
833                 which point 'pollchar' will be called again.
834
835                 'putchar' queues a character for output, flushing if the output buffer is
836                 full. It may block in this case.
837
838                 'flush' forces the output buffer to be flushed. It may
839                 block until the buffer is delivered, but it is not
840                 required to do so.
841
842 == Command line interface
843
844         AltOS includes a simple command line parser which is hooked up
845         to the stdio interfaces permitting remote control of the
846         device over USB, serial or the RF link as desired. Each
847         command uses a single character to invoke it, the remaining
848         characters on the line are available as parameters to the
849         command.
850
851         === ao_cmd_register
852
853                 ....
854                 void
855                 ao_cmd_register(__code struct ao_cmds *cmds)
856                 ....
857
858                 This registers a set of commands with the command
859                 parser. There is a fixed limit on the number of command
860                 sets, the system will panic if too many are registered.
861                 Each command is defined by a struct ao_cmds entry:
862
863                 ....
864                 \struct ao_cmds {
865                 \       char            cmd;
866                 \       void            (*func)(void);
867                 \       const char      *help;
868                 \};
869                 ....
870                 'cmd' is the character naming the command. 'func' is the
871                 function to invoke and 'help' is a string displayed by the
872                 '?' command. Syntax errors found while executing 'func'
873                 should be indicated by modifying the global ao_cmd_status
874                 variable with one of the following values:
875
876                 ao_cmd_success::
877
878                 The command was parsed successfully. There is no need
879                 to assign this value, it is the default.
880
881                 ao_cmd_lex_error::
882
883                 A token in the line was invalid, such as a number
884                 containing invalid characters. The low-level lexing
885                 functions already assign this value as needed.
886
887                 ao_syntax_error::
888
889                 The command line is invalid for some reason other than
890                 invalid tokens.
891
892         === ao_cmd_lex
893
894                 ....
895                 void
896                 ao_cmd_lex(void);
897                 ....
898
899                 This gets the next character out of the command line
900                 buffer and sticks it into ao_cmd_lex_c. At the end of
901                 the line, ao_cmd_lex_c will get a newline ('\n')
902                 character.
903
904         === ao_cmd_put16
905
906                 ....
907                 void
908                 ao_cmd_put16(uint16_t v);
909                 ....
910
911                 Writes 'v' as four hexadecimal characters.
912
913         === ao_cmd_put8
914
915                 ....
916                 void
917                 ao_cmd_put8(uint8_t v);
918                 ....
919
920                 Writes 'v' as two hexadecimal characters.
921
922         === ao_cmd_white
923
924                 ....
925                 void
926                 ao_cmd_white(void)
927                 ....
928
929                 This skips whitespace by calling ao_cmd_lex while
930                 ao_cmd_lex_c is either a space or tab. It does not
931                 skip any characters if ao_cmd_lex_c already non-white.
932
933         === ao_cmd_hex
934
935                 ....
936                 void
937                 ao_cmd_hex(void)
938                 ....
939
940                 This reads a 16-bit hexadecimal value from the command
941                 line with optional leading whitespace. The resulting
942                 value is stored in ao_cmd_lex_i;
943
944         === ao_cmd_decimal
945
946                 ....
947                 void
948                 ao_cmd_decimal(void)
949                 ....
950
951                 This reads a 32-bit decimal value from the command
952                 line with optional leading whitespace. The resulting
953                 value is stored in ao_cmd_lex_u32 and the low 16 bits
954                 are stored in ao_cmd_lex_i;
955
956         === ao_match_word
957
958                 ....
959                 uint8_t
960                 ao_match_word(__code char *word)
961                 ....
962
963                 This checks to make sure that 'word' occurs on the
964                 command line. It does not skip leading white space. If
965                 'word' is found, then 1 is returned. Otherwise,
966                 ao_cmd_status is set to ao_cmd_syntax_error and 0 is
967                 returned.
968
969         === ao_cmd_init
970
971                 ....
972                 void
973                 ao_cmd_init(void
974                 ....
975
976                 Initializes the command system, setting up the
977                 built-in commands and adding a task to run the command
978                 processing loop. It should be called by 'main' before
979                 ao_start_scheduler.
980
981 == USB target device
982
983         AltOS contains a full-speed USB target device driver. It can
984         be programmed to offer any kind of USB target, but to simplify
985         interactions with a variety of operating systems, AltOS
986         provides only a single target device profile, that of a USB
987         modem which has native drivers for Linux, Windows and Mac OS
988         X. It would be easy to change the code to provide an alternate
989         target device if necessary.
990
991         To the rest of the system, the USB device looks like a simple
992         two-way byte stream. It can be hooked into the command line
993         interface if desired, offering control of the device over the
994         USB link. Alternatively, the functions can be accessed
995         directly to provide for USB-specific I/O.
996
997         === ao_usb_flush
998
999                 ....
1000                 void
1001                 ao_usb_flush(void);
1002                 ....
1003
1004                 Flushes any pending USB output. This queues an 'IN'
1005                 packet to be delivered to the USB host if there is
1006                 pending data, or if the last IN packet was full to
1007                 indicate to the host that there isn't any more pending
1008                 data available.
1009
1010         === ao_usb_putchar
1011
1012                 ....
1013                 void
1014                 ao_usb_putchar(char c);
1015                 ....
1016
1017                 If there is a pending 'IN' packet awaiting delivery to
1018                 the host, this blocks until that has been
1019                 fetched. Then, this adds a byte to the pending IN
1020                 packet for delivery to the USB host. If the USB packet
1021                 is full, this queues the 'IN' packet for delivery.
1022
1023         === ao_usb_pollchar
1024
1025                 ....
1026                 char
1027                 ao_usb_pollchar(void);
1028                 ....
1029
1030                 If there are no characters remaining in the last 'OUT'
1031                 packet received, this returns
1032                 AO_READ_AGAIN. Otherwise, it returns the next
1033                 character, reporting to the host that it is ready for
1034                 more data when the last character is gone.
1035
1036         === ao_usb_getchar
1037
1038                 ....
1039                 char
1040                 ao_usb_getchar(void);
1041                 ....
1042
1043                 This uses ao_pollchar to receive the next character,
1044                 blocking while ao_pollchar returns AO_READ_AGAIN.
1045
1046         === ao_usb_disable
1047
1048                 ....
1049                 void
1050                 ao_usb_disable(void);
1051                 ....
1052
1053                 This turns off the USB controller. It will no longer
1054                 respond to host requests, nor return
1055                 characters. Calling any of the i/o routines while the
1056                 USB device is disabled is undefined, and likely to
1057                 break things. Disabling the USB device when not needed
1058                 saves power.
1059
1060                 Note that neither TeleDongle v0.2 nor TeleMetrum v1
1061                 are able to signal to the USB host that they have
1062                 disconnected, so after disabling the USB device, it's
1063                 likely that the cable will need to be disconnected and
1064                 reconnected before it will work again.
1065
1066         === ao_usb_enable
1067
1068                 ....
1069                 void
1070                 ao_usb_enable(void);
1071                 ....
1072
1073                 This turns the USB controller on again after it has
1074                 been disabled. See the note above about needing to
1075                 physically remove and re-insert the cable to get the
1076                 host to re-initialize the USB link.
1077
1078         === ao_usb_init
1079
1080                 ....
1081                 void
1082                 ao_usb_init(void);
1083                 ....
1084
1085                 This turns the USB controller on, adds a task to
1086                 handle the control end point and adds the usb I/O
1087                 functions to the stdio system. Call this from main
1088                 before ao_start_scheduler.
1089
1090 == Serial peripherals
1091
1092         The CC1111 provides two USART peripherals. AltOS uses one for
1093         asynch serial data, generally to communicate with a GPS
1094         device, and the other for a SPI bus. The UART is configured to
1095         operate in 8-bits, no parity, 1 stop bit framing. The default
1096         configuration has clock settings for 4800, 9600 and 57600 baud
1097         operation. Additional speeds can be added by computing
1098         appropriate clock values.
1099
1100         To prevent loss of data, AltOS provides receive and transmit
1101         fifos of 32 characters each.
1102
1103         === ao_serial_getchar
1104
1105                 ....
1106                 char
1107                 ao_serial_getchar(void);
1108                 ....
1109
1110                 Returns the next character from the receive fifo, blocking
1111                 until a character is received if the fifo is empty.
1112
1113         === ao_serial_putchar
1114
1115                 ....
1116                 void
1117                 ao_serial_putchar(char c);
1118                 ....
1119
1120                 Adds a character to the transmit fifo, blocking if the
1121                 fifo is full. Starts transmitting characters.
1122
1123         === ao_serial_drain
1124
1125                 ....
1126                 void
1127                 ao_serial_drain(void);
1128                 ....
1129
1130                 Blocks until the transmit fifo is empty. Used internally
1131                 when changing serial speeds.
1132
1133         === ao_serial_set_speed
1134
1135                 ....
1136                 void
1137                 ao_serial_set_speed(uint8_t speed);
1138                 ....
1139
1140                 Changes the serial baud rate to one of
1141                 AO_SERIAL_SPEED_4800, AO_SERIAL_SPEED_9600 or
1142                 AO_SERIAL_SPEED_57600. This first flushes the transmit
1143                 fifo using ao_serial_drain.
1144
1145         === ao_serial_init
1146
1147                 ....
1148                 void
1149                 ao_serial_init(void)
1150                 ....
1151
1152                 Initializes the serial peripheral. Call this from 'main'
1153                 before jumping to ao_start_scheduler. The default speed
1154                 setting is AO_SERIAL_SPEED_4800.
1155
1156 == CC1111/CC1120/CC1200 Radio peripheral
1157
1158         === Radio Introduction
1159
1160                 The CC1111, CC1120 and CC1200 radio transceiver sends
1161                 and receives digital packets with forward error
1162                 correction and detection. The AltOS driver is fairly
1163                 specific to the needs of the TeleMetrum and TeleDongle
1164                 devices, using it for other tasks may require
1165                 customization of the driver itself. There are three
1166                 basic modes of operation:
1167
1168                 . Telemetry mode. In this mode, TeleMetrum transmits telemetry
1169                   frames at a fixed rate. The frames are of fixed size. This
1170                   is strictly a one-way communication from TeleMetrum to
1171                   TeleDongle.
1172
1173                 . Packet mode. In this mode, the radio is used to create a
1174                   reliable duplex byte stream between TeleDongle and
1175                   TeleMetrum. This is an asymmetrical protocol with
1176                   TeleMetrum only transmitting in response to a packet sent
1177                   from TeleDongle. Thus getting data from TeleMetrum to
1178                   TeleDongle requires polling. The polling rate is adaptive,
1179                   when no data has been received for a while, the rate slows
1180                   down. The packets are checked at both ends and invalid data
1181                   are ignored.
1182
1183                   On the TeleMetrum side, the packet link is hooked into the
1184                   stdio mechanism, providing an alternate data path for the
1185                   command processor. It is enabled when the unit boots up in
1186                   'idle' mode.
1187
1188                   On the TeleDongle side, the packet link is enabled with a
1189                   command; data from the stdio package is forwarded over the
1190                   packet link providing a connection from the USB command
1191                   stream to the remote TeleMetrum device.
1192
1193                 . Radio Direction Finding mode. In this mode, TeleMetrum
1194                   constructs a special packet that sounds like an audio tone
1195                   when received by a conventional narrow-band FM
1196                   receiver. This is designed to provide a beacon to track the
1197                   device when other location mechanisms fail.
1198
1199         === ao_radio_set_telemetry
1200
1201                 ....
1202                 void
1203                 ao_radio_set_telemetry(void);
1204                 ....
1205
1206                 Configures the radio to send or receive telemetry
1207                 packets. This includes packet length, modulation scheme and
1208                 other RF parameters. It does not include the base frequency
1209                 or channel though. Those are set at the time of transmission
1210                 or reception, in case the values are changed by the user.
1211
1212         === ao_radio_set_packet
1213
1214                 ....
1215                 void
1216                 ao_radio_set_packet(void);
1217                 ....
1218
1219                 Configures the radio to send or receive packet data.  This
1220                 includes packet length, modulation scheme and other RF
1221                 parameters. It does not include the base frequency or
1222                 channel though. Those are set at the time of transmission or
1223                 reception, in case the values are changed by the user.
1224
1225         === ao_radio_set_rdf
1226
1227                 ....
1228                 void
1229                 ao_radio_set_rdf(void);
1230                 ....
1231
1232                 Configures the radio to send RDF 'packets'. An RDF 'packet'
1233                 is a sequence of hex 0x55 bytes sent at a base bit rate of
1234                 2kbps using a 5kHz deviation. All of the error correction
1235                 and data whitening logic is turned off so that the resulting
1236                 modulation is received as a 1kHz tone by a conventional 70cm
1237                 FM audio receiver.
1238
1239         === ao_radio_idle
1240
1241                 ....
1242                 void
1243                 ao_radio_idle(void);
1244                 ....
1245
1246                 Sets the radio device to idle mode, waiting until it reaches
1247                 that state. This will terminate any in-progress transmit or
1248                 receive operation.
1249
1250         === ao_radio_get
1251
1252                 ....
1253                 void
1254                 ao_radio_get(void);
1255                 ....
1256
1257                 Acquires the radio mutex and then configures the radio
1258                 frequency using the global radio calibration and channel
1259                 values.
1260
1261         === ao_radio_put
1262
1263                 ....
1264                 void
1265                 ao_radio_put(void);
1266                 ....
1267
1268                 Releases the radio mutex.
1269
1270         === ao_radio_abort
1271
1272                 ....
1273                 void
1274                 ao_radio_abort(void);
1275                 ....
1276
1277                 Aborts any transmission or reception process by aborting the
1278                 associated DMA object and calling ao_radio_idle to terminate
1279                 the radio operation.
1280
1281         === Radio Telemetry
1282
1283                 In telemetry mode, you can send or receive a telemetry
1284                 packet. The data from receiving a packet also includes the RSSI
1285                 and status values supplied by the receiver. These are added
1286                 after the telemetry data.
1287
1288                 ==== ao_radio_send
1289
1290                 ....
1291                 void
1292                 ao_radio_send(__xdata struct ao_telemetry *telemetry);
1293                 ....
1294
1295                 This sends the specific telemetry packet, waiting for the
1296                 transmission to complete. The radio must have been set to
1297                 telemetry mode. This function calls ao_radio_get() before
1298                 sending, and ao_radio_put() afterwards, to correctly
1299                 serialize access to the radio device.
1300
1301                 ==== ao_radio_recv
1302
1303                 ....
1304                 void
1305                 ao_radio_recv(__xdata struct ao_radio_recv *radio);
1306                 ....
1307
1308                 This blocks waiting for a telemetry packet to be received.
1309                 The radio must have been set to telemetry mode. This
1310                 function calls ao_radio_get() before receiving, and
1311                 ao_radio_put() afterwards, to correctly serialize access
1312                 to the radio device. This returns non-zero if a packet was
1313                 received, or zero if the operation was aborted (from some
1314                 other task calling ao_radio_abort()).
1315
1316         === Radio Direction Finding
1317
1318                 In radio direction finding mode, there's just one function to
1319                 use
1320
1321                 ==== ao_radio_rdf
1322
1323                 ....
1324                 void
1325                 ao_radio_rdf(int ms);
1326                 ....
1327
1328                 This sends an RDF packet lasting for the specified amount
1329                 of time. The maximum length is 1020 ms.
1330
1331         === Radio Packet Mode
1332
1333                 Packet mode is asymmetrical and is configured at compile time
1334                 for either master or slave mode (but not both). The basic I/O
1335                 functions look the same at both ends, but the internals are
1336                 different, along with the initialization steps.
1337
1338                 ==== ao_packet_putchar
1339
1340                         ....
1341                         void
1342                         ao_packet_putchar(char c);
1343                         ....
1344
1345                         If the output queue is full, this first blocks waiting for
1346                         that data to be delivered. Then, queues a character for
1347                         packet transmission. On the master side, this will
1348                         transmit a packet if the output buffer is full. On the
1349                         slave side, any pending data will be sent the next time
1350                         the master polls for data.
1351
1352                 ==== ao_packet_pollchar
1353
1354                         ....
1355                         char
1356                         ao_packet_pollchar(void);
1357                         ....
1358
1359                         This returns a pending input character if available,
1360                         otherwise returns AO_READ_AGAIN. On the master side, if
1361                         this empties the buffer, it triggers a poll for more data.
1362
1363                 ==== ao_packet_slave_start
1364
1365                         ....
1366                         void
1367                         ao_packet_slave_start(void);
1368                         ....
1369
1370                         This is available only on the slave side and starts a task
1371                         to listen for packet data.
1372
1373                 ==== ao_packet_slave_stop
1374
1375                         ....
1376                         void
1377                         ao_packet_slave_stop(void);
1378                         ....
1379
1380                         Disables the packet slave task, stopping the radio receiver.
1381
1382                 ==== ao_packet_slave_init
1383
1384                         ....
1385                         void
1386                         ao_packet_slave_init(void);
1387                         ....
1388
1389                         Adds the packet stdio functions to the stdio package so
1390                         that when packet slave mode is enabled, characters will
1391                         get send and received through the stdio functions.
1392
1393                 ==== ao_packet_master_init
1394
1395                         ....
1396                         void
1397                         ao_packet_master_init(void);
1398                         ....
1399
1400                         Adds the 'p' packet forward command to start packet mode.