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