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