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