4b6bfd8f7109be78233e25f13f2aa9317410bbbb
[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 static bool accel_plus_g_failed;
106 static bool accel_minus_g_failed;
107 static bool accel_plus_failed;
108 static bool accel_minus_failed;
109
110 static char *btos(bool x) { return x? "true" : "false"; }
111
112 void
113 ao_flight(void)
114 {
115         ao_sample_init();
116         ao_flight_state = ao_flight_startup;
117         for (;;) {
118
119                 /*
120                  * Process ADC samples, just looping
121                  * until the sensors are calibrated.
122                  */
123                 if (!ao_sample())
124                         continue;
125
126                 switch (ao_flight_state) {
127                 case ao_flight_startup:
128
129                         /* Check to see what mode we should go to.
130                          *  - Invalid mode if accel cal appears to be out
131                          *  - pad mode if we're upright,
132                          *  - idle mode otherwise
133                          */
134 #if HAS_ACCEL
135                         if (ao_config.accel_plus_g == 0 ||
136                             ao_config.accel_minus_g == 0 ||
137                             ao_ground_accel < (accel_t) ao_config.accel_plus_g - ACCEL_NOSE_UP ||
138                             ao_ground_accel > (accel_t) ao_config.accel_minus_g + ACCEL_NOSE_UP
139 #if HAS_BARO
140                             || ao_ground_height < -1000 ||
141                             ao_ground_height > 7000
142 #endif
143                                 )
144                         {
145                                 if (ao_config.accel_plus_g == 0)
146                                         accel_plus_g_failed = true;
147                                 if (ao_config.accel_minus_g == 0)
148                                         accel_minus_g_failed = true;
149                                 if (ao_ground_accel < (accel_t) ao_config.accel_plus_g - ACCEL_NOSE_UP)
150                                         accel_plus_failed = true;
151                                 if (ao_ground_accel > (accel_t) ao_config.accel_minus_g + ACCEL_NOSE_UP)
152                                         accel_minus_failed = true;
153                                 /* Detected an accel value outside -1.5g to 1.5g
154                                  * (or uncalibrated values), so we go into invalid mode
155                                  */
156                                 ao_flight_state = ao_flight_invalid;
157
158 #if HAS_RADIO && PACKET_HAS_SLAVE
159                                 /* Turn on packet system in invalid mode on TeleMetrum */
160                                 ao_packet_slave_start();
161 #endif
162                         } else
163 #endif
164                                 if (!ao_flight_force_idle
165 #if HAS_ACCEL
166                                     && ao_ground_accel < ao_config.accel_plus_g + ACCEL_NOSE_UP
167 #endif
168                                         )
169                         {
170                                 /* Set pad mode - we can fly! */
171                                 ao_flight_state = ao_flight_pad;
172 #if HAS_USB && !HAS_FLIGHT_DEBUG && !HAS_SAMPLE_PROFILE && !DEBUG
173                                 /* Disable the USB controller in flight mode
174                                  * to save power
175                                  */
176 #if HAS_FAKE_FLIGHT
177                                 if (!ao_fake_flight_active)
178 #endif
179                                         ao_usb_disable();
180 #endif
181
182 #if !HAS_ACCEL && PACKET_HAS_SLAVE
183                                 /* Disable packet mode in pad state on TeleMini */
184                                 ao_packet_slave_stop();
185 #endif
186
187 #if HAS_TELEMETRY
188                                 /* Turn on telemetry system */
189                                 ao_rdf_set(1);
190                                 ao_telemetry_set_interval(AO_TELEMETRY_INTERVAL_PAD);
191 #endif
192 #if AO_LED_RED
193                                 /* signal successful initialization by turning off the LED */
194                                 ao_led_off(AO_LED_RED);
195 #endif
196                         } else {
197                                 /* Set idle mode */
198                                 ao_flight_state = ao_flight_idle;
199 #if HAS_SENSOR_ERRORS
200                                 if (ao_sensor_errors)
201                                         ao_flight_state = ao_flight_invalid;
202 #endif
203  
204 #if HAS_ACCEL && HAS_RADIO && PACKET_HAS_SLAVE
205                                 /* Turn on packet system in idle mode on TeleMetrum */
206                                 ao_packet_slave_start();
207 #endif
208
209 #if AO_LED_RED
210                                 /* signal successful initialization by turning off the LED */
211                                 ao_led_off(AO_LED_RED);
212 #endif
213                         }
214                         /* wakeup threads due to state change */
215                         ao_wakeup(&ao_flight_state);
216
217                         break;
218
219                 case ao_flight_invalid:
220                         printf("+g? %s -g? %s +? %s -? %s +g %d -g %d ga %d +g-NU %d -g+NU %d\n",
221                                btos(accel_plus_g_failed),
222                                btos(accel_minus_g_failed),
223                                btos(accel_plus_failed),
224                                btos(accel_minus_failed),
225                                ao_config.accel_plus_g,
226                                ao_config.accel_minus_g,
227                                ao_ground_accel,
228                                ao_config.accel_plus_g - ACCEL_NOSE_UP,
229                                ao_config.accel_minus_g + ACCEL_NOSE_UP);
230                         break;
231 #if 0
232                 case ao_flight_idle:
233                         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);
234                         break;
235 #endif
236
237                 case ao_flight_pad:
238                         /* pad to boost:
239                          *
240                          * barometer: > 20m vertical motion
241                          *             OR
242                          * accelerometer: > 2g AND velocity > 5m/s
243                          *
244                          * The accelerometer should always detect motion before
245                          * the barometer, but we use both to make sure this
246                          * transition is detected. If the device
247                          * doesn't have an accelerometer, then ignore the
248                          * speed and acceleration as they are quite noisy
249                          * on the pad.
250                          */
251                         if (ao_height > AO_M_TO_HEIGHT(20)
252 #if HAS_ACCEL
253                             || (ao_accel > AO_MSS_TO_ACCEL(20)
254 #if HAS_BARO
255                                 && ao_speed > AO_MS_TO_SPEED(5)
256 #endif
257 )
258 #endif
259                                 )
260                         {
261                                 ao_flight_state = ao_flight_boost;
262                                 ao_wakeup(&ao_flight_state);
263
264                                 ao_launch_tick = ao_boost_tick = ao_sample_tick;
265
266                                 /* start logging data */
267 #if HAS_LOG
268                                 ao_log_start();
269 #endif
270
271 #if HAS_TELEMETRY
272                                 /* Increase telemetry rate */
273                                 ao_telemetry_set_interval(AO_TELEMETRY_INTERVAL_FLIGHT);
274
275                                 /* disable RDF beacon */
276                                 ao_rdf_set(0);
277 #endif
278
279 #if HAS_GPS
280                                 /* Record current GPS position by waking up GPS log tasks */
281                                 ao_gps_new = AO_GPS_NEW_DATA | AO_GPS_NEW_TRACKING;
282                                 ao_wakeup(&ao_gps_new);
283 #endif
284                         }
285                         break;
286                 case ao_flight_boost:
287
288                         /* boost to fast:
289                          *
290                          * accelerometer: start to fall at > 1/4 G
291                          *              OR
292                          * time: boost for more than 15 seconds
293                          *
294                          * Detects motor burn out by the switch from acceleration to
295                          * deceleration, or by waiting until the maximum burn duration
296                          * (15 seconds) has past.
297                          */
298                         if ((ao_accel < AO_MSS_TO_ACCEL(-2.5)) ||
299                             (int16_t) (ao_sample_tick - ao_boost_tick) > BOOST_TICKS_MAX)
300                         {
301 #if HAS_ACCEL
302 #if HAS_BARO
303                                 ao_flight_state = ao_flight_fast;
304 #else
305                                 ao_flight_state = ao_flight_coast;
306
307                                 /* Initialize landing detection interval values */
308                                 ao_interval_end = ao_sample_tick + AO_INTERVAL_TICKS;
309
310                                 init_bounds(ao_sample_accel_along, ao_interval_min_accel_along, ao_interval_max_accel_along);
311                                 init_bounds(ao_sample_accel_across, ao_interval_min_accel_across, ao_interval_max_accel_across);
312                                 init_bounds(ao_sample_accel_through, ao_interval_min_accel_through, ao_interval_max_accel_through);
313 #endif
314                                 ao_coast_avg_accel = ao_accel;
315 #else
316                                 ao_flight_state = ao_flight_coast;
317 #endif
318                                 ao_wakeup(&ao_flight_state);
319                                 ++ao_motor_number;
320                         }
321                         break;
322 #if HAS_ACCEL && HAS_BARO
323                 case ao_flight_fast:
324                         /*
325                          * This is essentially the same as coast,
326                          * but the barometer is being ignored as
327                          * it may be unreliable.
328                          */
329                         if (ao_speed < AO_MS_TO_SPEED(AO_MAX_BARO_SPEED))
330                         {
331                                 ao_flight_state = ao_flight_coast;
332                                 ao_wakeup(&ao_flight_state);
333                         } else
334                                 goto check_re_boost;
335                         break;
336 #endif
337                 case ao_flight_coast:
338
339 #if HAS_BARO
340                         /*
341                          * By customer request - allow the user
342                          * to lock out apogee detection for a specified
343                          * number of seconds.
344                          */
345                         if (ao_config.apogee_lockout) {
346                                 if ((int16_t) (ao_sample_tick - ao_launch_tick) <
347                                     AO_SEC_TO_TICKS(ao_config.apogee_lockout))
348                                         break;
349                         }
350
351                         /* apogee detect: coast to drogue deploy:
352                          *
353                          * speed: < 0
354                          *
355                          * Also make sure the model altitude is tracking
356                          * the measured altitude reasonably closely; otherwise
357                          * we're probably transsonic.
358                          */
359 #define AO_ERROR_BOUND  100
360
361                         if (ao_speed < 0
362 #if !HAS_ACCEL
363                             && (ao_sample_alt >= AO_MAX_BARO_HEIGHT || ao_error_h_sq_avg < AO_ERROR_BOUND)
364 #endif
365                                 )
366                         {
367                                 /* enter drogue state */
368                                 ao_flight_state = ao_flight_drogue;
369                                 ao_wakeup(&ao_flight_state);
370 #if HAS_TELEMETRY
371                                 /* slow down the telemetry system */
372                                 ao_telemetry_set_interval(AO_TELEMETRY_INTERVAL_RECOVER);
373
374                                 /* Turn the RDF beacon back on */
375                                 ao_rdf_set(1);
376 #endif
377                         }
378                         else
379 #else /* not HAS_BARO */
380                         /* coast to land:
381                          *
382                          * accel: values stable
383                          */
384                         check_bounds(ao_sample_accel_along, ao_interval_min_accel_along, ao_interval_max_accel_along);
385                         check_bounds(ao_sample_accel_across, ao_interval_min_accel_across, ao_interval_max_accel_across);
386                         check_bounds(ao_sample_accel_through, ao_interval_min_accel_through, ao_interval_max_accel_through);
387
388 #define MAX_QUIET_ACCEL 2
389
390                         if ((int16_t) (ao_sample_tick - ao_interval_end) >= 0) {
391                                 if (ao_interval_max_accel_along - ao_interval_min_accel_along <= ao_data_accel_to_sample(MAX_QUIET_ACCEL) &&
392                                     ao_interval_max_accel_across - ao_interval_min_accel_across <= ao_data_accel_to_sample(MAX_QUIET_ACCEL) &&
393                                     ao_interval_max_accel_through - ao_interval_min_accel_through <= ao_data_accel_to_sample(MAX_QUIET_ACCEL))
394                                 {
395                                         ao_flight_state = ao_flight_landed;
396                                         ao_wakeup(&ao_flight_state);
397 #if HAS_ADC
398                                         /* turn off the ADC capture */
399                                         ao_timer_set_adc_interval(0);
400 #endif
401                                 }
402
403                                 /* Reset interval values */
404                                 ao_interval_end = ao_sample_tick + AO_INTERVAL_TICKS;
405
406                                 init_bounds(ao_sample_accel_along, ao_interval_min_accel_along, ao_interval_max_accel_along);
407                                 init_bounds(ao_sample_accel_across, ao_interval_min_accel_across, ao_interval_max_accel_across);
408                                 init_bounds(ao_sample_accel_through, ao_interval_min_accel_through, ao_interval_max_accel_through);
409                         }
410 #endif
411 #if HAS_ACCEL
412                         {
413 #if HAS_BARO
414                         check_re_boost:
415 #endif
416                                 ao_coast_avg_accel = ao_coast_avg_accel + ((ao_accel - ao_coast_avg_accel) >> 5);
417                                 if (ao_coast_avg_accel > AO_MSS_TO_ACCEL(20)) {
418                                         ao_boost_tick = ao_sample_tick;
419                                         ao_flight_state = ao_flight_boost;
420                                         ao_wakeup(&ao_flight_state);
421                                 }
422                         }
423 #endif
424
425                         break;
426 #if HAS_BARO
427                 case ao_flight_drogue:
428
429                         /* drogue to main deploy:
430                          *
431                          * barometer: reach main deploy altitude
432                          *
433                          * Would like to use the accelerometer for this test, but
434                          * the orientation of the flight computer is unknown after
435                          * drogue deploy, so we ignore it. Could also detect
436                          * high descent rate using the pressure sensor to
437                          * recognize drogue deploy failure and eject the main
438                          * at that point. Perhaps also use the drogue sense lines
439                          * to notice continutity?
440                          */
441                         if (ao_height <= ao_config.main_deploy)
442                         {
443                                 ao_flight_state = ao_flight_main;
444                                 ao_wakeup(&ao_flight_state);
445
446                                 /*
447                                  * Start recording min/max height
448                                  * to figure out when the rocket has landed
449                                  */
450
451                                 /* initialize interval values */
452                                 ao_interval_end = ao_sample_tick + AO_INTERVAL_TICKS;
453
454                                 ao_interval_min_height = ao_interval_max_height = ao_avg_height;
455                         }
456                         break;
457
458                         /* fall through... */
459                 case ao_flight_main:
460
461                         /* main to land:
462                          *
463                          * barometer: altitude stable
464                          */
465                         if (ao_avg_height < ao_interval_min_height)
466                                 ao_interval_min_height = ao_avg_height;
467                         if (ao_avg_height > ao_interval_max_height)
468                                 ao_interval_max_height = ao_avg_height;
469
470                         if ((int16_t) (ao_sample_tick - ao_interval_end) >= 0) {
471                                 if (ao_interval_max_height - ao_interval_min_height <= AO_M_TO_HEIGHT(4))
472                                 {
473                                         ao_flight_state = ao_flight_landed;
474                                         ao_wakeup(&ao_flight_state);
475 #if HAS_ADC
476                                         /* turn off the ADC capture */
477                                         ao_timer_set_adc_interval(0);
478 #endif
479                                 }
480                                 ao_interval_min_height = ao_interval_max_height = ao_avg_height;
481                                 ao_interval_end = ao_sample_tick + AO_INTERVAL_TICKS;
482                         }
483                         break;
484 #endif /* HAS_BARO */
485 #if HAS_FLIGHT_DEBUG
486                 case ao_flight_test:
487 #if HAS_GYRO
488                         printf ("angle %4d pitch %7d yaw %7d roll %7d\n",
489                                 ao_sample_orient,
490                                 ((ao_sample_pitch << 9) - ao_ground_pitch) >> 9,
491                                 ((ao_sample_yaw << 9) - ao_ground_yaw) >> 9,
492                                 ((ao_sample_roll << 9) - ao_ground_roll) >> 9);
493 #endif
494                         flush();
495                         break;
496 #endif /* HAS_FLIGHT_DEBUG */
497                 default:
498                         break;
499                 }
500         }
501 }
502
503 #if HAS_FLIGHT_DEBUG
504 static inline int int_part(ao_v_t i)    { return i >> 4; }
505 static inline int frac_part(ao_v_t i)   { return ((i & 0xf) * 100 + 8) / 16; }
506
507 static void
508 ao_flight_dump(void)
509 {
510 #if HAS_ACCEL
511         ao_v_t  accel;
512
513         accel = ((ao_config.accel_plus_g - ao_sample_accel) * ao_accel_scale) >> 16;
514 #endif
515
516         printf ("sample:\n");
517         printf ("  tick        %d\n", ao_sample_tick);
518 #if HAS_BARO
519         printf ("  raw pres    %d\n", ao_sample_pres);
520 #endif
521 #if HAS_ACCEL
522         printf ("  raw accel   %d\n", ao_sample_accel);
523 #endif
524 #if HAS_BARO
525         printf ("  ground pres %d\n", ao_ground_pres);
526         printf ("  ground alt  %d\n", ao_ground_height);
527 #endif
528 #if HAS_ACCEL
529         printf ("  raw accel   %d\n", ao_sample_accel);
530         printf ("  groundaccel %d\n", ao_ground_accel);
531         printf ("  accel_2g    %d\n", ao_accel_2g);
532 #endif
533
534 #if HAS_BARO
535         printf ("  alt         %d\n", ao_sample_alt);
536         printf ("  height      %d\n", ao_sample_height);
537 #endif
538
539 #if HAS_ACCEL
540         printf ("  accel       %d.%02d\n", int_part(accel), frac_part(accel));
541 #endif
542
543
544         printf ("kalman:\n");
545         printf ("  height      %d\n", ao_height);
546         printf ("  speed       %d.%02d\n", int_part(ao_speed), frac_part(ao_speed));
547         printf ("  accel       %d.%02d\n", int_part(ao_accel), frac_part(ao_accel));
548         printf ("  max_height  %d\n", ao_max_height);
549         printf ("  avg_height  %d\n", ao_avg_height);
550         printf ("  error_h     %d\n", ao_error_h);
551 #if !HAS_ACCEL
552         printf ("  error_avg   %d\n", ao_error_h_sq_avg);
553 #endif
554 }
555
556 static void
557 ao_gyro_test(void)
558 {
559         ao_flight_state = ao_flight_test;
560         ao_getchar();
561         ao_flight_state = ao_flight_idle;
562 }
563
564 uint8_t ao_orient_test;
565
566 static void
567 ao_orient_test_select(void)
568 {
569         ao_orient_test = !ao_orient_test;
570 }
571
572 const struct ao_cmds ao_flight_cmds[] = {
573         { ao_flight_dump,       "F\0Dump flight status" },
574         { ao_gyro_test,         "G\0Test gyro code" },
575         { ao_orient_test_select,"O\0Test orientation code" },
576         { 0, NULL },
577 };
578 #endif
579
580 static struct ao_task   flight_task;
581
582 void
583 ao_flight_init(void)
584 {
585         ao_flight_state = ao_flight_startup;
586 #if HAS_FLIGHT_DEBUG
587         ao_cmd_register(&ao_flight_cmds[0]);
588 #endif
589         ao_add_task(&flight_task, ao_flight, "flight");
590 }