altos: Add ability to read new TELEM files to ao_flight_test
[fw/altos] / src / 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 AO_ADC_RING     64
30 #define ao_adc_ring_next(n)     (((n) + 1) & (AO_ADC_RING - 1))
31 #define ao_adc_ring_prev(n)     (((n) - 1) & (AO_ADC_RING - 1))
32
33 #define AO_M_TO_HEIGHT(m)       ((int16_t) (m))
34 #define AO_MS_TO_SPEED(ms)      ((int16_t) ((ms) * 16))
35 #define AO_MSS_TO_ACCEL(mss)    ((int16_t) ((mss) * 16))
36
37 /*
38  * One set of samples read from the A/D converter
39  */
40 struct ao_adc {
41         uint16_t        tick;           /* tick when the sample was read */
42         int16_t         accel;          /* accelerometer */
43         int16_t         pres;           /* pressure sensor */
44         int16_t         pres_real;      /* unclipped */
45         int16_t         temp;           /* temperature sensor */
46         int16_t         v_batt;         /* battery voltage */
47         int16_t         sense_d;        /* drogue continuity sense */
48         int16_t         sense_m;        /* main continuity sense */
49 };
50
51 #define __pdata
52 #define __data
53 #define __xdata
54 #define __code
55 #define __reentrant
56
57 #define to_fix16(x) ((int16_t) ((x) * 65536.0 + 0.5))
58 #define to_fix32(x) ((int32_t) ((x) * 65536.0 + 0.5))
59 #define from_fix(x)     ((x) >> 16)
60
61 /*
62  * Above this height, the baro sensor doesn't work
63  */
64 #define AO_MAX_BARO_HEIGHT      12000
65 #define AO_BARO_SATURATE        13000
66 #define AO_MIN_BARO_VALUE       ao_altitude_to_pres(AO_BARO_SATURATE)
67
68 /*
69  * Above this speed, baro measurements are unreliable
70  */
71 #define AO_MAX_BARO_SPEED       200
72
73 #define ACCEL_NOSE_UP   (ao_accel_2g >> 2)
74
75 enum ao_flight_state {
76         ao_flight_startup = 0,
77         ao_flight_idle = 1,
78         ao_flight_pad = 2,
79         ao_flight_boost = 3,
80         ao_flight_fast = 4,
81         ao_flight_coast = 5,
82         ao_flight_drogue = 6,
83         ao_flight_main = 7,
84         ao_flight_landed = 8,
85         ao_flight_invalid = 9
86 };
87
88 extern enum ao_flight_state ao_flight_state;
89
90 #define FALSE 0
91 #define TRUE 1
92
93 struct ao_adc ao_adc_ring[AO_ADC_RING];
94 uint8_t ao_adc_head;
95 int     ao_summary = 0;
96
97 #define ao_led_on(l)
98 #define ao_led_off(l)
99 #define ao_timer_set_adc_interval(i)
100 #define ao_wakeup(wchan) ao_dump_state()
101 #define ao_cmd_register(c)
102 #define ao_usb_disable()
103 #define ao_telemetry_set_interval(x)
104 #define ao_rdf_set(rdf)
105 #define ao_packet_slave_start()
106 #define ao_packet_slave_stop()
107
108 enum ao_igniter {
109         ao_igniter_drogue = 0,
110         ao_igniter_main = 1
111 };
112
113 struct ao_adc ao_adc_static;
114
115 int     drogue_height;
116 double  drogue_time;
117 int     main_height;
118 double  main_time;
119
120 int     tick_offset;
121
122 static int32_t  ao_k_height;
123
124 void
125 ao_ignite(enum ao_igniter igniter)
126 {
127         double time = (double) (ao_adc_static.tick + tick_offset) / 100;
128
129         if (igniter == ao_igniter_drogue) {
130                 drogue_time = time;
131                 drogue_height = ao_k_height >> 16;
132         } else {
133                 main_time = time;
134                 main_height = ao_k_height >> 16;
135         }
136 }
137
138 struct ao_task {
139         int dummy;
140 };
141
142 #define ao_add_task(t,f,n)
143
144 #define ao_log_start()
145 #define ao_log_stop()
146
147 #define AO_MS_TO_TICKS(ms)      ((ms) / 10)
148 #define AO_SEC_TO_TICKS(s)      ((s) * 100)
149
150 #define AO_FLIGHT_TEST
151
152 int     ao_flight_debug;
153
154 FILE *emulator_in;
155 char *emulator_app;
156 char *emulator_name;
157 double emulator_error_max = 4;
158
159 void
160 ao_dump_state(void);
161
162 void
163 ao_sleep(void *wchan);
164
165 const char const * const ao_state_names[] = {
166         "startup", "idle", "pad", "boost", "fast",
167         "coast", "drogue", "main", "landed", "invalid"
168 };
169
170 struct ao_cmds {
171         void            (*func)(void);
172         const char      *help;
173 };
174
175 #include "ao_convert.c"
176
177 struct ao_config {
178         uint16_t        main_deploy;
179         int16_t         accel_plus_g;
180         int16_t         accel_minus_g;
181 };
182
183 #define ao_config_get()
184
185 struct ao_config ao_config;
186
187 #define DATA_TO_XDATA(x) (x)
188
189 #define HAS_FLIGHT 1
190 #define HAS_ADC 1
191 #define HAS_USB 1
192 #define HAS_GPS 1
193 #ifndef HAS_ACCEL
194 #define HAS_ACCEL 1
195 #define HAS_ACCEL_REF 0
196 #endif
197
198 #define GRAVITY 9.80665
199 extern int16_t ao_ground_accel, ao_flight_accel;
200 extern int16_t ao_accel_2g;
201
202 extern uint16_t ao_sample_tick;
203
204 extern int16_t  ao_sample_height;
205 extern int16_t  ao_sample_accel;
206 extern int32_t  ao_accel_scale;
207 extern int16_t  ao_ground_height;
208 extern int16_t  ao_sample_alt;
209
210 int ao_sample_prev_tick;
211 uint16_t        prev_tick;
212
213 #include "ao_kalman.c"
214 #include "ao_sample.c"
215 #include "ao_flight.c"
216
217 #define to_double(f)    ((f) / 65536.0)
218
219 static int      ao_records_read = 0;
220 static int      ao_eof_read = 0;
221 static int      ao_flight_ground_accel;
222 static int      ao_flight_started = 0;
223 static int      ao_test_max_height;
224 static double   ao_test_max_height_time;
225 static int      ao_test_main_height;
226 static double   ao_test_main_height_time;
227
228 void
229 ao_test_exit(void)
230 {
231         double  drogue_error;
232         double  main_error;
233
234         if (!ao_test_main_height_time) {
235                 ao_test_main_height_time = ao_test_max_height_time;
236                 ao_test_main_height = ao_test_max_height;
237         }
238         drogue_error = fabs(ao_test_max_height_time - drogue_time);
239         main_error = fabs(ao_test_main_height_time - main_time);
240         if (drogue_error > emulator_error_max || main_error > emulator_error_max) {
241                 printf ("%s %s\n",
242                         emulator_app, emulator_name);
243                 printf ("\tApogee error %g\n", drogue_error);
244                 printf ("\tMain error %g\n", main_error);
245                 printf ("\tActual: apogee: %d at %7.2f main: %d at %7.2f\n",
246                         ao_test_max_height, ao_test_max_height_time,
247                         ao_test_main_height, ao_test_main_height_time);
248                 printf ("\tComputed: apogee: %d at %7.2f main: %d at %7.2f\n",
249                         drogue_height, drogue_time, main_height, main_time);
250                 exit (1);
251         }
252         exit(0);
253 }
254
255 void
256 ao_insert(void)
257 {
258         double  time;
259
260         ao_adc_ring[ao_adc_head] = ao_adc_static;
261         ao_adc_head = ao_adc_ring_next(ao_adc_head);
262         if (ao_flight_state != ao_flight_startup) {
263                 double  height = ao_pres_to_altitude(ao_adc_static.pres_real) - ao_ground_height;
264                 double  accel = ((ao_flight_ground_accel - ao_adc_static.accel) * GRAVITY * 2.0) /
265                         (ao_config.accel_minus_g - ao_config.accel_plus_g);
266
267                 if (!tick_offset)
268                         tick_offset = -ao_adc_static.tick;
269                 if ((prev_tick - ao_adc_static.tick) > 0x400)
270                         tick_offset += 65536;
271                 prev_tick = ao_adc_static.tick;
272                 time = (double) (ao_adc_static.tick + tick_offset) / 100;
273
274                 if (ao_test_max_height < height) {
275                         ao_test_max_height = height;
276                         ao_test_max_height_time = time;
277                 }
278                 if (height > ao_config.main_deploy) {
279                         ao_test_main_height_time = time;
280                         ao_test_main_height = height;
281                 }
282
283                 if (!ao_summary) {
284                         printf("%7.2f height %g accel %g state %s k_height %g k_speed %g k_accel %g drogue %d main %d error %d\n",
285                                time,
286                                height,
287                                accel,
288                                ao_state_names[ao_flight_state],
289                                ao_k_height / 65536.0,
290                                ao_k_speed / 65536.0 / 16.0,
291                                ao_k_accel / 65536.0 / 16.0,
292                                drogue_height,
293                                main_height,
294                                ao_error_h_sq_avg);
295                         if (ao_flight_state == ao_flight_landed)
296                                 ao_test_exit();
297                 }
298         }
299 }
300
301 #define AO_MAX_CALLSIGN                 8
302 #define AO_MAX_VERSION                  8
303 #define AO_MAX_TELEMETRY                128
304
305 struct ao_telemetry_generic {
306         uint16_t        serial;         /* 0 */
307         uint16_t        tick;           /* 2 */
308         uint8_t         type;           /* 4 */
309         uint8_t         payload[27];    /* 5 */
310         /* 32 */
311 };
312
313 #define AO_TELEMETRY_SENSOR_TELEMETRUM  0x01
314 #define AO_TELEMETRY_SENSOR_TELEMINI    0x02
315 #define AO_TELEMETRY_SENSOR_TELENANO    0x03
316
317 struct ao_telemetry_sensor {
318         uint16_t        serial;         /*  0 */
319         uint16_t        tick;           /*  2 */
320         uint8_t         type;           /*  4 */
321
322         uint8_t         state;          /*  5 flight state */
323         int16_t         accel;          /*  6 accelerometer (TM only) */
324         int16_t         pres;           /*  8 pressure sensor */
325         int16_t         temp;           /* 10 temperature sensor */
326         int16_t         v_batt;         /* 12 battery voltage */
327         int16_t         sense_d;        /* 14 drogue continuity sense (TM/Tm) */
328         int16_t         sense_m;        /* 16 main continuity sense (TM/Tm) */
329
330         int16_t         acceleration;   /* 18 m/s² * 16 */
331         int16_t         speed;          /* 20 m/s * 16 */
332         int16_t         height;         /* 22 m */
333
334         int16_t         ground_pres;    /* 24 average pres on pad */
335         int16_t         ground_accel;   /* 26 average accel on pad */
336         int16_t         accel_plus_g;   /* 28 accel calibration at +1g */
337         int16_t         accel_minus_g;  /* 30 accel calibration at -1g */
338         /* 32 */
339 };
340
341 #define AO_TELEMETRY_CONFIGURATION      0x04
342
343 struct ao_telemetry_configuration {
344         uint16_t        serial;                         /*  0 */
345         uint16_t        tick;                           /*  2 */
346         uint8_t         type;                           /*  4 */
347
348         uint8_t         device;                         /*  5 device type */
349         uint16_t        flight;                         /*  6 flight number */
350         uint8_t         config_major;                   /*  8 Config major version */
351         uint8_t         config_minor;                   /*  9 Config minor version */
352         uint16_t        apogee_delay;                   /* 10 Apogee deploy delay in seconds */
353         uint16_t        main_deploy;                    /* 12 Main deploy alt in meters */
354         uint16_t        flight_log_max;                 /* 14 Maximum flight log size in kB */
355         char            callsign[AO_MAX_CALLSIGN];      /* 16 Radio operator identity */
356         char            version[AO_MAX_VERSION];        /* 24 Software version */
357         /* 32 */
358 };
359
360 #define AO_TELEMETRY_LOCATION           0x05
361
362 #define AO_GPS_MODE_NOT_VALID           'N'
363 #define AO_GPS_MODE_AUTONOMOUS          'A'
364 #define AO_GPS_MODE_DIFFERENTIAL        'D'
365 #define AO_GPS_MODE_ESTIMATED           'E'
366 #define AO_GPS_MODE_MANUAL              'M'
367 #define AO_GPS_MODE_SIMULATED           'S'
368
369 struct ao_telemetry_location {
370         uint16_t        serial;         /*  0 */
371         uint16_t        tick;           /*  2 */
372         uint8_t         type;           /*  4 */
373
374         uint8_t         flags;          /*  5 Number of sats and other flags */
375         int16_t         altitude;       /*  6 GPS reported altitude (m) */
376         int32_t         latitude;       /*  8 latitude (degrees * 10⁷) */
377         int32_t         longitude;      /* 12 longitude (degrees * 10⁷) */
378         uint8_t         year;           /* 16 (- 2000) */
379         uint8_t         month;          /* 17 (1-12) */
380         uint8_t         day;            /* 18 (1-31) */
381         uint8_t         hour;           /* 19 (0-23) */
382         uint8_t         minute;         /* 20 (0-59) */
383         uint8_t         second;         /* 21 (0-59) */
384         uint8_t         pdop;           /* 22 (m * 5) */
385         uint8_t         hdop;           /* 23 (m * 5) */
386         uint8_t         vdop;           /* 24 (m * 5) */
387         uint8_t         mode;           /* 25 */
388         uint16_t        ground_speed;   /* 26 cm/s */
389         int16_t         climb_rate;     /* 28 cm/s */
390         uint8_t         course;         /* 30 degrees / 2 */
391         uint8_t         unused[1];      /* 31 */
392         /* 32 */
393 };
394
395 #define AO_TELEMETRY_SATELLITE          0x06
396
397 struct ao_telemetry_satellite_info {
398         uint8_t         svid;
399         uint8_t         c_n_1;
400 };
401
402 struct ao_telemetry_satellite {
403         uint16_t                                serial;         /*  0 */
404         uint16_t                                tick;           /*  2 */
405         uint8_t                                 type;           /*  4 */
406         uint8_t                                 channels;       /*  5 number of reported sats */
407
408         struct ao_telemetry_satellite_info      sats[12];       /* 6 */
409         uint8_t                                 unused[2];      /* 30 */
410         /* 32 */
411 };
412
413 union ao_telemetry_all {
414         struct ao_telemetry_generic             generic;
415         struct ao_telemetry_sensor              sensor;
416         struct ao_telemetry_configuration       configuration;
417         struct ao_telemetry_location            location;
418         struct ao_telemetry_satellite           satellite;
419 };
420
421 uint16_t
422 uint16(uint8_t *bytes, int off)
423 {
424         off++;
425         return (uint16_t) bytes[off] | (((uint16_t) bytes[off+1]) << 8);
426 }
427
428 int16_t
429 int16(uint8_t *bytes, int off)
430 {
431         return (int16_t) uint16(bytes, off);
432 }
433
434 void
435 ao_sleep(void *wchan)
436 {
437         if (wchan == &ao_adc_head) {
438                 char            type;
439                 uint16_t        tick;
440                 uint16_t        a, b;
441                 int             ret;
442                 uint8_t         bytes[1024];
443                 union ao_telemetry_all  telem;
444                 char            line[1024];
445                 char            *saveptr;
446                 char            *l;
447                 char            *words[64];
448                 int             nword;
449
450                 for (;;) {
451                         if (ao_records_read > 2 && ao_flight_state == ao_flight_startup)
452                         {
453                                 ao_adc_static.accel = ao_flight_ground_accel;
454                                 ao_insert();
455                                 return;
456                         }
457
458                         if (!fgets(line, sizeof (line), emulator_in)) {
459                                 if (++ao_eof_read >= 1000) {
460                                         if (!ao_summary)
461                                                 printf ("no more data, exiting simulation\n");
462                                         ao_test_exit();
463                                 }
464                                 ao_adc_static.tick += 10;
465                                 ao_insert();
466                                 return;
467                         }
468                         l = line;
469                         for (nword = 0; nword < 64; nword++) {
470                                 words[nword] = strtok_r(l, " \t\n", &saveptr);
471                                 l = NULL;
472                                 if (words[nword] == NULL)
473                                         break;
474                         }
475                         if (nword == 4) {
476                                 type = words[0][0];
477                                 tick = strtoul(words[1], NULL, 16);
478                                 a = strtoul(words[2], NULL, 16);
479                                 b = strtoul(words[3], NULL, 16);
480                                 if (type == 'P')
481                                         type = 'A';
482                         } else if (nword >= 6 && strcmp(words[0], "Accel") == 0) {
483                                 ao_config.accel_plus_g = atoi(words[3]);
484                                 ao_config.accel_minus_g = atoi(words[5]);
485                         } else if (nword >= 4 && strcmp(words[0], "Main") == 0) {
486                                 ao_config.main_deploy = atoi(words[2]);
487                         } else if (nword >= 36 && strcmp(words[0], "CALL") == 0) {
488                                 tick = atoi(words[10]);
489                                 if (!ao_flight_started) {
490                                         type = 'F';
491                                         a = atoi(words[26]);
492                                         ao_flight_started = 1;
493                                 } else {
494                                         type = 'A';
495                                         a = atoi(words[12]);
496                                         b = atoi(words[14]);
497                                 }
498                         } else if (nword == 2 && strcmp(words[0], "TELEM") == 0) {
499                                 char    *hex = words[1];
500                                 char    elt[3];
501                                 int     i, len;
502                                 uint8_t sum;
503
504                                 len = strlen(hex);
505                                 if (len > sizeof (bytes) * 2) {
506                                         len = sizeof (bytes)*2;
507                                         hex[len] = '\0';
508                                 }
509                                 for (i = 0; i < len; i += 2) {
510                                         elt[0] = hex[i];
511                                         elt[1] = hex[i+1];
512                                         elt[2] = '\0';
513                                         bytes[i/2] = (uint8_t) strtol(elt, NULL, 16);
514                                 }
515                                 len = i/2;
516                                 if (bytes[0] != len - 2) {
517                                         printf ("bad length %d != %d\n", bytes[0], len - 2);
518                                         continue;
519                                 }
520                                 sum = 0x5a;
521                                 for (i = 1; i < len-1; i++)
522                                         sum += bytes[i];
523                                 if (sum != bytes[len-1]) {
524                                         printf ("bad checksum\n");
525                                         continue;
526                                 }
527                                 if ((bytes[len-2] & 0x80) == 0) {
528                                         continue;
529                                 }
530                                 if (len == 36) {
531                                         memcpy(&telem, bytes + 1, 32);
532                                         tick = telem.generic.tick;
533                                         switch (telem.generic.type) {
534                                         case AO_TELEMETRY_SENSOR_TELEMETRUM:
535                                         case AO_TELEMETRY_SENSOR_TELEMINI:
536                                         case AO_TELEMETRY_SENSOR_TELENANO:
537                                                 if (!ao_flight_started) {
538                                                         ao_flight_ground_accel = telem.sensor.ground_accel;
539                                                         ao_config.accel_plus_g = telem.sensor.accel_plus_g;
540                                                         ao_config.accel_minus_g = telem.sensor.accel_minus_g;
541                                                         ao_flight_started = 1;
542                                                 }
543                                                 type = 'A';
544                                                 a = telem.sensor.accel;
545                                                 b = telem.sensor.pres;
546                                                 break;
547                                         }
548                                 } else if (len == 99) {
549                                         ao_flight_started = 1;
550                                         tick = uint16(bytes, 21);
551                                         ao_flight_ground_accel = int16(bytes, 7);
552                                         ao_config.accel_plus_g = int16(bytes, 17);
553                                         ao_config.accel_minus_g = int16(bytes, 19);
554                                         type = 'A';
555                                         a = int16(bytes, 23);
556                                         b = int16(bytes, 25);
557                                 } else if (len == 98) {
558                                         ao_flight_started = 1;
559                                         tick = uint16(bytes, 20);
560                                         ao_flight_ground_accel = int16(bytes, 6);
561                                         ao_config.accel_plus_g = int16(bytes, 16);
562                                         ao_config.accel_minus_g = int16(bytes, 18);
563                                         type = 'A';
564                                         a = int16(bytes, 22);
565                                         b = int16(bytes, 24);
566                                 } else {
567                                         printf("unknown len %d\n", len);
568                                         continue;
569                                 }
570                         }
571                         if (type != 'F' && !ao_flight_started)
572                                 continue;
573
574                         switch (type) {
575                         case 'F':
576                                 ao_flight_ground_accel = a;
577                                 if (ao_config.accel_plus_g == 0) {
578                                         ao_config.accel_plus_g = a;
579                                         ao_config.accel_minus_g = a + 530;
580                                 }
581                                 if (ao_config.main_deploy == 0)
582                                         ao_config.main_deploy = 250;
583                                 ao_flight_started = 1;
584                                 break;
585                         case 'S':
586                                 break;
587                         case 'A':
588                                 ao_adc_static.tick = tick;
589                                 ao_adc_static.accel = a;
590                                 ao_adc_static.pres_real = b;
591                                 if (b < AO_MIN_BARO_VALUE)
592                                         b = AO_MIN_BARO_VALUE;
593                                 ao_adc_static.pres = b;
594                                 ao_records_read++;
595                                 ao_insert();
596                                 return;
597                         case 'T':
598                                 ao_adc_static.tick = tick;
599                                 ao_adc_static.temp = a;
600                                 ao_adc_static.v_batt = b;
601                                 break;
602                         case 'D':
603                         case 'G':
604                         case 'N':
605                         case 'W':
606                         case 'H':
607                                 break;
608                         }
609                 }
610
611         }
612 }
613 #define COUNTS_PER_G 264.8
614
615 void
616 ao_dump_state(void)
617 {
618 }
619
620 static const struct option options[] = {
621         { .name = "summary", .has_arg = 0, .val = 's' },
622         { .name = "debug", .has_arg = 0, .val = 'd' },
623         { 0, 0, 0, 0},
624 };
625
626 void run_flight_fixed(char *name, FILE *f, int summary)
627 {
628         emulator_name = name;
629         emulator_in = f;
630         ao_summary = summary;
631         ao_flight_init();
632         ao_flight();
633 }
634
635 int
636 main (int argc, char **argv)
637 {
638         int     summary = 0;
639         int     c;
640         int     i;
641
642 #if HAS_ACCEL
643         emulator_app="full";
644 #else
645         emulator_app="baro";
646 #endif
647         while ((c = getopt_long(argc, argv, "sd", options, NULL)) != -1) {
648                 switch (c) {
649                 case 's':
650                         summary = 1;
651                         break;
652                 case 'd':
653                         ao_flight_debug = 1;
654                         break;
655                 }
656         }
657
658         if (optind == argc)
659                 run_flight_fixed("<stdin>", stdin, summary);
660         else
661                 for (i = optind; i < argc; i++) {
662                         FILE    *f = fopen(argv[i], "r");
663                         if (!f) {
664                                 perror(argv[i]);
665                                 continue;
666                         }
667                         run_flight_fixed(argv[i], f, summary);
668                         fclose(f);
669                 }
670 }