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