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