altos: Make skytraq reflashing code try both 9600 and 4800 baud
[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 MEGAMETRUM
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 MEGAMETRUM
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 int ao_sample_prev_tick;
240 uint16_t        prev_tick;
241
242 #include "ao_kalman.c"
243 #include "ao_sample.c"
244 #include "ao_flight.c"
245
246 #define to_double(f)    ((f) / 65536.0)
247
248 static int      ao_records_read = 0;
249 static int      ao_eof_read = 0;
250 static int      ao_flight_ground_accel;
251 static int      ao_flight_started = 0;
252 static int      ao_test_max_height;
253 static double   ao_test_max_height_time;
254 static int      ao_test_main_height;
255 static double   ao_test_main_height_time;
256 static double   ao_test_landed_time;
257 static double   ao_test_landed_height;
258 static double   ao_test_landed_time;
259 static int      landed_set;
260 static double   landed_time;
261 static double   landed_height;
262
263 #if HAS_MPU6000
264 static struct ao_mpu6000_sample ao_ground_mpu6000;
265 #endif
266
267 void
268 ao_test_exit(void)
269 {
270         double  drogue_error;
271         double  main_error;
272         double  landed_error;
273         double  landed_time_error;
274
275         if (!ao_test_main_height_time) {
276                 ao_test_main_height_time = ao_test_max_height_time;
277                 ao_test_main_height = ao_test_max_height;
278         }
279         drogue_error = fabs(ao_test_max_height_time - drogue_time);
280         main_error = fabs(ao_test_main_height_time - main_time);
281         landed_error = fabs(ao_test_landed_height - landed_height);
282         landed_time_error = ao_test_landed_time - landed_time;
283         if (drogue_error > emulator_error_max || main_error > emulator_error_max) {
284                 printf ("%s %s\n",
285                         emulator_app, emulator_name);
286                 if (emulator_info)
287                         printf ("\t%s\n", emulator_info);
288                 printf ("\tApogee error %g\n", drogue_error);
289                 printf ("\tMain error %g\n", main_error);
290                 printf ("\tLanded height error %g\n", landed_error);
291                 printf ("\tLanded time error %g\n", landed_time_error);
292                 printf ("\tActual: apogee: %d at %7.2f main: %d at %7.2f landed %7.2f at %7.2f\n",
293                         ao_test_max_height, ao_test_max_height_time,
294                         ao_test_main_height, ao_test_main_height_time,
295                         ao_test_landed_height, ao_test_landed_time);
296                 printf ("\tComputed: apogee: %d at %7.2f main: %d at %7.2f landed %7.2f at %7.2f\n",
297                         drogue_height, drogue_time, main_height, main_time,
298                         landed_height, landed_time);
299                 exit (1);
300         }
301         exit(0);
302 }
303
304 #if HAS_MPU6000
305 static double
306 ao_mpu6000_accel(int16_t sensor)
307 {
308         return sensor / 32767.0 * MPU6000_ACCEL_FULLSCALE * GRAVITY;
309 }
310
311 static double
312 ao_mpu6000_gyro(int16_t sensor)
313 {
314         return sensor / 32767.0 * MPU6000_GYRO_FULLSCALE;
315 }
316 #endif
317
318 void
319 ao_insert(void)
320 {
321         double  time;
322
323         ao_data_ring[ao_data_head] = ao_data_static;
324         ao_data_head = ao_data_ring_next(ao_data_head);
325         if (ao_flight_state != ao_flight_startup) {
326 #if HAS_ACCEL
327                 double  accel = ((ao_flight_ground_accel - ao_data_accel_cook(&ao_data_static)) * GRAVITY * 2.0) /
328                         (ao_config.accel_minus_g - ao_config.accel_plus_g);
329 #else
330                 double  accel = 0.0;
331 #endif
332 #if MEGAMETRUM
333                 double  height;
334
335                 ao_ms5607_convert(&ao_data_static.ms5607_raw, &ao_data_static.ms5607_cooked);
336                 height = ao_pa_to_altitude(ao_data_static.ms5607_cooked.pres) - ao_ground_height;
337 #else
338                 double  height = ao_pres_to_altitude(ao_data_static.adc.pres_real) - ao_ground_height;
339 #endif
340
341                 if (!tick_offset)
342                         tick_offset = -ao_data_static.tick;
343                 if ((prev_tick - ao_data_static.tick) > 0x400)
344                         tick_offset += 65536;
345                 prev_tick = ao_data_static.tick;
346                 time = (double) (ao_data_static.tick + tick_offset) / 100;
347
348                 if (ao_test_max_height < height) {
349                         ao_test_max_height = height;
350                         ao_test_max_height_time = time;
351                         ao_test_landed_height = height;
352                         ao_test_landed_time = time;
353                 }
354                 if (height > ao_config.main_deploy) {
355                         ao_test_main_height_time = time;
356                         ao_test_main_height = height;
357                 }
358
359                 if (ao_test_landed_height > height) {
360                         ao_test_landed_height = height;
361                         ao_test_landed_time = time;
362                 }
363
364                 if (ao_flight_state == ao_flight_landed && !landed_set) {
365                         landed_set = 1;
366                         landed_time = time;
367                         landed_height = height;
368                 }
369
370                 if (!ao_summary) {
371                         printf("%7.2f height %8.2f accel %8.3f "
372 #if MEGAMETRUM
373                                "accel_x %8.3f accel_y %8.3f accel_z %8.3f gyro_x %8.3f gyro_y %8.3f gyro_z %8.3f "
374 #endif
375                                "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",
376                                time,
377                                height,
378                                accel,
379 #if MEGAMETRUM
380                                ao_mpu6000_accel(ao_data_static.mpu6000.accel_x),
381                                ao_mpu6000_accel(ao_data_static.mpu6000.accel_y),
382                                ao_mpu6000_accel(ao_data_static.mpu6000.accel_z),
383                                ao_mpu6000_gyro(ao_data_static.mpu6000.gyro_x - ao_ground_mpu6000.gyro_x),
384                                ao_mpu6000_gyro(ao_data_static.mpu6000.gyro_y - ao_ground_mpu6000.gyro_y),
385                                ao_mpu6000_gyro(ao_data_static.mpu6000.gyro_z - ao_ground_mpu6000.gyro_z),
386 #endif
387                                ao_state_names[ao_flight_state],
388                                ao_k_height / 65536.0,
389                                ao_k_speed / 65536.0 / 16.0,
390                                ao_k_accel / 65536.0 / 16.0,
391                                ao_avg_height,
392                                drogue_height,
393                                main_height,
394                                ao_error_h_sq_avg);
395                         
396 //                      if (ao_flight_state == ao_flight_landed)
397 //                              ao_test_exit();
398                 }
399         }
400 }
401
402 #define AO_MAX_CALLSIGN                 8
403 #define AO_MAX_VERSION                  8
404 #define AO_MAX_TELEMETRY                128
405
406 struct ao_telemetry_generic {
407         uint16_t        serial;         /* 0 */
408         uint16_t        tick;           /* 2 */
409         uint8_t         type;           /* 4 */
410         uint8_t         payload[27];    /* 5 */
411         /* 32 */
412 };
413
414 #define AO_TELEMETRY_SENSOR_TELEMETRUM  0x01
415 #define AO_TELEMETRY_SENSOR_TELEMINI    0x02
416 #define AO_TELEMETRY_SENSOR_TELENANO    0x03
417
418 struct ao_telemetry_sensor {
419         uint16_t        serial;         /*  0 */
420         uint16_t        tick;           /*  2 */
421         uint8_t         type;           /*  4 */
422
423         uint8_t         state;          /*  5 flight state */
424         int16_t         accel;          /*  6 accelerometer (TM only) */
425         int16_t         pres;           /*  8 pressure sensor */
426         int16_t         temp;           /* 10 temperature sensor */
427         int16_t         v_batt;         /* 12 battery voltage */
428         int16_t         sense_d;        /* 14 drogue continuity sense (TM/Tm) */
429         int16_t         sense_m;        /* 16 main continuity sense (TM/Tm) */
430
431         int16_t         acceleration;   /* 18 m/s² * 16 */
432         int16_t         speed;          /* 20 m/s * 16 */
433         int16_t         height;         /* 22 m */
434
435         int16_t         ground_pres;    /* 24 average pres on pad */
436         int16_t         ground_accel;   /* 26 average accel on pad */
437         int16_t         accel_plus_g;   /* 28 accel calibration at +1g */
438         int16_t         accel_minus_g;  /* 30 accel calibration at -1g */
439         /* 32 */
440 };
441
442 #define AO_TELEMETRY_CONFIGURATION      0x04
443
444 struct ao_telemetry_configuration {
445         uint16_t        serial;                         /*  0 */
446         uint16_t        tick;                           /*  2 */
447         uint8_t         type;                           /*  4 */
448
449         uint8_t         device;                         /*  5 device type */
450         uint16_t        flight;                         /*  6 flight number */
451         uint8_t         config_major;                   /*  8 Config major version */
452         uint8_t         config_minor;                   /*  9 Config minor version */
453         uint16_t        apogee_delay;                   /* 10 Apogee deploy delay in seconds */
454         uint16_t        main_deploy;                    /* 12 Main deploy alt in meters */
455         uint16_t        flight_log_max;                 /* 14 Maximum flight log size in kB */
456         char            callsign[AO_MAX_CALLSIGN];      /* 16 Radio operator identity */
457         char            version[AO_MAX_VERSION];        /* 24 Software version */
458         /* 32 */
459 };
460
461 #define AO_TELEMETRY_LOCATION           0x05
462
463 #define AO_GPS_MODE_NOT_VALID           'N'
464 #define AO_GPS_MODE_AUTONOMOUS          'A'
465 #define AO_GPS_MODE_DIFFERENTIAL        'D'
466 #define AO_GPS_MODE_ESTIMATED           'E'
467 #define AO_GPS_MODE_MANUAL              'M'
468 #define AO_GPS_MODE_SIMULATED           'S'
469
470 struct ao_telemetry_location {
471         uint16_t        serial;         /*  0 */
472         uint16_t        tick;           /*  2 */
473         uint8_t         type;           /*  4 */
474
475         uint8_t         flags;          /*  5 Number of sats and other flags */
476         int16_t         altitude;       /*  6 GPS reported altitude (m) */
477         int32_t         latitude;       /*  8 latitude (degrees * 10⁷) */
478         int32_t         longitude;      /* 12 longitude (degrees * 10⁷) */
479         uint8_t         year;           /* 16 (- 2000) */
480         uint8_t         month;          /* 17 (1-12) */
481         uint8_t         day;            /* 18 (1-31) */
482         uint8_t         hour;           /* 19 (0-23) */
483         uint8_t         minute;         /* 20 (0-59) */
484         uint8_t         second;         /* 21 (0-59) */
485         uint8_t         pdop;           /* 22 (m * 5) */
486         uint8_t         hdop;           /* 23 (m * 5) */
487         uint8_t         vdop;           /* 24 (m * 5) */
488         uint8_t         mode;           /* 25 */
489         uint16_t        ground_speed;   /* 26 cm/s */
490         int16_t         climb_rate;     /* 28 cm/s */
491         uint8_t         course;         /* 30 degrees / 2 */
492         uint8_t         unused[1];      /* 31 */
493         /* 32 */
494 };
495
496 #define AO_TELEMETRY_SATELLITE          0x06
497
498 struct ao_telemetry_satellite_info {
499         uint8_t         svid;
500         uint8_t         c_n_1;
501 };
502
503 struct ao_telemetry_satellite {
504         uint16_t                                serial;         /*  0 */
505         uint16_t                                tick;           /*  2 */
506         uint8_t                                 type;           /*  4 */
507         uint8_t                                 channels;       /*  5 number of reported sats */
508
509         struct ao_telemetry_satellite_info      sats[12];       /* 6 */
510         uint8_t                                 unused[2];      /* 30 */
511         /* 32 */
512 };
513
514 union ao_telemetry_all {
515         struct ao_telemetry_generic             generic;
516         struct ao_telemetry_sensor              sensor;
517         struct ao_telemetry_configuration       configuration;
518         struct ao_telemetry_location            location;
519         struct ao_telemetry_satellite           satellite;
520 };
521
522 uint16_t
523 uint16(uint8_t *bytes, int off)
524 {
525         return (uint16_t) bytes[off] | (((uint16_t) bytes[off+1]) << 8);
526 }
527
528 int16_t
529 int16(uint8_t *bytes, int off)
530 {
531         return (int16_t) uint16(bytes, off);
532 }
533
534 uint32_t
535 uint32(uint8_t *bytes, int off)
536 {
537         return (uint32_t) bytes[off] | (((uint32_t) bytes[off+1]) << 8) |
538                 (((uint32_t) bytes[off+2]) << 16) |
539                 (((uint32_t) bytes[off+3]) << 24);
540 }
541
542 int32_t
543 int32(uint8_t *bytes, int off)
544 {
545         return (int32_t) uint32(bytes, off);
546 }
547
548 static int log_format;
549
550 #if MEGAMETRUM
551
552 static double
553 ao_vec_norm(double x, double y, double z)
554 {
555         return x*x + y*y + z*z;
556 }
557
558 static void
559 ao_vec_normalize(double *x, double *y, double *z)
560 {
561         double  scale = 1/sqrt(ao_vec_norm(*x, *y, *z));
562
563         *x *= scale;
564         *y *= scale;
565         *z *= scale;
566 }
567
568 struct ao_quat {
569         double  q0, q1, q2, q3;
570 };
571
572 static void
573 ao_quat_mul(struct ao_quat *r, struct ao_quat *a, struct ao_quat *b)
574 {
575         r->q0 = a->q0 * b->q0 - a->q1 * b->q1 - a->q2 * b->q2 - a->q3 * b->q3;
576         r->q1 = a->q0 * b->q1 + a->q1 * b->q0 + a->q2 * b->q3 - a->q3 * b->q2;
577         r->q2 = a->q0 * b->q2 - a->q1 * b->q3 + a->q2 * b->q0 + a->q3 * b->q1;
578         r->q3 = a->q0 * b->q3 + a->q1 * b->q2 - a->q2 * b->q1 + a->q3 * b->q0;
579 }
580
581 #if 0
582 static void
583 ao_quat_scale(struct ao_quat *r, struct ao_quat *a, double s)
584 {
585         r->q0 = a->q0 * s;
586         r->q1 = a->q1 * s;
587         r->q2 = a->q2 * s;
588         r->q3 = a->q3 * s;
589 }
590 #endif
591
592 static void
593 ao_quat_conj(struct ao_quat *r, struct ao_quat *a)
594 {
595         r->q0 =  a->q0;
596         r->q1 = -a->q1;
597         r->q2 = -a->q2;
598         r->q3 = -a->q3;
599 }
600
601 static void
602 ao_quat_rot(struct ao_quat *r, struct ao_quat *a, struct ao_quat *q)
603 {
604         struct ao_quat  t;
605         struct ao_quat  c;
606         ao_quat_mul(&t, q, a);
607         ao_quat_conj(&c, q);
608         ao_quat_mul(r, &t, &c);
609 }
610
611 static void
612 ao_quat_from_angle(struct ao_quat *r,
613                    double x_rad,
614                    double y_rad,
615                    double z_rad)
616 {
617         double angle = sqrt (x_rad * x_rad + y_rad * y_rad + z_rad * z_rad);
618         double s = sin(angle/2);
619         double c = cos(angle/2);
620
621         r->q0 = c;
622         r->q1 = x_rad * s / angle;
623         r->q2 = y_rad * s / angle;
624         r->q3 = z_rad * s / angle;
625 }
626
627 static void
628 ao_quat_from_vector(struct ao_quat *r, double x, double y, double z)
629 {
630         ao_vec_normalize(&x, &y, &z);
631         double  x_rad = atan2(z, y);
632         double  y_rad = atan2(x, z);
633         double  z_rad = atan2(y, x);
634
635         ao_quat_from_angle(r, x_rad, y_rad, z_rad);
636 }
637
638 static double
639 ao_quat_norm(struct ao_quat *a)
640 {
641         return (a->q0 * a->q0 +
642                 a->q1 * a->q1 +
643                 a->q2 * a->q2 +
644                 a->q3 * a->q3);
645 }
646
647 static void
648 ao_quat_normalize(struct ao_quat *a)
649 {
650         double  norm = ao_quat_norm(a);
651
652         if (norm) {
653                 double m = 1/sqrt(norm);
654
655                 a->q0 *= m;
656                 a->q1 *= m;
657                 a->q2 *= m;
658                 a->q3 *= m;
659         }
660 }
661
662 static struct ao_quat   ao_up, ao_current;
663 static struct ao_quat   ao_orient;
664 static int              ao_orient_tick;
665
666 void
667 set_orientation(double x, double y, double z, int tick)
668 {
669         struct ao_quat  t;
670
671         printf ("set_orientation %g %g %g\n", x, y, z);
672         ao_quat_from_vector(&ao_orient, x, y, z);
673         ao_up.q1 = ao_up.q2 = 0;
674         ao_up.q0 = ao_up.q3 = sqrt(2)/2;
675         ao_orient_tick = tick;
676
677         ao_orient.q0 = 1;
678         ao_orient.q1 = 0;
679         ao_orient.q2 = 0;
680         ao_orient.q3 = 0;
681
682         printf ("orient (%g) %g %g %g up (%g) %g %g %g\n",
683                 ao_orient.q0,
684                 ao_orient.q1,
685                 ao_orient.q2,
686                 ao_orient.q3,
687                 ao_up.q0,
688                 ao_up.q1,
689                 ao_up.q2,
690                 ao_up.q3);
691
692         ao_quat_rot(&t, &ao_up, &ao_orient);
693         printf ("pad orient (%g) %g %g %g\n",
694                 t.q0,
695                 t.q1,
696                 t.q2,
697                 t.q3);
698
699 }
700
701 void
702 update_orientation (double rate_x, double rate_y, double rate_z, int tick)
703 {
704         struct ao_quat  q_dot;
705         double          lambda;
706         double          dt = (tick - ao_orient_tick) / 100.0;
707
708         ao_orient_tick = tick;
709  
710 //      lambda = 1 - ao_quat_norm(&ao_orient);
711         lambda = 0;
712
713         q_dot.q0 = -0.5 * (ao_orient.q1 * rate_x + ao_orient.q2 * rate_y + ao_orient.q3 * rate_z) + lambda * ao_orient.q0;
714         q_dot.q1 =  0.5 * (ao_orient.q0 * rate_x + ao_orient.q2 * rate_z - ao_orient.q3 * rate_y) + lambda * ao_orient.q1;
715         q_dot.q2 =  0.5 * (ao_orient.q0 * rate_y + ao_orient.q3 * rate_x - ao_orient.q1 * rate_z) + lambda * ao_orient.q2;
716         q_dot.q3 =  0.5 * (ao_orient.q0 * rate_z + ao_orient.q1 * rate_y - ao_orient.q2 * rate_x) + lambda * ao_orient.q3;
717
718         printf ("update_orientation %g %g %g (%g s)\n", rate_x, rate_y, rate_z, dt);
719         printf ("q_dot (%g) %g %g %g\n",
720                 q_dot.q0,
721                 q_dot.q1,
722                 q_dot.q2,
723                 q_dot.q3);
724
725         ao_orient.q0 += q_dot.q0 * dt;
726         ao_orient.q1 += q_dot.q1 * dt;
727         ao_orient.q2 += q_dot.q2 * dt;
728         ao_orient.q3 += q_dot.q3 * dt;
729
730         ao_quat_normalize(&ao_orient);
731
732         ao_quat_rot(&ao_current, &ao_up, &ao_orient);
733
734         printf ("orient (%g) %g %g %g current (%g) %g %g %g\n",
735                 ao_orient.q0,
736                 ao_orient.q1,
737                 ao_orient.q2,
738                 ao_orient.q3,
739                 ao_current.q0,
740                 ao_current.q1,
741                 ao_current.q2,
742                 ao_current.q3);
743 }
744 #endif
745
746 void
747 ao_sleep(void *wchan)
748 {
749         if (wchan == &ao_data_head) {
750                 char            type = 0;
751                 uint16_t        tick = 0;
752                 uint16_t        a = 0, b = 0;
753                 uint8_t         bytes[1024];
754                 union ao_telemetry_all  telem;
755                 char            line[1024];
756                 char            *saveptr;
757                 char            *l;
758                 char            *words[64];
759                 int             nword;
760
761                 for (;;) {
762                         if (ao_records_read > 2 && ao_flight_state == ao_flight_startup)
763                         {
764 #if MEGAMETRUM
765                                 ao_data_static.mpu6000 = ao_ground_mpu6000;
766 #else
767                                 ao_data_static.adc.accel = ao_flight_ground_accel;
768 #endif
769                                 ao_insert();
770                                 return;
771                         }
772
773                         if (!fgets(line, sizeof (line), emulator_in)) {
774                                 if (++ao_eof_read >= 1000) {
775                                         if (!ao_summary)
776                                                 printf ("no more data, exiting simulation\n");
777                                         ao_test_exit();
778                                 }
779                                 ao_data_static.tick += 10;
780                                 ao_insert();
781                                 return;
782                         }
783                         l = line;
784                         for (nword = 0; nword < 64; nword++) {
785                                 words[nword] = strtok_r(l, " \t\n", &saveptr);
786                                 l = NULL;
787                                 if (words[nword] == NULL)
788                                         break;
789                         }
790 #if MEGAMETRUM
791                         if (log_format == AO_LOG_FORMAT_MEGAMETRUM && nword == 30 && strlen(words[0]) == 1) {
792                                 int     i;
793                                 struct ao_ms5607_value  value;
794
795                                 type = words[0][0];
796                                 tick = strtoul(words[1], NULL, 16);
797 //                              printf ("%c %04x", type, tick);
798                                 for (i = 2; i < nword; i++) {
799                                         bytes[i - 2] = strtoul(words[i], NULL, 16);
800 //                                      printf(" %02x", bytes[i-2]);
801                                 }
802 //                              printf ("\n");
803                                 switch (type) {
804                                 case 'F':
805                                         ao_flight_ground_accel = int16(bytes, 2);
806                                         ao_flight_started = 1;
807                                         ao_ground_pres = int32(bytes, 4);
808                                         ao_ground_height = ao_pa_to_altitude(ao_ground_pres);
809                                         break;
810                                 case 'A':
811                                         ao_data_static.tick = tick;
812                                         ao_data_static.ms5607_raw.pres = int32(bytes, 0);
813                                         ao_data_static.ms5607_raw.temp = int32(bytes, 4);
814                                         ao_ms5607_convert(&ao_data_static.ms5607_raw, &value);
815                                         ao_data_static.mpu6000.accel_x = int16(bytes, 8);
816                                         ao_data_static.mpu6000.accel_y = -int16(bytes, 10);
817                                         ao_data_static.mpu6000.accel_z = int16(bytes, 12);
818                                         ao_data_static.mpu6000.gyro_x = int16(bytes, 14);
819                                         ao_data_static.mpu6000.gyro_y = -int16(bytes, 16);
820                                         ao_data_static.mpu6000.gyro_z = int16(bytes, 18);
821 #if HAS_MMA655X
822                                         ao_data_static.mma655x = int16(bytes, 26);
823 #endif
824                                         if (ao_records_read == 0)
825                                                 ao_ground_mpu6000 = ao_data_static.mpu6000;
826                                         else if (ao_records_read < 10) {
827 #define f(f) ao_ground_mpu6000.f = ao_ground_mpu6000.f + ((ao_data_static.mpu6000.f - ao_ground_mpu6000.f) >> 2)
828                                                 f(accel_x);
829                                                 f(accel_y);
830                                                 f(accel_z);
831                                                 f(gyro_x);
832                                                 f(gyro_y);
833                                                 f(gyro_z);
834
835                                                 double          accel_x = ao_mpu6000_accel(ao_ground_mpu6000.accel_x);
836                                                 double          accel_y = ao_mpu6000_accel(ao_ground_mpu6000.accel_y);
837                                                 double          accel_z = ao_mpu6000_accel(ao_ground_mpu6000.accel_z);
838
839                                                 /* X and Y are in the ground plane, arbitraryily picked as MPU X and Z axes
840                                                  * Z is normal to the ground, the MPU y axis
841                                                  */
842                                                 set_orientation(accel_x, accel_z, accel_y, tick);
843                                         } else {
844                                                 double          rate_x = ao_mpu6000_gyro(ao_data_static.mpu6000.gyro_x - ao_ground_mpu6000.gyro_x);
845                                                 double          rate_y = ao_mpu6000_gyro(ao_data_static.mpu6000.gyro_y - ao_ground_mpu6000.gyro_y);
846                                                 double          rate_z = ao_mpu6000_gyro(ao_data_static.mpu6000.gyro_z - ao_ground_mpu6000.gyro_z);
847
848                                                 update_orientation(rate_x, rate_z, rate_y, tick);
849                                         }
850                                         ao_records_read++;
851                                         ao_insert();
852                                         return;
853                                 }
854                                 continue;
855                         } else if (nword == 3 && strcmp(words[0], "ms5607") == 0) {
856                                 if (strcmp(words[1], "reserved:") == 0)
857                                         ms5607_prom.reserved = strtoul(words[2], NULL, 10);
858                                 else if (strcmp(words[1], "sens:") == 0)
859                                         ms5607_prom.sens = strtoul(words[2], NULL, 10);
860                                 else if (strcmp(words[1], "off:") == 0)
861                                         ms5607_prom.off = strtoul(words[2], NULL, 10);
862                                 else if (strcmp(words[1], "tcs:") == 0)
863                                         ms5607_prom.tcs = strtoul(words[2], NULL, 10);
864                                 else if (strcmp(words[1], "tco:") == 0)
865                                         ms5607_prom.tco = strtoul(words[2], NULL, 10);
866                                 else if (strcmp(words[1], "tref:") == 0)
867                                         ms5607_prom.tref = strtoul(words[2], NULL, 10);
868                                 else if (strcmp(words[1], "tempsens:") == 0)
869                                         ms5607_prom.tempsens = strtoul(words[2], NULL, 10);
870                                 else if (strcmp(words[1], "crc:") == 0)
871                                         ms5607_prom.crc = strtoul(words[2], NULL, 10);
872                                 continue;
873                         }
874 #else
875                         if (nword == 4 && log_format != AO_LOG_FORMAT_MEGAMETRUM) {
876                                 type = words[0][0];
877                                 tick = strtoul(words[1], NULL, 16);
878                                 a = strtoul(words[2], NULL, 16);
879                                 b = strtoul(words[3], NULL, 16);
880                                 if (type == 'P')
881                                         type = 'A';
882                         }
883 #endif
884                         else if (nword == 2 && strcmp(words[0], "log-format") == 0) {
885                                 log_format = strtoul(words[1], NULL, 10);
886                         } else if (nword >= 6 && strcmp(words[0], "Accel") == 0) {
887                                 ao_config.accel_plus_g = atoi(words[3]);
888                                 ao_config.accel_minus_g = atoi(words[5]);
889                         } else if (nword >= 4 && strcmp(words[0], "Main") == 0) {
890                                 ao_config.main_deploy = atoi(words[2]);
891                         } else if (nword >= 3 && strcmp(words[0], "Apogee") == 0 &&
892                                    strcmp(words[1], "lockout:") == 0) {
893                                 ao_config.apogee_lockout = atoi(words[2]);
894                         } else if (nword >= 36 && strcmp(words[0], "CALL") == 0) {
895                                 tick = atoi(words[10]);
896                                 if (!ao_flight_started) {
897                                         type = 'F';
898                                         a = atoi(words[26]);
899                                         ao_flight_started = 1;
900                                 } else {
901                                         type = 'A';
902                                         a = atoi(words[12]);
903                                         b = atoi(words[14]);
904                                 }
905                         } else if (nword == 3 && strcmp(words[0], "BARO") == 0) {
906                                 tick = strtol(words[1], NULL, 16);
907                                 a = 16384 - 328;
908                                 b = strtol(words[2], NULL, 10);
909                                 type = 'A';
910                                 if (!ao_flight_started) {
911                                         ao_flight_ground_accel = 16384 - 328;
912                                         ao_config.accel_plus_g = 16384 - 328;
913                                         ao_config.accel_minus_g = 16384 + 328;
914                                         ao_flight_started = 1;
915                                 }
916                         } else if (nword == 2 && strcmp(words[0], "TELEM") == 0) {
917                                 __xdata char    *hex = words[1];
918                                 char    elt[3];
919                                 int     i, len;
920                                 uint8_t sum;
921
922                                 len = strlen(hex);
923                                 if (len > sizeof (bytes) * 2) {
924                                         len = sizeof (bytes)*2;
925                                         hex[len] = '\0';
926                                 }
927                                 for (i = 0; i < len; i += 2) {
928                                         elt[0] = hex[i];
929                                         elt[1] = hex[i+1];
930                                         elt[2] = '\0';
931                                         bytes[i/2] = (uint8_t) strtol(elt, NULL, 16);
932                                 }
933                                 len = i/2;
934                                 if (bytes[0] != len - 2) {
935                                         printf ("bad length %d != %d\n", bytes[0], len - 2);
936                                         continue;
937                                 }
938                                 sum = 0x5a;
939                                 for (i = 1; i < len-1; i++)
940                                         sum += bytes[i];
941                                 if (sum != bytes[len-1]) {
942                                         printf ("bad checksum\n");
943                                         continue;
944                                 }
945                                 if ((bytes[len-2] & 0x80) == 0) {
946                                         continue;
947                                 }
948                                 if (len == 36) {
949                                         ao_xmemcpy(&telem, bytes + 1, 32);
950                                         tick = telem.generic.tick;
951                                         switch (telem.generic.type) {
952                                         case AO_TELEMETRY_SENSOR_TELEMETRUM:
953                                         case AO_TELEMETRY_SENSOR_TELEMINI:
954                                         case AO_TELEMETRY_SENSOR_TELENANO:
955                                                 if (!ao_flight_started) {
956                                                         ao_flight_ground_accel = telem.sensor.ground_accel;
957                                                         ao_config.accel_plus_g = telem.sensor.accel_plus_g;
958                                                         ao_config.accel_minus_g = telem.sensor.accel_minus_g;
959                                                         ao_flight_started = 1;
960                                                 }
961                                                 type = 'A';
962                                                 a = telem.sensor.accel;
963                                                 b = telem.sensor.pres;
964                                                 break;
965                                         }
966                                 } else if (len == 99) {
967                                         ao_flight_started = 1;
968                                         tick = uint16(bytes+1, 21);
969                                         ao_flight_ground_accel = int16(bytes+1, 7);
970                                         ao_config.accel_plus_g = int16(bytes+1, 17);
971                                         ao_config.accel_minus_g = int16(bytes+1, 19);
972                                         type = 'A';
973                                         a = int16(bytes+1, 23);
974                                         b = int16(bytes+1, 25);
975                                 } else if (len == 98) {
976                                         ao_flight_started = 1;
977                                         tick = uint16(bytes+1, 20);
978                                         ao_flight_ground_accel = int16(bytes+1, 6);
979                                         ao_config.accel_plus_g = int16(bytes+1, 16);
980                                         ao_config.accel_minus_g = int16(bytes+1, 18);
981                                         type = 'A';
982                                         a = int16(bytes+1, 22);
983                                         b = int16(bytes+1, 24);
984                                 } else {
985                                         printf("unknown len %d\n", len);
986                                         continue;
987                                 }
988                         }
989                         if (type != 'F' && !ao_flight_started)
990                                 continue;
991
992 #if MEGAMETRUM
993                         (void) a;
994                         (void) b;
995 #else
996                         switch (type) {
997                         case 'F':
998                                 ao_flight_ground_accel = a;
999                                 if (ao_config.accel_plus_g == 0) {
1000                                         ao_config.accel_plus_g = a;
1001                                         ao_config.accel_minus_g = a + 530;
1002                                 }
1003                                 if (ao_config.main_deploy == 0)
1004                                         ao_config.main_deploy = 250;
1005                                 ao_flight_started = 1;
1006                                 break;
1007                         case 'S':
1008                                 break;
1009                         case 'A':
1010                                 ao_data_static.tick = tick;
1011                                 ao_data_static.adc.accel = a;
1012                                 ao_data_static.adc.pres_real = b;
1013                                 if (b < AO_MIN_BARO_VALUE)
1014                                         b = AO_MIN_BARO_VALUE;
1015                                 ao_data_static.adc.pres = b;
1016                                 ao_records_read++;
1017                                 ao_insert();
1018                                 return;
1019                         case 'T':
1020                                 ao_data_static.tick = tick;
1021                                 ao_data_static.adc.temp = a;
1022                                 ao_data_static.adc.v_batt = b;
1023                                 break;
1024                         case 'D':
1025                         case 'G':
1026                         case 'N':
1027                         case 'W':
1028                         case 'H':
1029                                 break;
1030                         }
1031 #endif
1032                 }
1033
1034         }
1035 }
1036 #define COUNTS_PER_G 264.8
1037
1038 void
1039 ao_dump_state(void)
1040 {
1041 }
1042
1043 static const struct option options[] = {
1044         { .name = "summary", .has_arg = 0, .val = 's' },
1045         { .name = "debug", .has_arg = 0, .val = 'd' },
1046         { .name = "info", .has_arg = 1, .val = 'i' },
1047         { 0, 0, 0, 0},
1048 };
1049
1050 void run_flight_fixed(char *name, FILE *f, int summary, char *info)
1051 {
1052         emulator_name = name;
1053         emulator_in = f;
1054         emulator_info = info;
1055         ao_summary = summary;
1056         ao_flight_init();
1057         ao_flight();
1058 }
1059
1060 int
1061 main (int argc, char **argv)
1062 {
1063         int     summary = 0;
1064         int     c;
1065         int     i;
1066         char    *info = NULL;
1067
1068 #if HAS_ACCEL
1069         emulator_app="full";
1070 #else
1071         emulator_app="baro";
1072 #endif
1073         while ((c = getopt_long(argc, argv, "sdi:", options, NULL)) != -1) {
1074                 switch (c) {
1075                 case 's':
1076                         summary = 1;
1077                         break;
1078                 case 'd':
1079                         ao_flight_debug = 1;
1080                         break;
1081                 case 'i':
1082                         info = optarg;
1083                         break;
1084                 }
1085         }
1086
1087         if (optind == argc)
1088                 run_flight_fixed("<stdin>", stdin, summary, info);
1089         else
1090                 for (i = optind; i < argc; i++) {
1091                         FILE    *f = fopen(argv[i], "r");
1092                         if (!f) {
1093                                 perror(argv[i]);
1094                                 continue;
1095                         }
1096                         run_flight_fixed(argv[i], f, summary, info);
1097                         fclose(f);
1098                 }
1099         exit(0);
1100 }