name change from MegaMetrum to TeleMega
[fw/altos] / src / test / ao_flight_test.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; version 2 of the License.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
16  */
17
18 #define _GNU_SOURCE
19
20 #include <stdint.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <getopt.h>
25 #include <math.h>
26
27 #define AO_HERTZ        100
28
29 #define HAS_ADC 1
30 #define AO_DATA_RING    64
31 #define ao_data_ring_next(n)    (((n) + 1) & (AO_DATA_RING - 1))
32 #define ao_data_ring_prev(n)    (((n) - 1) & (AO_DATA_RING - 1))
33
34 #define AO_M_TO_HEIGHT(m)       ((int16_t) (m))
35 #define AO_MS_TO_SPEED(ms)      ((int16_t) ((ms) * 16))
36 #define AO_MSS_TO_ACCEL(mss)    ((int16_t) ((mss) * 16))
37
38 #if TELEMEGA
39 #define AO_ADC_NUM_SENSE        6
40 #define HAS_MS5607              1
41 #define HAS_MPU6000             1
42 #define HAS_MMA655X             1
43
44 struct ao_adc {
45         int16_t                 sense[AO_ADC_NUM_SENSE];
46         int16_t                 v_batt;
47         int16_t                 v_pbatt;
48         int16_t                 accel_ref;
49         int16_t                 accel;
50         int16_t                 temp;
51 };
52 #else
53 /*
54  * One set of samples read from the A/D converter
55  */
56 struct ao_adc {
57         int16_t         accel;          /* accelerometer */
58         int16_t         pres;           /* pressure sensor */
59         int16_t         pres_real;      /* unclipped */
60         int16_t         temp;           /* temperature sensor */
61         int16_t         v_batt;         /* battery voltage */
62         int16_t         sense_d;        /* drogue continuity sense */
63         int16_t         sense_m;        /* main continuity sense */
64 };
65
66 #ifndef HAS_ACCEL
67 #define HAS_ACCEL 1
68 #define HAS_ACCEL_REF 0
69 #endif
70
71 #endif
72
73 #define __pdata
74 #define __data
75 #define __xdata
76 #define __code
77 #define __reentrant
78
79 #define HAS_FLIGHT 1
80 #define HAS_IGNITE 1
81 #define HAS_USB 1
82 #define HAS_GPS 1
83
84 #include <ao_data.h>
85 #include <ao_log.h>
86
87 #define to_fix16(x) ((int16_t) ((x) * 65536.0 + 0.5))
88 #define to_fix32(x) ((int32_t) ((x) * 65536.0 + 0.5))
89 #define from_fix(x)     ((x) >> 16)
90
91 /*
92  * Above this height, the baro sensor doesn't work
93  */
94 #define AO_BARO_SATURATE        13000
95 #define AO_MIN_BARO_VALUE       ao_altitude_to_pres(AO_BARO_SATURATE)
96
97 /*
98  * Above this speed, baro measurements are unreliable
99  */
100 #define AO_MAX_BARO_SPEED       200
101
102 #define ACCEL_NOSE_UP   (ao_accel_2g >> 2)
103
104 extern enum ao_flight_state ao_flight_state;
105
106 #define FALSE 0
107 #define TRUE 1
108
109 volatile struct ao_data ao_data_ring[AO_DATA_RING];
110 volatile uint8_t ao_data_head;
111 int     ao_summary = 0;
112
113 #define ao_led_on(l)
114 #define ao_led_off(l)
115 #define ao_timer_set_adc_interval(i)
116 #define ao_wakeup(wchan) ao_dump_state()
117 #define ao_cmd_register(c)
118 #define ao_usb_disable()
119 #define ao_telemetry_set_interval(x)
120 #define ao_rdf_set(rdf)
121 #define ao_packet_slave_start()
122 #define ao_packet_slave_stop()
123
124 enum ao_igniter {
125         ao_igniter_drogue = 0,
126         ao_igniter_main = 1
127 };
128
129 struct ao_data ao_data_static;
130
131 int     drogue_height;
132 double  drogue_time;
133 int     main_height;
134 double  main_time;
135
136 int     tick_offset;
137
138 static int32_t  ao_k_height;
139
140 void
141 ao_ignite(enum ao_igniter igniter)
142 {
143         double time = (double) (ao_data_static.tick + tick_offset) / 100;
144
145         if (igniter == ao_igniter_drogue) {
146                 drogue_time = time;
147                 drogue_height = ao_k_height >> 16;
148         } else {
149                 main_time = time;
150                 main_height = ao_k_height >> 16;
151         }
152 }
153
154 struct ao_task {
155         int dummy;
156 };
157
158 #define ao_add_task(t,f,n) ((void) (t))
159
160 #define ao_log_start()
161 #define ao_log_stop()
162
163 #define AO_MS_TO_TICKS(ms)      ((ms) / 10)
164 #define AO_SEC_TO_TICKS(s)      ((s) * 100)
165
166 #define AO_FLIGHT_TEST
167
168 int     ao_flight_debug;
169
170 FILE *emulator_in;
171 char *emulator_app;
172 char *emulator_name;
173 char *emulator_info;
174 double emulator_error_max = 4;
175 double emulator_height_error_max = 20;  /* noise in the baro sensor */
176
177 void
178 ao_dump_state(void);
179
180 void
181 ao_sleep(void *wchan);
182
183 const char const * const ao_state_names[] = {
184         "startup", "idle", "pad", "boost", "fast",
185         "coast", "drogue", "main", "landed", "invalid"
186 };
187
188 struct ao_cmds {
189         void            (*func)(void);
190         const char      *help;
191 };
192
193 #define ao_xmemcpy(d,s,c) memcpy(d,s,c)
194 #define ao_xmemset(d,v,c) memset(d,v,c)
195 #define ao_xmemcmp(d,s,c) memcmp(d,s,c)
196
197 #define AO_NEED_ALTITUDE_TO_PRES 1
198 #if TELEMEGA
199 #include "ao_convert_pa.c"
200 #include <ao_ms5607.h>
201 struct ao_ms5607_prom   ms5607_prom;
202 #include "ao_ms5607_convert.c"
203 #else
204 #include "ao_convert.c"
205 #endif
206
207 struct ao_config {
208         uint16_t        main_deploy;
209         int16_t         accel_plus_g;
210         int16_t         accel_minus_g;
211         uint8_t         pad_orientation;
212         uint16_t        apogee_lockout;
213 };
214
215 #define AO_PAD_ORIENTATION_ANTENNA_UP   0
216 #define AO_PAD_ORIENTATION_ANTENNA_DOWN 1
217
218 #define ao_config_get()
219
220 struct ao_config ao_config;
221
222 #define DATA_TO_XDATA(x) (x)
223
224
225 #define GRAVITY 9.80665
226 extern int16_t ao_ground_accel, ao_flight_accel;
227 extern int16_t ao_accel_2g;
228
229 typedef int16_t accel_t;
230
231 extern uint16_t ao_sample_tick;
232
233 extern alt_t    ao_sample_height;
234 extern accel_t  ao_sample_accel;
235 extern int32_t  ao_accel_scale;
236 extern alt_t    ao_ground_height;
237 extern alt_t    ao_sample_alt;
238
239 double ao_sample_qangle;
240
241 int ao_sample_prev_tick;
242 uint16_t        prev_tick;
243
244
245 #include "ao_kalman.c"
246 #include "ao_sqrt.c"
247 #include "ao_sample.c"
248 #include "ao_flight.c"
249
250 #define to_double(f)    ((f) / 65536.0)
251
252 static int      ao_records_read = 0;
253 static int      ao_eof_read = 0;
254 static int      ao_flight_ground_accel;
255 static int      ao_flight_started = 0;
256 static int      ao_test_max_height;
257 static double   ao_test_max_height_time;
258 static int      ao_test_main_height;
259 static double   ao_test_main_height_time;
260 static double   ao_test_landed_time;
261 static double   ao_test_landed_height;
262 static double   ao_test_landed_time;
263 static int      landed_set;
264 static double   landed_time;
265 static double   landed_height;
266
267 #if HAS_MPU6000
268 static struct ao_mpu6000_sample ao_ground_mpu6000;
269 #endif
270
271 void
272 ao_test_exit(void)
273 {
274         double  drogue_error;
275         double  main_error;
276         double  landed_error;
277         double  landed_time_error;
278
279         if (!ao_test_main_height_time) {
280                 ao_test_main_height_time = ao_test_max_height_time;
281                 ao_test_main_height = ao_test_max_height;
282         }
283         drogue_error = fabs(ao_test_max_height_time - drogue_time);
284         main_error = fabs(ao_test_main_height_time - main_time);
285         landed_error = fabs(ao_test_landed_height - landed_height);
286         landed_time_error = ao_test_landed_time - landed_time;
287         if (drogue_error > emulator_error_max || main_error > emulator_error_max) {
288                 printf ("%s %s\n",
289                         emulator_app, emulator_name);
290                 if (emulator_info)
291                         printf ("\t%s\n", emulator_info);
292                 printf ("\tApogee error %g\n", drogue_error);
293                 printf ("\tMain error %g\n", main_error);
294                 printf ("\tLanded height error %g\n", landed_error);
295                 printf ("\tLanded time error %g\n", landed_time_error);
296                 printf ("\tActual: apogee: %d at %7.2f main: %d at %7.2f landed %7.2f at %7.2f\n",
297                         ao_test_max_height, ao_test_max_height_time,
298                         ao_test_main_height, ao_test_main_height_time,
299                         ao_test_landed_height, ao_test_landed_time);
300                 printf ("\tComputed: apogee: %d at %7.2f main: %d at %7.2f landed %7.2f at %7.2f\n",
301                         drogue_height, drogue_time, main_height, main_time,
302                         landed_height, landed_time);
303                 exit (1);
304         }
305         exit(0);
306 }
307
308 #if HAS_MPU6000
309 static double
310 ao_mpu6000_accel(int16_t sensor)
311 {
312         return sensor / 32767.0 * MPU6000_ACCEL_FULLSCALE * GRAVITY;
313 }
314
315 static double
316 ao_mpu6000_gyro(int32_t sensor)
317 {
318         return sensor / 32767.0 * MPU6000_GYRO_FULLSCALE;
319 }
320 #endif
321
322 void
323 ao_insert(void)
324 {
325         double  time;
326
327         ao_data_ring[ao_data_head] = ao_data_static;
328         ao_data_head = ao_data_ring_next(ao_data_head);
329         if (ao_flight_state != ao_flight_startup) {
330 #if HAS_ACCEL
331                 double  accel = ((ao_flight_ground_accel - ao_data_accel_cook(&ao_data_static)) * GRAVITY * 2.0) /
332                         (ao_config.accel_minus_g - ao_config.accel_plus_g);
333 #else
334                 double  accel = 0.0;
335 #endif
336 #if TELEMEGA
337                 double  height;
338
339                 ao_ms5607_convert(&ao_data_static.ms5607_raw, &ao_data_static.ms5607_cooked);
340                 height = ao_pa_to_altitude(ao_data_static.ms5607_cooked.pres) - ao_ground_height;
341 #else
342                 double  height = ao_pres_to_altitude(ao_data_static.adc.pres_real) - ao_ground_height;
343 #endif
344
345                 if (!tick_offset)
346                         tick_offset = -ao_data_static.tick;
347                 if ((prev_tick - ao_data_static.tick) > 0x400)
348                         tick_offset += 65536;
349                 prev_tick = ao_data_static.tick;
350                 time = (double) (ao_data_static.tick + tick_offset) / 100;
351
352                 if (ao_test_max_height < height) {
353                         ao_test_max_height = height;
354                         ao_test_max_height_time = time;
355                         ao_test_landed_height = height;
356                         ao_test_landed_time = time;
357                 }
358                 if (height > ao_config.main_deploy) {
359                         ao_test_main_height_time = time;
360                         ao_test_main_height = height;
361                 }
362
363                 if (ao_test_landed_height > height) {
364                         ao_test_landed_height = height;
365                         ao_test_landed_time = time;
366                 }
367
368                 if (ao_flight_state == ao_flight_landed && !landed_set) {
369                         landed_set = 1;
370                         landed_time = time;
371                         landed_height = height;
372                 }
373
374                 if (!ao_summary) {
375                         printf("%7.2f height %8.2f accel %8.3f "
376 #if TELEMEGA
377                                "roll %8.3f angle %8.3f qangle %8.3f "
378                                "accel_x %8.3f accel_y %8.3f accel_z %8.3f gyro_x %8.3f gyro_y %8.3f gyro_z %8.3f "
379 #endif
380                                "state %-8.8s k_height %8.2f k_speed %8.3f k_accel %8.3f avg_height %5d drogue %4d main %4d error %5d\n",
381                                time,
382                                height,
383                                accel,
384 #if TELEMEGA
385                                ao_mpu6000_gyro(ao_sample_roll_angle) / 100.0,
386                                ao_mpu6000_gyro(ao_sample_angle) / 100.0,
387                                ao_sample_qangle,
388                                ao_mpu6000_accel(ao_data_static.mpu6000.accel_x),
389                                ao_mpu6000_accel(ao_data_static.mpu6000.accel_y),
390                                ao_mpu6000_accel(ao_data_static.mpu6000.accel_z),
391                                ao_mpu6000_gyro(ao_data_static.mpu6000.gyro_x - ao_ground_mpu6000.gyro_x),
392                                ao_mpu6000_gyro(ao_data_static.mpu6000.gyro_y - ao_ground_mpu6000.gyro_y),
393                                ao_mpu6000_gyro(ao_data_static.mpu6000.gyro_z - ao_ground_mpu6000.gyro_z),
394 #endif
395                                ao_state_names[ao_flight_state],
396                                ao_k_height / 65536.0,
397                                ao_k_speed / 65536.0 / 16.0,
398                                ao_k_accel / 65536.0 / 16.0,
399                                ao_avg_height,
400                                drogue_height,
401                                main_height,
402                                ao_error_h_sq_avg);
403                         
404 //                      if (ao_flight_state == ao_flight_landed)
405 //                              ao_test_exit();
406                 }
407         }
408 }
409
410 #define AO_MAX_CALLSIGN                 8
411 #define AO_MAX_VERSION                  8
412 #define AO_MAX_TELEMETRY                128
413
414 struct ao_telemetry_generic {
415         uint16_t        serial;         /* 0 */
416         uint16_t        tick;           /* 2 */
417         uint8_t         type;           /* 4 */
418         uint8_t         payload[27];    /* 5 */
419         /* 32 */
420 };
421
422 #define AO_TELEMETRY_SENSOR_TELEMETRUM  0x01
423 #define AO_TELEMETRY_SENSOR_TELEMINI    0x02
424 #define AO_TELEMETRY_SENSOR_TELENANO    0x03
425
426 struct ao_telemetry_sensor {
427         uint16_t        serial;         /*  0 */
428         uint16_t        tick;           /*  2 */
429         uint8_t         type;           /*  4 */
430
431         uint8_t         state;          /*  5 flight state */
432         int16_t         accel;          /*  6 accelerometer (TM only) */
433         int16_t         pres;           /*  8 pressure sensor */
434         int16_t         temp;           /* 10 temperature sensor */
435         int16_t         v_batt;         /* 12 battery voltage */
436         int16_t         sense_d;        /* 14 drogue continuity sense (TM/Tm) */
437         int16_t         sense_m;        /* 16 main continuity sense (TM/Tm) */
438
439         int16_t         acceleration;   /* 18 m/s² * 16 */
440         int16_t         speed;          /* 20 m/s * 16 */
441         int16_t         height;         /* 22 m */
442
443         int16_t         ground_pres;    /* 24 average pres on pad */
444         int16_t         ground_accel;   /* 26 average accel on pad */
445         int16_t         accel_plus_g;   /* 28 accel calibration at +1g */
446         int16_t         accel_minus_g;  /* 30 accel calibration at -1g */
447         /* 32 */
448 };
449
450 #define AO_TELEMETRY_CONFIGURATION      0x04
451
452 struct ao_telemetry_configuration {
453         uint16_t        serial;                         /*  0 */
454         uint16_t        tick;                           /*  2 */
455         uint8_t         type;                           /*  4 */
456
457         uint8_t         device;                         /*  5 device type */
458         uint16_t        flight;                         /*  6 flight number */
459         uint8_t         config_major;                   /*  8 Config major version */
460         uint8_t         config_minor;                   /*  9 Config minor version */
461         uint16_t        apogee_delay;                   /* 10 Apogee deploy delay in seconds */
462         uint16_t        main_deploy;                    /* 12 Main deploy alt in meters */
463         uint16_t        flight_log_max;                 /* 14 Maximum flight log size in kB */
464         char            callsign[AO_MAX_CALLSIGN];      /* 16 Radio operator identity */
465         char            version[AO_MAX_VERSION];        /* 24 Software version */
466         /* 32 */
467 };
468
469 #define AO_TELEMETRY_LOCATION           0x05
470
471 #define AO_GPS_MODE_NOT_VALID           'N'
472 #define AO_GPS_MODE_AUTONOMOUS          'A'
473 #define AO_GPS_MODE_DIFFERENTIAL        'D'
474 #define AO_GPS_MODE_ESTIMATED           'E'
475 #define AO_GPS_MODE_MANUAL              'M'
476 #define AO_GPS_MODE_SIMULATED           'S'
477
478 struct ao_telemetry_location {
479         uint16_t        serial;         /*  0 */
480         uint16_t        tick;           /*  2 */
481         uint8_t         type;           /*  4 */
482
483         uint8_t         flags;          /*  5 Number of sats and other flags */
484         int16_t         altitude;       /*  6 GPS reported altitude (m) */
485         int32_t         latitude;       /*  8 latitude (degrees * 10⁷) */
486         int32_t         longitude;      /* 12 longitude (degrees * 10⁷) */
487         uint8_t         year;           /* 16 (- 2000) */
488         uint8_t         month;          /* 17 (1-12) */
489         uint8_t         day;            /* 18 (1-31) */
490         uint8_t         hour;           /* 19 (0-23) */
491         uint8_t         minute;         /* 20 (0-59) */
492         uint8_t         second;         /* 21 (0-59) */
493         uint8_t         pdop;           /* 22 (m * 5) */
494         uint8_t         hdop;           /* 23 (m * 5) */
495         uint8_t         vdop;           /* 24 (m * 5) */
496         uint8_t         mode;           /* 25 */
497         uint16_t        ground_speed;   /* 26 cm/s */
498         int16_t         climb_rate;     /* 28 cm/s */
499         uint8_t         course;         /* 30 degrees / 2 */
500         uint8_t         unused[1];      /* 31 */
501         /* 32 */
502 };
503
504 #define AO_TELEMETRY_SATELLITE          0x06
505
506 struct ao_telemetry_satellite_info {
507         uint8_t         svid;
508         uint8_t         c_n_1;
509 };
510
511 struct ao_telemetry_satellite {
512         uint16_t                                serial;         /*  0 */
513         uint16_t                                tick;           /*  2 */
514         uint8_t                                 type;           /*  4 */
515         uint8_t                                 channels;       /*  5 number of reported sats */
516
517         struct ao_telemetry_satellite_info      sats[12];       /* 6 */
518         uint8_t                                 unused[2];      /* 30 */
519         /* 32 */
520 };
521
522 union ao_telemetry_all {
523         struct ao_telemetry_generic             generic;
524         struct ao_telemetry_sensor              sensor;
525         struct ao_telemetry_configuration       configuration;
526         struct ao_telemetry_location            location;
527         struct ao_telemetry_satellite           satellite;
528 };
529
530 uint16_t
531 uint16(uint8_t *bytes, int off)
532 {
533         return (uint16_t) bytes[off] | (((uint16_t) bytes[off+1]) << 8);
534 }
535
536 int16_t
537 int16(uint8_t *bytes, int off)
538 {
539         return (int16_t) uint16(bytes, off);
540 }
541
542 uint32_t
543 uint32(uint8_t *bytes, int off)
544 {
545         return (uint32_t) bytes[off] | (((uint32_t) bytes[off+1]) << 8) |
546                 (((uint32_t) bytes[off+2]) << 16) |
547                 (((uint32_t) bytes[off+3]) << 24);
548 }
549
550 int32_t
551 int32(uint8_t *bytes, int off)
552 {
553         return (int32_t) uint32(bytes, off);
554 }
555
556 static int log_format;
557
558 #if TELEMEGA
559
560 static double
561 ao_vec_norm(double x, double y, double z)
562 {
563         return x*x + y*y + z*z;
564 }
565
566 static void
567 ao_vec_normalize(double *x, double *y, double *z)
568 {
569         double  scale = 1/sqrt(ao_vec_norm(*x, *y, *z));
570
571         *x *= scale;
572         *y *= scale;
573         *z *= scale;
574 }
575
576 struct ao_quat {
577         double  q0, q1, q2, q3;
578 };
579
580 static void
581 ao_quat_mul(struct ao_quat *r, struct ao_quat *a, struct ao_quat *b)
582 {
583         r->q0 = a->q0 * b->q0 - a->q1 * b->q1 - a->q2 * b->q2 - a->q3 * b->q3;
584         r->q1 = a->q0 * b->q1 + a->q1 * b->q0 + a->q2 * b->q3 - a->q3 * b->q2;
585         r->q2 = a->q0 * b->q2 - a->q1 * b->q3 + a->q2 * b->q0 + a->q3 * b->q1;
586         r->q3 = a->q0 * b->q3 + a->q1 * b->q2 - a->q2 * b->q1 + a->q3 * b->q0;
587 }
588
589 #if 0
590 static void
591 ao_quat_scale(struct ao_quat *r, struct ao_quat *a, double s)
592 {
593         r->q0 = a->q0 * s;
594         r->q1 = a->q1 * s;
595         r->q2 = a->q2 * s;
596         r->q3 = a->q3 * s;
597 }
598 #endif
599
600 static void
601 ao_quat_conj(struct ao_quat *r, struct ao_quat *a)
602 {
603         r->q0 =  a->q0;
604         r->q1 = -a->q1;
605         r->q2 = -a->q2;
606         r->q3 = -a->q3;
607 }
608
609 static void
610 ao_quat_rot(struct ao_quat *r, struct ao_quat *a, struct ao_quat *q)
611 {
612         struct ao_quat  t;
613         struct ao_quat  c;
614         ao_quat_mul(&t, q, a);
615         ao_quat_conj(&c, q);
616         ao_quat_mul(r, &t, &c);
617 }
618
619 static void
620 ao_quat_from_angle(struct ao_quat *r,
621                    double x_rad,
622                    double y_rad,
623                    double z_rad)
624 {
625         double angle = sqrt (x_rad * x_rad + y_rad * y_rad + z_rad * z_rad);
626         double s = sin(angle/2);
627         double c = cos(angle/2);
628
629         r->q0 = c;
630         r->q1 = x_rad * s / angle;
631         r->q2 = y_rad * s / angle;
632         r->q3 = z_rad * s / angle;
633 }
634
635 static void
636 ao_quat_from_vector(struct ao_quat *r, double x, double y, double z)
637 {
638         ao_vec_normalize(&x, &y, &z);
639         double  x_rad = atan2(z, y);
640         double  y_rad = atan2(x, z);
641         double  z_rad = atan2(y, x);
642
643         ao_quat_from_angle(r, x_rad, y_rad, z_rad);
644 }
645
646 static double
647 ao_quat_norm(struct ao_quat *a)
648 {
649         return (a->q0 * a->q0 +
650                 a->q1 * a->q1 +
651                 a->q2 * a->q2 +
652                 a->q3 * a->q3);
653 }
654
655 static void
656 ao_quat_normalize(struct ao_quat *a)
657 {
658         double  norm = ao_quat_norm(a);
659
660         if (norm) {
661                 double m = 1/sqrt(norm);
662
663                 a->q0 *= m;
664                 a->q1 *= m;
665                 a->q2 *= m;
666                 a->q3 *= m;
667         }
668 }
669
670 static struct ao_quat   ao_up, ao_current;
671 static struct ao_quat   ao_orient;
672 static int              ao_orient_tick;
673
674 void
675 set_orientation(double x, double y, double z, int tick)
676 {
677         struct ao_quat  t;
678
679         printf ("set_orientation %g %g %g\n", x, y, z);
680         ao_quat_from_vector(&ao_orient, x, y, z);
681         ao_up.q1 = ao_up.q2 = 0;
682         ao_up.q0 = ao_up.q3 = sqrt(2)/2;
683         ao_orient_tick = tick;
684
685         ao_orient.q0 = 1;
686         ao_orient.q1 = 0;
687         ao_orient.q2 = 0;
688         ao_orient.q3 = 0;
689
690         printf ("orient (%g) %g %g %g up (%g) %g %g %g\n",
691                 ao_orient.q0,
692                 ao_orient.q1,
693                 ao_orient.q2,
694                 ao_orient.q3,
695                 ao_up.q0,
696                 ao_up.q1,
697                 ao_up.q2,
698                 ao_up.q3);
699
700         ao_quat_rot(&t, &ao_up, &ao_orient);
701         printf ("pad orient (%g) %g %g %g\n",
702                 t.q0,
703                 t.q1,
704                 t.q2,
705                 t.q3);
706
707 }
708
709 void
710 update_orientation (double rate_x, double rate_y, double rate_z, int tick)
711 {
712         struct ao_quat  q_dot;
713         double          lambda;
714         double          dt = (tick - ao_orient_tick) / 100.0;
715
716         ao_orient_tick = tick;
717  
718 //      lambda = 1 - ao_quat_norm(&ao_orient);
719         lambda = 0;
720
721         q_dot.q0 = -0.5 * (ao_orient.q1 * rate_x + ao_orient.q2 * rate_y + ao_orient.q3 * rate_z) + lambda * ao_orient.q0;
722         q_dot.q1 =  0.5 * (ao_orient.q0 * rate_x + ao_orient.q2 * rate_z - ao_orient.q3 * rate_y) + lambda * ao_orient.q1;
723         q_dot.q2 =  0.5 * (ao_orient.q0 * rate_y + ao_orient.q3 * rate_x - ao_orient.q1 * rate_z) + lambda * ao_orient.q2;
724         q_dot.q3 =  0.5 * (ao_orient.q0 * rate_z + ao_orient.q1 * rate_y - ao_orient.q2 * rate_x) + lambda * ao_orient.q3;
725
726 #if 0
727         printf ("update_orientation %g %g %g (%g s)\n", rate_x, rate_y, rate_z, dt);
728         printf ("q_dot (%g) %g %g %g\n",
729                 q_dot.q0,
730                 q_dot.q1,
731                 q_dot.q2,
732                 q_dot.q3);
733 #endif
734
735         ao_orient.q0 += q_dot.q0 * dt;
736         ao_orient.q1 += q_dot.q1 * dt;
737         ao_orient.q2 += q_dot.q2 * dt;
738         ao_orient.q3 += q_dot.q3 * dt;
739
740         ao_quat_normalize(&ao_orient);
741
742         ao_quat_rot(&ao_current, &ao_up, &ao_orient);
743
744         ao_sample_qangle = 180 / M_PI * acos(ao_current.q3 * sqrt(2));
745 #if 0
746         printf ("orient (%g) %g %g %g current (%g) %g %g %g\n",
747                 ao_orient.q0,
748                 ao_orient.q1,
749                 ao_orient.q2,
750                 ao_orient.q3,
751                 ao_current.q0,
752                 ao_current.q1,
753                 ao_current.q2,
754                 ao_current.q3);
755 #endif
756 }
757 #endif
758
759 void
760 ao_sleep(void *wchan)
761 {
762         if (wchan == &ao_data_head) {
763                 char            type = 0;
764                 uint16_t        tick = 0;
765                 uint16_t        a = 0, b = 0;
766                 uint8_t         bytes[1024];
767                 union ao_telemetry_all  telem;
768                 char            line[1024];
769                 char            *saveptr;
770                 char            *l;
771                 char            *words[64];
772                 int             nword;
773
774                 for (;;) {
775                         if (ao_records_read > 2 && ao_flight_state == ao_flight_startup)
776                         {
777 #if TELEMEGA
778                                 ao_data_static.mpu6000 = ao_ground_mpu6000;
779 #else
780                                 ao_data_static.adc.accel = ao_flight_ground_accel;
781 #endif
782                                 ao_insert();
783                                 return;
784                         }
785
786                         if (!fgets(line, sizeof (line), emulator_in)) {
787                                 if (++ao_eof_read >= 1000) {
788                                         if (!ao_summary)
789                                                 printf ("no more data, exiting simulation\n");
790                                         ao_test_exit();
791                                 }
792                                 ao_data_static.tick += 10;
793                                 ao_insert();
794                                 return;
795                         }
796                         l = line;
797                         for (nword = 0; nword < 64; nword++) {
798                                 words[nword] = strtok_r(l, " \t\n", &saveptr);
799                                 l = NULL;
800                                 if (words[nword] == NULL)
801                                         break;
802                         }
803 #if TELEMEGA
804                         if (log_format == AO_LOG_FORMAT_TELEMEGA && nword == 30 && strlen(words[0]) == 1) {
805                                 int     i;
806                                 struct ao_ms5607_value  value;
807
808                                 type = words[0][0];
809                                 tick = strtoul(words[1], NULL, 16);
810 //                              printf ("%c %04x", type, tick);
811                                 for (i = 2; i < nword; i++) {
812                                         bytes[i - 2] = strtoul(words[i], NULL, 16);
813 //                                      printf(" %02x", bytes[i-2]);
814                                 }
815 //                              printf ("\n");
816                                 switch (type) {
817                                 case 'F':
818                                         ao_flight_ground_accel = int16(bytes, 2);
819                                         ao_flight_started = 1;
820                                         ao_ground_pres = int32(bytes, 4);
821                                         ao_ground_height = ao_pa_to_altitude(ao_ground_pres);
822                                         break;
823                                 case 'A':
824                                         ao_data_static.tick = tick;
825                                         ao_data_static.ms5607_raw.pres = int32(bytes, 0);
826                                         ao_data_static.ms5607_raw.temp = int32(bytes, 4);
827                                         ao_ms5607_convert(&ao_data_static.ms5607_raw, &value);
828                                         ao_data_static.mpu6000.accel_x = int16(bytes, 8);
829                                         ao_data_static.mpu6000.accel_y = -int16(bytes, 10);
830                                         ao_data_static.mpu6000.accel_z = int16(bytes, 12);
831                                         ao_data_static.mpu6000.gyro_x = int16(bytes, 14);
832                                         ao_data_static.mpu6000.gyro_y = -int16(bytes, 16);
833                                         ao_data_static.mpu6000.gyro_z = int16(bytes, 18);
834 #if HAS_MMA655X
835                                         ao_data_static.mma655x = int16(bytes, 26);
836 #endif
837                                         if (ao_records_read == 0)
838                                                 ao_ground_mpu6000 = ao_data_static.mpu6000;
839                                         else if (ao_records_read < 10) {
840 #define f(f) ao_ground_mpu6000.f = ao_ground_mpu6000.f + ((ao_data_static.mpu6000.f - ao_ground_mpu6000.f) >> 2)
841                                                 f(accel_x);
842                                                 f(accel_y);
843                                                 f(accel_z);
844                                                 f(gyro_x);
845                                                 f(gyro_y);
846                                                 f(gyro_z);
847
848                                                 double          accel_x = ao_mpu6000_accel(ao_ground_mpu6000.accel_x);
849                                                 double          accel_y = ao_mpu6000_accel(ao_ground_mpu6000.accel_y);
850                                                 double          accel_z = ao_mpu6000_accel(ao_ground_mpu6000.accel_z);
851
852                                                 /* X and Y are in the ground plane, arbitraryily picked as MPU X and Z axes
853                                                  * Z is normal to the ground, the MPU y axis
854                                                  */
855                                                 set_orientation(accel_x, accel_z, accel_y, tick);
856                                         } else {
857                                                 double          rate_x = ao_mpu6000_gyro(ao_data_static.mpu6000.gyro_x - ao_ground_mpu6000.gyro_x);
858                                                 double          rate_y = ao_mpu6000_gyro(ao_data_static.mpu6000.gyro_y - ao_ground_mpu6000.gyro_y);
859                                                 double          rate_z = ao_mpu6000_gyro(ao_data_static.mpu6000.gyro_z - ao_ground_mpu6000.gyro_z);
860
861                                                 update_orientation(rate_x * M_PI / 180, rate_z * M_PI / 180, rate_y * M_PI / 180, tick);
862                                         }
863                                         ao_records_read++;
864                                         ao_insert();
865                                         return;
866                                 }
867                                 continue;
868                         } else if (nword == 3 && strcmp(words[0], "ms5607") == 0) {
869                                 if (strcmp(words[1], "reserved:") == 0)
870                                         ms5607_prom.reserved = strtoul(words[2], NULL, 10);
871                                 else if (strcmp(words[1], "sens:") == 0)
872                                         ms5607_prom.sens = strtoul(words[2], NULL, 10);
873                                 else if (strcmp(words[1], "off:") == 0)
874                                         ms5607_prom.off = strtoul(words[2], NULL, 10);
875                                 else if (strcmp(words[1], "tcs:") == 0)
876                                         ms5607_prom.tcs = strtoul(words[2], NULL, 10);
877                                 else if (strcmp(words[1], "tco:") == 0)
878                                         ms5607_prom.tco = strtoul(words[2], NULL, 10);
879                                 else if (strcmp(words[1], "tref:") == 0)
880                                         ms5607_prom.tref = strtoul(words[2], NULL, 10);
881                                 else if (strcmp(words[1], "tempsens:") == 0)
882                                         ms5607_prom.tempsens = strtoul(words[2], NULL, 10);
883                                 else if (strcmp(words[1], "crc:") == 0)
884                                         ms5607_prom.crc = strtoul(words[2], NULL, 10);
885                                 continue;
886                         }
887 #else
888                         if (nword == 4 && log_format != AO_LOG_FORMAT_TELEMEGA) {
889                                 type = words[0][0];
890                                 tick = strtoul(words[1], NULL, 16);
891                                 a = strtoul(words[2], NULL, 16);
892                                 b = strtoul(words[3], NULL, 16);
893                                 if (type == 'P')
894                                         type = 'A';
895                         }
896 #endif
897                         else if (nword == 2 && strcmp(words[0], "log-format") == 0) {
898                                 log_format = strtoul(words[1], NULL, 10);
899                         } else if (nword >= 6 && strcmp(words[0], "Accel") == 0) {
900                                 ao_config.accel_plus_g = atoi(words[3]);
901                                 ao_config.accel_minus_g = atoi(words[5]);
902                         } else if (nword >= 4 && strcmp(words[0], "Main") == 0) {
903                                 ao_config.main_deploy = atoi(words[2]);
904                         } else if (nword >= 3 && strcmp(words[0], "Apogee") == 0 &&
905                                    strcmp(words[1], "lockout:") == 0) {
906                                 ao_config.apogee_lockout = atoi(words[2]);
907                         } else if (nword >= 36 && strcmp(words[0], "CALL") == 0) {
908                                 tick = atoi(words[10]);
909                                 if (!ao_flight_started) {
910                                         type = 'F';
911                                         a = atoi(words[26]);
912                                         ao_flight_started = 1;
913                                 } else {
914                                         type = 'A';
915                                         a = atoi(words[12]);
916                                         b = atoi(words[14]);
917                                 }
918                         } else if (nword == 3 && strcmp(words[0], "BARO") == 0) {
919                                 tick = strtol(words[1], NULL, 16);
920                                 a = 16384 - 328;
921                                 b = strtol(words[2], NULL, 10);
922                                 type = 'A';
923                                 if (!ao_flight_started) {
924                                         ao_flight_ground_accel = 16384 - 328;
925                                         ao_config.accel_plus_g = 16384 - 328;
926                                         ao_config.accel_minus_g = 16384 + 328;
927                                         ao_flight_started = 1;
928                                 }
929                         } else if (nword == 2 && strcmp(words[0], "TELEM") == 0) {
930                                 __xdata char    *hex = words[1];
931                                 char    elt[3];
932                                 int     i, len;
933                                 uint8_t sum;
934
935                                 len = strlen(hex);
936                                 if (len > sizeof (bytes) * 2) {
937                                         len = sizeof (bytes)*2;
938                                         hex[len] = '\0';
939                                 }
940                                 for (i = 0; i < len; i += 2) {
941                                         elt[0] = hex[i];
942                                         elt[1] = hex[i+1];
943                                         elt[2] = '\0';
944                                         bytes[i/2] = (uint8_t) strtol(elt, NULL, 16);
945                                 }
946                                 len = i/2;
947                                 if (bytes[0] != len - 2) {
948                                         printf ("bad length %d != %d\n", bytes[0], len - 2);
949                                         continue;
950                                 }
951                                 sum = 0x5a;
952                                 for (i = 1; i < len-1; i++)
953                                         sum += bytes[i];
954                                 if (sum != bytes[len-1]) {
955                                         printf ("bad checksum\n");
956                                         continue;
957                                 }
958                                 if ((bytes[len-2] & 0x80) == 0) {
959                                         continue;
960                                 }
961                                 if (len == 36) {
962                                         ao_xmemcpy(&telem, bytes + 1, 32);
963                                         tick = telem.generic.tick;
964                                         switch (telem.generic.type) {
965                                         case AO_TELEMETRY_SENSOR_TELEMETRUM:
966                                         case AO_TELEMETRY_SENSOR_TELEMINI:
967                                         case AO_TELEMETRY_SENSOR_TELENANO:
968                                                 if (!ao_flight_started) {
969                                                         ao_flight_ground_accel = telem.sensor.ground_accel;
970                                                         ao_config.accel_plus_g = telem.sensor.accel_plus_g;
971                                                         ao_config.accel_minus_g = telem.sensor.accel_minus_g;
972                                                         ao_flight_started = 1;
973                                                 }
974                                                 type = 'A';
975                                                 a = telem.sensor.accel;
976                                                 b = telem.sensor.pres;
977                                                 break;
978                                         }
979                                 } else if (len == 99) {
980                                         ao_flight_started = 1;
981                                         tick = uint16(bytes+1, 21);
982                                         ao_flight_ground_accel = int16(bytes+1, 7);
983                                         ao_config.accel_plus_g = int16(bytes+1, 17);
984                                         ao_config.accel_minus_g = int16(bytes+1, 19);
985                                         type = 'A';
986                                         a = int16(bytes+1, 23);
987                                         b = int16(bytes+1, 25);
988                                 } else if (len == 98) {
989                                         ao_flight_started = 1;
990                                         tick = uint16(bytes+1, 20);
991                                         ao_flight_ground_accel = int16(bytes+1, 6);
992                                         ao_config.accel_plus_g = int16(bytes+1, 16);
993                                         ao_config.accel_minus_g = int16(bytes+1, 18);
994                                         type = 'A';
995                                         a = int16(bytes+1, 22);
996                                         b = int16(bytes+1, 24);
997                                 } else {
998                                         printf("unknown len %d\n", len);
999                                         continue;
1000                                 }
1001                         }
1002                         if (type != 'F' && !ao_flight_started)
1003                                 continue;
1004
1005 #if TELEMEGA
1006                         (void) a;
1007                         (void) b;
1008 #else
1009                         switch (type) {
1010                         case 'F':
1011                                 ao_flight_ground_accel = a;
1012                                 if (ao_config.accel_plus_g == 0) {
1013                                         ao_config.accel_plus_g = a;
1014                                         ao_config.accel_minus_g = a + 530;
1015                                 }
1016                                 if (ao_config.main_deploy == 0)
1017                                         ao_config.main_deploy = 250;
1018                                 ao_flight_started = 1;
1019                                 break;
1020                         case 'S':
1021                                 break;
1022                         case 'A':
1023                                 ao_data_static.tick = tick;
1024                                 ao_data_static.adc.accel = a;
1025                                 ao_data_static.adc.pres_real = b;
1026                                 if (b < AO_MIN_BARO_VALUE)
1027                                         b = AO_MIN_BARO_VALUE;
1028                                 ao_data_static.adc.pres = b;
1029                                 ao_records_read++;
1030                                 ao_insert();
1031                                 return;
1032                         case 'T':
1033                                 ao_data_static.tick = tick;
1034                                 ao_data_static.adc.temp = a;
1035                                 ao_data_static.adc.v_batt = b;
1036                                 break;
1037                         case 'D':
1038                         case 'G':
1039                         case 'N':
1040                         case 'W':
1041                         case 'H':
1042                                 break;
1043                         }
1044 #endif
1045                 }
1046
1047         }
1048 }
1049 #define COUNTS_PER_G 264.8
1050
1051 void
1052 ao_dump_state(void)
1053 {
1054 }
1055
1056 static const struct option options[] = {
1057         { .name = "summary", .has_arg = 0, .val = 's' },
1058         { .name = "debug", .has_arg = 0, .val = 'd' },
1059         { .name = "info", .has_arg = 1, .val = 'i' },
1060         { 0, 0, 0, 0},
1061 };
1062
1063 void run_flight_fixed(char *name, FILE *f, int summary, char *info)
1064 {
1065         emulator_name = name;
1066         emulator_in = f;
1067         emulator_info = info;
1068         ao_summary = summary;
1069         ao_flight_init();
1070         ao_flight();
1071 }
1072
1073 int
1074 main (int argc, char **argv)
1075 {
1076         int     summary = 0;
1077         int     c;
1078         int     i;
1079         char    *info = NULL;
1080
1081 #if HAS_ACCEL
1082         emulator_app="full";
1083 #else
1084         emulator_app="baro";
1085 #endif
1086         while ((c = getopt_long(argc, argv, "sdi:", options, NULL)) != -1) {
1087                 switch (c) {
1088                 case 's':
1089                         summary = 1;
1090                         break;
1091                 case 'd':
1092                         ao_flight_debug = 1;
1093                         break;
1094                 case 'i':
1095                         info = optarg;
1096                         break;
1097                 }
1098         }
1099
1100         if (optind == argc)
1101                 run_flight_fixed("<stdin>", stdin, summary, info);
1102         else
1103                 for (i = optind; i < argc; i++) {
1104                         FILE    *f = fopen(argv[i], "r");
1105                         if (!f) {
1106                                 perror(argv[i]);
1107                                 continue;
1108                         }
1109                         run_flight_fixed(argv[i], f, summary, info);
1110                         fclose(f);
1111                 }
1112         exit(0);
1113 }