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