f778b2fbb62896dca526eeafbd83755f3def1dad
[fw/altos] / src / kernel / ao_flight.c
1 /*
2  * Copyright © 2009 Keith Packard <keithp@keithp.com>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
17  */
18
19 #ifndef AO_FLIGHT_TEST
20 #include "ao.h"
21 #include <ao_log.h>
22 #endif
23
24 #include <ao_flight.h>
25
26 #if HAS_MPU6000 || HAS_MPU9250
27 #include <ao_quaternion.h>
28 #endif
29
30 #ifndef HAS_ACCEL
31 #error Please define HAS_ACCEL
32 #endif
33
34 #ifndef HAS_GPS
35 #error Please define HAS_GPS
36 #endif
37
38 #ifndef HAS_USB
39 #error Please define HAS_USB
40 #endif
41
42 #if HAS_FAKE_FLIGHT
43 #include <ao_fake_flight.h>
44 #endif
45
46 #ifndef HAS_TELEMETRY
47 #define HAS_TELEMETRY   HAS_RADIO
48 #endif
49
50 /* Main flight thread. */
51
52 enum ao_flight_state    ao_flight_state;        /* current flight state */
53 uint16_t                ao_boost_tick;          /* time of most recent boost detect */
54 uint16_t                ao_launch_tick;         /* time of first boost detect */
55 uint16_t                ao_motor_number;        /* number of motors burned so far */
56
57 #if HAS_SENSOR_ERRORS
58 /* Any sensor can set this to mark the flight computer as 'broken' */
59 uint8_t                 ao_sensor_errors;
60 #endif
61
62 /*
63  * track min/max data over a long interval to detect
64  * resting
65  */
66 static uint16_t         ao_interval_end;
67 #ifdef HAS_BARO
68 static ao_v_t           ao_interval_min_height;
69 static ao_v_t           ao_interval_max_height;
70 #else
71 static accel_t          ao_interval_min_accel_along, ao_interval_max_accel_along;
72 static accel_t          ao_interval_min_accel_across, ao_interval_max_accel_across;
73 static accel_t          ao_interval_min_accel_through, ao_interval_max_accel_through;
74 #endif
75 #if HAS_ACCEL
76 static ao_v_t           ao_coast_avg_accel;
77 #endif
78
79 #define init_bounds(_cur, _min, _max) do {                              \
80                 _min = _max = _cur;                                     \
81         } while (0)
82
83 #define check_bounds(_cur, _min, _max) do {     \
84                 if (_cur < _min)                \
85                         _min = _cur;            \
86                 if (_cur > _max)                \
87                         _max = _cur;            \
88         } while(0)
89
90 uint8_t                 ao_flight_force_idle;
91
92 /* We also have a clock, which can be used to sanity check things in
93  * case of other failures
94  */
95
96 #define BOOST_TICKS_MAX AO_SEC_TO_TICKS(15)
97
98 /* Landing is detected by getting constant readings from both pressure and accelerometer
99  * for a fairly long time (AO_INTERVAL_TICKS)
100  */
101 #define AO_INTERVAL_TICKS       AO_SEC_TO_TICKS(10)
102
103 #define abs(a)  ((a) < 0 ? -(a) : (a))
104
105 void
106 ao_flight(void)
107 {
108         ao_sample_init();
109         ao_flight_state = ao_flight_startup;
110         for (;;) {
111
112                 /*
113                  * Process ADC samples, just looping
114                  * until the sensors are calibrated.
115                  */
116                 if (!ao_sample())
117                         continue;
118
119                 switch (ao_flight_state) {
120                 case ao_flight_startup:
121
122                         /* Check to see what mode we should go to.
123                          *  - Invalid mode if accel cal appears to be out
124                          *  - pad mode if we're upright,
125                          *  - idle mode otherwise
126                          */
127 #if HAS_ACCEL
128                         if (ao_config.accel_plus_g == 0 ||
129                             ao_config.accel_minus_g == 0 ||
130                             ao_ground_accel < ao_config.accel_plus_g - ACCEL_NOSE_UP ||
131                             ao_ground_accel > ao_config.accel_minus_g + ACCEL_NOSE_UP
132 #if HAS_BARO
133                             || ao_ground_height < -1000 ||
134                             ao_ground_height > 7000
135 #endif
136                                 )
137                         {
138                                 /* Detected an accel value outside -1.5g to 1.5g
139                                  * (or uncalibrated values), so we go into invalid mode
140                                  */
141                                 ao_flight_state = ao_flight_invalid;
142
143 #if HAS_RADIO && PACKET_HAS_SLAVE
144                                 /* Turn on packet system in invalid mode on TeleMetrum */
145                                 ao_packet_slave_start();
146 #endif
147                         } else
148 #endif
149                                 if (!ao_flight_force_idle
150 #if HAS_ACCEL
151                                     && ao_ground_accel < ao_config.accel_plus_g + ACCEL_NOSE_UP
152 #endif
153                                         )
154                         {
155                                 /* Set pad mode - we can fly! */
156                                 ao_flight_state = ao_flight_pad;
157 #if HAS_USB && !HAS_FLIGHT_DEBUG && !HAS_SAMPLE_PROFILE && !DEBUG
158                                 /* Disable the USB controller in flight mode
159                                  * to save power
160                                  */
161 #if HAS_FAKE_FLIGHT
162                                 if (!ao_fake_flight_active)
163 #endif
164                                         ao_usb_disable();
165 #endif
166
167 #if !HAS_ACCEL && PACKET_HAS_SLAVE
168                                 /* Disable packet mode in pad state on TeleMini */
169                                 ao_packet_slave_stop();
170 #endif
171
172 #if HAS_TELEMETRY
173                                 /* Turn on telemetry system */
174                                 ao_rdf_set(1);
175                                 ao_telemetry_set_interval(AO_TELEMETRY_INTERVAL_PAD);
176 #endif
177 #if AO_LED_RED
178                                 /* signal successful initialization by turning off the LED */
179                                 ao_led_off(AO_LED_RED);
180 #endif
181                         } else {
182                                 /* Set idle mode */
183                                 ao_flight_state = ao_flight_idle;
184 #if HAS_SENSOR_ERRORS
185                                 if (ao_sensor_errors)
186                                         ao_flight_state = ao_flight_invalid;
187 #endif
188  
189 #if HAS_ACCEL && HAS_RADIO && PACKET_HAS_SLAVE
190                                 /* Turn on packet system in idle mode on TeleMetrum */
191                                 ao_packet_slave_start();
192 #endif
193
194 #if AO_LED_RED
195                                 /* signal successful initialization by turning off the LED */
196                                 ao_led_off(AO_LED_RED);
197 #endif
198                         }
199                         /* wakeup threads due to state change */
200                         ao_wakeup(&ao_flight_state);
201
202                         break;
203
204                 case ao_flight_invalid:
205                         printf("+g %d -g %d ga %d +g-NU %d -g+NU %d\n",
206                                ao_config.accel_plus_g,
207                                ao_config.accel_minus_g,
208                                ao_ground_accel,
209                                ao_config.accel_plus_g - ACCEL_NOSE_UP,
210                                ao_config.accel_minus_g + ACCEL_NOSE_UP);
211                         break;
212 #if 0
213                 case ao_flight_idle:
214                         printf("+g %d ga %d sa %d accel %ld speed %ld\n", ao_config.accel_plus_g, ao_ground_accel, ao_sample_accel, ao_accel, ao_speed);
215                         break;
216 #endif
217
218                 case ao_flight_pad:
219                         /* pad to boost:
220                          *
221                          * barometer: > 20m vertical motion
222                          *             OR
223                          * accelerometer: > 2g AND velocity > 5m/s
224                          *
225                          * The accelerometer should always detect motion before
226                          * the barometer, but we use both to make sure this
227                          * transition is detected. If the device
228                          * doesn't have an accelerometer, then ignore the
229                          * speed and acceleration as they are quite noisy
230                          * on the pad.
231                          */
232                         if (ao_height > AO_M_TO_HEIGHT(20)
233 #if HAS_ACCEL
234                             || (ao_accel > AO_MSS_TO_ACCEL(20)
235 #if HAS_BARO
236                                 && ao_speed > AO_MS_TO_SPEED(5)
237 #endif
238 )
239 #endif
240                                 )
241                         {
242                                 ao_flight_state = ao_flight_boost;
243                                 ao_wakeup(&ao_flight_state);
244
245                                 ao_launch_tick = ao_boost_tick = ao_sample_tick;
246
247                                 /* start logging data */
248 #if HAS_LOG
249                                 ao_log_start();
250 #endif
251
252 #if HAS_TELEMETRY
253                                 /* Increase telemetry rate */
254                                 ao_telemetry_set_interval(AO_TELEMETRY_INTERVAL_FLIGHT);
255
256                                 /* disable RDF beacon */
257                                 ao_rdf_set(0);
258 #endif
259
260 #if HAS_GPS
261                                 /* Record current GPS position by waking up GPS log tasks */
262                                 ao_gps_new = AO_GPS_NEW_DATA | AO_GPS_NEW_TRACKING;
263                                 ao_wakeup(&ao_gps_new);
264 #endif
265                         }
266                         break;
267                 case ao_flight_boost:
268
269                         /* boost to fast:
270                          *
271                          * accelerometer: start to fall at > 1/4 G
272                          *              OR
273                          * time: boost for more than 15 seconds
274                          *
275                          * Detects motor burn out by the switch from acceleration to
276                          * deceleration, or by waiting until the maximum burn duration
277                          * (15 seconds) has past.
278                          */
279                         if ((ao_accel < AO_MSS_TO_ACCEL(-2.5)) ||
280                             (int16_t) (ao_sample_tick - ao_boost_tick) > BOOST_TICKS_MAX)
281                         {
282 #if HAS_ACCEL
283 #if HAS_BARO
284                                 ao_flight_state = ao_flight_fast;
285 #else
286                                 ao_flight_state = ao_flight_coast;
287
288                                 /* Initialize landing detection interval values */
289                                 ao_interval_end = ao_sample_tick + AO_INTERVAL_TICKS;
290
291                                 init_bounds(ao_sample_accel_along, ao_interval_min_accel_along, ao_interval_max_accel_along);
292                                 init_bounds(ao_sample_accel_across, ao_interval_min_accel_across, ao_interval_max_accel_across);
293                                 init_bounds(ao_sample_accel_through, ao_interval_min_accel_through, ao_interval_max_accel_through);
294 #endif
295                                 ao_coast_avg_accel = ao_accel;
296 #else
297                                 ao_flight_state = ao_flight_coast;
298 #endif
299                                 ao_wakeup(&ao_flight_state);
300                                 ++ao_motor_number;
301                         }
302                         break;
303 #if HAS_ACCEL && HAS_BARO
304                 case ao_flight_fast:
305                         /*
306                          * This is essentially the same as coast,
307                          * but the barometer is being ignored as
308                          * it may be unreliable.
309                          */
310                         if (ao_speed < AO_MS_TO_SPEED(AO_MAX_BARO_SPEED))
311                         {
312                                 ao_flight_state = ao_flight_coast;
313                                 ao_wakeup(&ao_flight_state);
314                         } else
315                                 goto check_re_boost;
316                         break;
317 #endif
318                 case ao_flight_coast:
319
320 #if HAS_BARO
321                         /*
322                          * By customer request - allow the user
323                          * to lock out apogee detection for a specified
324                          * number of seconds.
325                          */
326                         if (ao_config.apogee_lockout) {
327                                 if ((int16_t) (ao_sample_tick - ao_launch_tick) <
328                                     AO_SEC_TO_TICKS(ao_config.apogee_lockout))
329                                         break;
330                         }
331
332                         /* apogee detect: coast to drogue deploy:
333                          *
334                          * speed: < 0
335                          *
336                          * Also make sure the model altitude is tracking
337                          * the measured altitude reasonably closely; otherwise
338                          * we're probably transsonic.
339                          */
340 #define AO_ERROR_BOUND  100
341
342                         if (ao_speed < 0
343 #if !HAS_ACCEL
344                             && (ao_sample_alt >= AO_MAX_BARO_HEIGHT || ao_error_h_sq_avg < AO_ERROR_BOUND)
345 #endif
346                                 )
347                         {
348                                 /* enter drogue state */
349                                 ao_flight_state = ao_flight_drogue;
350                                 ao_wakeup(&ao_flight_state);
351 #if HAS_TELEMETRY
352                                 /* slow down the telemetry system */
353                                 ao_telemetry_set_interval(AO_TELEMETRY_INTERVAL_RECOVER);
354
355                                 /* Turn the RDF beacon back on */
356                                 ao_rdf_set(1);
357 #endif
358                         }
359                         else
360 #else /* not HAS_BARO */
361                         /* coast to land:
362                          *
363                          * accel: values stable
364                          */
365                         check_bounds(ao_sample_accel_along, ao_interval_min_accel_along, ao_interval_max_accel_along);
366                         check_bounds(ao_sample_accel_across, ao_interval_min_accel_across, ao_interval_max_accel_across);
367                         check_bounds(ao_sample_accel_through, ao_interval_min_accel_through, ao_interval_max_accel_through);
368
369 #define MAX_QUIET_ACCEL 2
370
371                         if ((int16_t) (ao_sample_tick - ao_interval_end) >= 0) {
372                                 if (ao_interval_max_accel_along - ao_interval_min_accel_along <= ao_data_accel_to_sample(MAX_QUIET_ACCEL) &&
373                                     ao_interval_max_accel_across - ao_interval_min_accel_across <= ao_data_accel_to_sample(MAX_QUIET_ACCEL) &&
374                                     ao_interval_max_accel_through - ao_interval_min_accel_through <= ao_data_accel_to_sample(MAX_QUIET_ACCEL))
375                                 {
376                                         ao_flight_state = ao_flight_landed;
377                                         ao_wakeup(&ao_flight_state);
378 #if HAS_ADC
379                                         /* turn off the ADC capture */
380                                         ao_timer_set_adc_interval(0);
381 #endif
382                                 }
383
384                                 /* Reset interval values */
385                                 ao_interval_end = ao_sample_tick + AO_INTERVAL_TICKS;
386
387                                 init_bounds(ao_sample_accel_along, ao_interval_min_accel_along, ao_interval_max_accel_along);
388                                 init_bounds(ao_sample_accel_across, ao_interval_min_accel_across, ao_interval_max_accel_across);
389                                 init_bounds(ao_sample_accel_through, ao_interval_min_accel_through, ao_interval_max_accel_through);
390                         }
391 #endif
392 #if HAS_ACCEL
393                         {
394 #if HAS_BARO
395                         check_re_boost:
396 #endif
397                                 ao_coast_avg_accel = ao_coast_avg_accel + ((ao_accel - ao_coast_avg_accel) >> 5);
398                                 if (ao_coast_avg_accel > AO_MSS_TO_ACCEL(20)) {
399                                         ao_boost_tick = ao_sample_tick;
400                                         ao_flight_state = ao_flight_boost;
401                                         ao_wakeup(&ao_flight_state);
402                                 }
403                         }
404 #endif
405
406                         break;
407 #if HAS_BARO
408                 case ao_flight_drogue:
409
410                         /* drogue to main deploy:
411                          *
412                          * barometer: reach main deploy altitude
413                          *
414                          * Would like to use the accelerometer for this test, but
415                          * the orientation of the flight computer is unknown after
416                          * drogue deploy, so we ignore it. Could also detect
417                          * high descent rate using the pressure sensor to
418                          * recognize drogue deploy failure and eject the main
419                          * at that point. Perhaps also use the drogue sense lines
420                          * to notice continutity?
421                          */
422                         if (ao_height <= ao_config.main_deploy)
423                         {
424                                 ao_flight_state = ao_flight_main;
425                                 ao_wakeup(&ao_flight_state);
426
427                                 /*
428                                  * Start recording min/max height
429                                  * to figure out when the rocket has landed
430                                  */
431
432                                 /* initialize interval values */
433                                 ao_interval_end = ao_sample_tick + AO_INTERVAL_TICKS;
434
435                                 ao_interval_min_height = ao_interval_max_height = ao_avg_height;
436                         }
437                         break;
438
439                         /* fall through... */
440                 case ao_flight_main:
441
442                         /* main to land:
443                          *
444                          * barometer: altitude stable
445                          */
446                         if (ao_avg_height < ao_interval_min_height)
447                                 ao_interval_min_height = ao_avg_height;
448                         if (ao_avg_height > ao_interval_max_height)
449                                 ao_interval_max_height = ao_avg_height;
450
451                         if ((int16_t) (ao_sample_tick - ao_interval_end) >= 0) {
452                                 if (ao_interval_max_height - ao_interval_min_height <= AO_M_TO_HEIGHT(4))
453                                 {
454                                         ao_flight_state = ao_flight_landed;
455                                         ao_wakeup(&ao_flight_state);
456 #if HAS_ADC
457                                         /* turn off the ADC capture */
458                                         ao_timer_set_adc_interval(0);
459 #endif
460                                 }
461                                 ao_interval_min_height = ao_interval_max_height = ao_avg_height;
462                                 ao_interval_end = ao_sample_tick + AO_INTERVAL_TICKS;
463                         }
464                         break;
465 #endif /* HAS_BARO */
466 #if HAS_FLIGHT_DEBUG
467                 case ao_flight_test:
468 #if HAS_GYRO
469                         printf ("angle %4d pitch %7d yaw %7d roll %7d\n",
470                                 ao_sample_orient,
471                                 ((ao_sample_pitch << 9) - ao_ground_pitch) >> 9,
472                                 ((ao_sample_yaw << 9) - ao_ground_yaw) >> 9,
473                                 ((ao_sample_roll << 9) - ao_ground_roll) >> 9);
474 #endif
475                         flush();
476                         break;
477 #endif /* HAS_FLIGHT_DEBUG */
478                 default:
479                         break;
480                 }
481         }
482 }
483
484 #if HAS_FLIGHT_DEBUG
485 static inline int int_part(ao_v_t i)    { return i >> 4; }
486 static inline int frac_part(ao_v_t i)   { return ((i & 0xf) * 100 + 8) / 16; }
487
488 static void
489 ao_flight_dump(void)
490 {
491 #if HAS_ACCEL
492         ao_v_t  accel;
493
494         accel = ((ao_config.accel_plus_g - ao_sample_accel) * ao_accel_scale) >> 16;
495 #endif
496
497         printf ("sample:\n");
498         printf ("  tick        %d\n", ao_sample_tick);
499 #if HAS_BARO
500         printf ("  raw pres    %d\n", ao_sample_pres);
501 #endif
502 #if HAS_ACCEL
503         printf ("  raw accel   %d\n", ao_sample_accel);
504 #endif
505 #if HAS_BARO
506         printf ("  ground pres %d\n", ao_ground_pres);
507         printf ("  ground alt  %d\n", ao_ground_height);
508 #endif
509 #if HAS_ACCEL
510         printf ("  raw accel   %d\n", ao_sample_accel);
511         printf ("  groundaccel %d\n", ao_ground_accel);
512         printf ("  accel_2g    %d\n", ao_accel_2g);
513 #endif
514
515 #if HAS_BARO
516         printf ("  alt         %d\n", ao_sample_alt);
517         printf ("  height      %d\n", ao_sample_height);
518 #endif
519
520 #if HAS_ACCEL
521         printf ("  accel       %d.%02d\n", int_part(accel), frac_part(accel));
522 #endif
523
524
525         printf ("kalman:\n");
526         printf ("  height      %d\n", ao_height);
527         printf ("  speed       %d.%02d\n", int_part(ao_speed), frac_part(ao_speed));
528         printf ("  accel       %d.%02d\n", int_part(ao_accel), frac_part(ao_accel));
529         printf ("  max_height  %d\n", ao_max_height);
530         printf ("  avg_height  %d\n", ao_avg_height);
531         printf ("  error_h     %d\n", ao_error_h);
532 #if !HAS_ACCEL
533         printf ("  error_avg   %d\n", ao_error_h_sq_avg);
534 #endif
535 }
536
537 static void
538 ao_gyro_test(void)
539 {
540         ao_flight_state = ao_flight_test;
541         ao_getchar();
542         ao_flight_state = ao_flight_idle;
543 }
544
545 uint8_t ao_orient_test;
546
547 static void
548 ao_orient_test_select(void)
549 {
550         ao_orient_test = !ao_orient_test;
551 }
552
553 const struct ao_cmds ao_flight_cmds[] = {
554         { ao_flight_dump,       "F\0Dump flight status" },
555         { ao_gyro_test,         "G\0Test gyro code" },
556         { ao_orient_test_select,"O\0Test orientation code" },
557         { 0, NULL },
558 };
559 #endif
560
561 static struct ao_task   flight_task;
562
563 void
564 ao_flight_init(void)
565 {
566         ao_flight_state = ao_flight_startup;
567 #if HAS_FLIGHT_DEBUG
568         ao_cmd_register(&ao_flight_cmds[0]);
569 #endif
570         ao_add_task(&flight_task, ao_flight, "flight");
571 }