883098ed9bdebbb08ff1a29432861b3c34ab6fc6
[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 < (accel_t) ao_config.accel_plus_g - ACCEL_NOSE_UP ||
131                             ao_ground_accel > (accel_t) 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 #if DEBUG_ACCEL_ONLY
205                 case ao_flight_invalid:
206                 case ao_flight_idle:
207                         printf("+g %d ga %d sa %d accel %ld speed %ld\n",
208                                ao_config.accel_plus_g, ao_ground_accel, ao_sample_accel, ao_accel, ao_speed);
209                         break;
210 #endif
211
212                 case ao_flight_pad:
213                         /* pad to boost:
214                          *
215                          * barometer: > 20m vertical motion
216                          *             OR
217                          * accelerometer: > 2g AND velocity > 5m/s
218                          *
219                          * The accelerometer should always detect motion before
220                          * the barometer, but we use both to make sure this
221                          * transition is detected. If the device
222                          * doesn't have an accelerometer, then ignore the
223                          * speed and acceleration as they are quite noisy
224                          * on the pad.
225                          */
226                         if (ao_height > AO_M_TO_HEIGHT(20)
227 #if HAS_ACCEL
228                             || (ao_accel > AO_MSS_TO_ACCEL(20)
229                                 && ao_speed > AO_MS_TO_SPEED(5))
230 #endif
231                                 )
232                         {
233                                 ao_flight_state = ao_flight_boost;
234                                 ao_wakeup(&ao_flight_state);
235
236                                 ao_launch_tick = ao_boost_tick = ao_sample_tick;
237
238                                 /* start logging data */
239 #if HAS_LOG
240                                 ao_log_start();
241 #endif
242
243 #if HAS_TELEMETRY
244                                 /* Increase telemetry rate */
245                                 ao_telemetry_set_interval(AO_TELEMETRY_INTERVAL_FLIGHT);
246
247                                 /* disable RDF beacon */
248                                 ao_rdf_set(0);
249 #endif
250
251 #if HAS_GPS
252                                 /* Record current GPS position by waking up GPS log tasks */
253                                 ao_gps_new = AO_GPS_NEW_DATA | AO_GPS_NEW_TRACKING;
254                                 ao_wakeup(&ao_gps_new);
255 #endif
256                         }
257                         break;
258                 case ao_flight_boost:
259
260                         /* boost to fast:
261                          *
262                          * accelerometer: start to fall at > 1/4 G
263                          *              OR
264                          * time: boost for more than 15 seconds
265                          *
266                          * Detects motor burn out by the switch from acceleration to
267                          * deceleration, or by waiting until the maximum burn duration
268                          * (15 seconds) has past.
269                          */
270                         if ((ao_accel < AO_MSS_TO_ACCEL(-2.5)) ||
271                             (int16_t) (ao_sample_tick - ao_boost_tick) > BOOST_TICKS_MAX)
272                         {
273 #if HAS_ACCEL
274 #if HAS_BARO
275                                 ao_flight_state = ao_flight_fast;
276 #else
277                                 ao_flight_state = ao_flight_coast;
278
279                                 /* Initialize landing detection interval values */
280                                 ao_interval_end = ao_sample_tick + AO_INTERVAL_TICKS;
281
282                                 init_bounds(ao_sample_accel_along, ao_interval_min_accel_along, ao_interval_max_accel_along);
283                                 init_bounds(ao_sample_accel_across, ao_interval_min_accel_across, ao_interval_max_accel_across);
284                                 init_bounds(ao_sample_accel_through, ao_interval_min_accel_through, ao_interval_max_accel_through);
285 #endif
286                                 ao_coast_avg_accel = ao_accel;
287 #else
288                                 ao_flight_state = ao_flight_coast;
289 #endif
290                                 ao_wakeup(&ao_flight_state);
291                                 ++ao_motor_number;
292                         }
293                         break;
294 #if HAS_ACCEL && HAS_BARO
295                 case ao_flight_fast:
296                         /*
297                          * This is essentially the same as coast,
298                          * but the barometer is being ignored as
299                          * it may be unreliable.
300                          */
301                         if (ao_speed < AO_MS_TO_SPEED(AO_MAX_BARO_SPEED))
302                         {
303                                 ao_flight_state = ao_flight_coast;
304                                 ao_wakeup(&ao_flight_state);
305                         } else
306                                 goto check_re_boost;
307                         break;
308 #endif
309                 case ao_flight_coast:
310
311 #if HAS_BARO
312                         /*
313                          * By customer request - allow the user
314                          * to lock out apogee detection for a specified
315                          * number of seconds.
316                          */
317                         if (ao_config.apogee_lockout) {
318                                 if ((int16_t) (ao_sample_tick - ao_launch_tick) <
319                                     AO_SEC_TO_TICKS(ao_config.apogee_lockout))
320                                         break;
321                         }
322
323                         /* apogee detect: coast to drogue deploy:
324                          *
325                          * speed: < 0
326                          *
327                          * Also make sure the model altitude is tracking
328                          * the measured altitude reasonably closely; otherwise
329                          * we're probably transsonic.
330                          */
331 #define AO_ERROR_BOUND  100
332
333                         if (ao_speed < 0
334 #if !HAS_ACCEL
335                             && (ao_sample_alt >= AO_MAX_BARO_HEIGHT || ao_error_h_sq_avg < AO_ERROR_BOUND)
336 #endif
337                                 )
338                         {
339                                 /* enter drogue state */
340                                 ao_flight_state = ao_flight_drogue;
341                                 ao_wakeup(&ao_flight_state);
342 #if HAS_TELEMETRY
343                                 /* slow down the telemetry system */
344                                 ao_telemetry_set_interval(AO_TELEMETRY_INTERVAL_RECOVER);
345
346                                 /* Turn the RDF beacon back on */
347                                 ao_rdf_set(1);
348 #endif
349                         }
350                         else
351 #else /* not HAS_BARO */
352                         /* coast to land:
353                          *
354                          * accel: values stable
355                          */
356                         check_bounds(ao_sample_accel_along, ao_interval_min_accel_along, ao_interval_max_accel_along);
357                         check_bounds(ao_sample_accel_across, ao_interval_min_accel_across, ao_interval_max_accel_across);
358                         check_bounds(ao_sample_accel_through, ao_interval_min_accel_through, ao_interval_max_accel_through);
359
360 #define MAX_QUIET_ACCEL 2
361
362                         if ((int16_t) (ao_sample_tick - ao_interval_end) >= 0) {
363                                 if (ao_interval_max_accel_along - ao_interval_min_accel_along <= ao_data_accel_to_sample(MAX_QUIET_ACCEL) &&
364                                     ao_interval_max_accel_across - ao_interval_min_accel_across <= ao_data_accel_to_sample(MAX_QUIET_ACCEL) &&
365                                     ao_interval_max_accel_through - ao_interval_min_accel_through <= ao_data_accel_to_sample(MAX_QUIET_ACCEL))
366                                 {
367                                         ao_flight_state = ao_flight_landed;
368                                         ao_wakeup(&ao_flight_state);
369 #if HAS_ADC
370                                         /* turn off the ADC capture */
371                                         ao_timer_set_adc_interval(0);
372 #endif
373                                 }
374
375                                 /* Reset interval values */
376                                 ao_interval_end = ao_sample_tick + AO_INTERVAL_TICKS;
377
378                                 init_bounds(ao_sample_accel_along, ao_interval_min_accel_along, ao_interval_max_accel_along);
379                                 init_bounds(ao_sample_accel_across, ao_interval_min_accel_across, ao_interval_max_accel_across);
380                                 init_bounds(ao_sample_accel_through, ao_interval_min_accel_through, ao_interval_max_accel_through);
381                         }
382 #endif
383 #if HAS_ACCEL
384                         {
385 #if HAS_BARO
386                         check_re_boost:
387 #endif
388                                 ao_coast_avg_accel = ao_coast_avg_accel + ((ao_accel - ao_coast_avg_accel) >> 5);
389                                 if (ao_coast_avg_accel > AO_MSS_TO_ACCEL(20)) {
390                                         ao_boost_tick = ao_sample_tick;
391                                         ao_flight_state = ao_flight_boost;
392                                         ao_wakeup(&ao_flight_state);
393                                 }
394                         }
395 #endif
396
397                         break;
398 #if HAS_BARO
399                 case ao_flight_drogue:
400
401                         /* drogue to main deploy:
402                          *
403                          * barometer: reach main deploy altitude
404                          *
405                          * Would like to use the accelerometer for this test, but
406                          * the orientation of the flight computer is unknown after
407                          * drogue deploy, so we ignore it. Could also detect
408                          * high descent rate using the pressure sensor to
409                          * recognize drogue deploy failure and eject the main
410                          * at that point. Perhaps also use the drogue sense lines
411                          * to notice continutity?
412                          */
413                         if (ao_height <= ao_config.main_deploy)
414                         {
415                                 ao_flight_state = ao_flight_main;
416                                 ao_wakeup(&ao_flight_state);
417
418                                 /*
419                                  * Start recording min/max height
420                                  * to figure out when the rocket has landed
421                                  */
422
423                                 /* initialize interval values */
424                                 ao_interval_end = ao_sample_tick + AO_INTERVAL_TICKS;
425
426                                 ao_interval_min_height = ao_interval_max_height = ao_avg_height;
427                         }
428                         break;
429
430                         /* fall through... */
431                 case ao_flight_main:
432
433                         /* main to land:
434                          *
435                          * barometer: altitude stable
436                          */
437                         if (ao_avg_height < ao_interval_min_height)
438                                 ao_interval_min_height = ao_avg_height;
439                         if (ao_avg_height > ao_interval_max_height)
440                                 ao_interval_max_height = ao_avg_height;
441
442                         if ((int16_t) (ao_sample_tick - ao_interval_end) >= 0) {
443                                 if (ao_interval_max_height - ao_interval_min_height <= AO_M_TO_HEIGHT(4))
444                                 {
445                                         ao_flight_state = ao_flight_landed;
446                                         ao_wakeup(&ao_flight_state);
447 #if HAS_ADC
448                                         /* turn off the ADC capture */
449                                         ao_timer_set_adc_interval(0);
450 #endif
451                                 }
452                                 ao_interval_min_height = ao_interval_max_height = ao_avg_height;
453                                 ao_interval_end = ao_sample_tick + AO_INTERVAL_TICKS;
454                         }
455                         break;
456 #endif /* HAS_BARO */
457 #if HAS_FLIGHT_DEBUG
458                 case ao_flight_test:
459 #if HAS_GYRO
460                         printf ("angle %4d pitch %7d yaw %7d roll %7d\n",
461                                 ao_sample_orient,
462                                 ((ao_sample_pitch << 9) - ao_ground_pitch) >> 9,
463                                 ((ao_sample_yaw << 9) - ao_ground_yaw) >> 9,
464                                 ((ao_sample_roll << 9) - ao_ground_roll) >> 9);
465 #endif
466                         flush();
467                         break;
468 #endif /* HAS_FLIGHT_DEBUG */
469                 default:
470                         break;
471                 }
472         }
473 }
474
475 #if HAS_FLIGHT_DEBUG
476 static inline int int_part(ao_v_t i)    { return i >> 4; }
477 static inline int frac_part(ao_v_t i)   { return ((i & 0xf) * 100 + 8) / 16; }
478
479 static void
480 ao_flight_dump(void)
481 {
482 #if HAS_ACCEL
483         ao_v_t  accel;
484
485         accel = ((ao_config.accel_plus_g - ao_sample_accel) * ao_accel_scale) >> 16;
486 #endif
487
488         printf ("sample:\n");
489         printf ("  tick        %d\n", ao_sample_tick);
490 #if HAS_BARO
491         printf ("  raw pres    %d\n", ao_sample_pres);
492 #endif
493 #if HAS_ACCEL
494         printf ("  raw accel   %d\n", ao_sample_accel);
495 #endif
496 #if HAS_BARO
497         printf ("  ground pres %d\n", ao_ground_pres);
498         printf ("  ground alt  %d\n", ao_ground_height);
499 #endif
500 #if HAS_ACCEL
501         printf ("  raw accel   %d\n", ao_sample_accel);
502         printf ("  groundaccel %d\n", ao_ground_accel);
503         printf ("  accel_2g    %d\n", ao_accel_2g);
504 #endif
505
506 #if HAS_BARO
507         printf ("  alt         %d\n", ao_sample_alt);
508         printf ("  height      %d\n", ao_sample_height);
509 #endif
510
511 #if HAS_ACCEL
512         printf ("  accel       %d.%02d\n", int_part(accel), frac_part(accel));
513 #endif
514
515
516         printf ("kalman:\n");
517         printf ("  height      %d\n", ao_height);
518         printf ("  speed       %d.%02d\n", int_part(ao_speed), frac_part(ao_speed));
519         printf ("  accel       %d.%02d\n", int_part(ao_accel), frac_part(ao_accel));
520         printf ("  max_height  %d\n", ao_max_height);
521         printf ("  avg_height  %d\n", ao_avg_height);
522         printf ("  error_h     %d\n", ao_error_h);
523 #if !HAS_ACCEL
524         printf ("  error_avg   %d\n", ao_error_h_sq_avg);
525 #endif
526 }
527
528 static void
529 ao_gyro_test(void)
530 {
531         ao_flight_state = ao_flight_test;
532         ao_getchar();
533         ao_flight_state = ao_flight_idle;
534 }
535
536 uint8_t ao_orient_test;
537
538 static void
539 ao_orient_test_select(void)
540 {
541         ao_orient_test = !ao_orient_test;
542 }
543
544 const struct ao_cmds ao_flight_cmds[] = {
545         { ao_flight_dump,       "F\0Dump flight status" },
546         { ao_gyro_test,         "G\0Test gyro code" },
547         { ao_orient_test_select,"O\0Test orientation code" },
548         { 0, NULL },
549 };
550 #endif
551
552 static struct ao_task   flight_task;
553
554 void
555 ao_flight_init(void)
556 {
557         ao_flight_state = ao_flight_startup;
558 #if HAS_FLIGHT_DEBUG
559         ao_cmd_register(&ao_flight_cmds[0]);
560 #endif
561         ao_add_task(&flight_task, ao_flight, "flight");
562 }