]> git.mxchange.org Git - flightgear.git/blob - utils/GPSsmooth/UGear_main.cxx
considering u,v,wbody-fps are the ECEF velocity expressed in body axis, change in...
[flightgear.git] / utils / GPSsmooth / UGear_main.cxx
1 #ifdef HAVE_CONFIG_H
2 #  include <config.h>
3 #endif
4
5 #ifdef HAVE_WINDOWS_H
6 #  include <windows.h>
7 #else
8 #  include <netinet/in.h>       // htonl() ntohl()
9 #endif
10
11 #ifndef _WIN32
12 #  include <strings.h>          // for bzero()
13 #else
14 #  define bzero(a,b) memset(a,0,b)
15 #endif
16 #include <iostream>
17 #include <string>
18
19 #include <plib/sg.h>
20
21 #include <simgear/constants.h>
22 #include <simgear/io/lowlevel.hxx> // endian tests
23 #include <simgear/io/sg_file.hxx>
24 #include <simgear/io/raw_socket.hxx>
25 #include <simgear/serial/serial.hxx>
26 #include <simgear/math/sg_geodesy.hxx>
27 #include <simgear/timing/timestamp.hxx>
28
29 #include <Network/net_ctrls.hxx>
30 #include <Network/net_fdm.hxx>
31
32 #include "UGear.hxx"
33 #include "UGear_command.hxx"
34 #include "UGear_opengc.hxx"
35 #include "UGear_telnet.hxx"
36
37
38 using std::cout;
39 using std::endl;
40 using std::string;
41
42
43 // Network channels
44 static simgear::Socket fdm_sock, ctrls_sock, opengc_sock;
45
46 // ugear data
47 UGTrack track;
48
49 // Default ports
50 static int fdm_port = 5505;
51 static int ctrls_port = 5506;
52 static int opengc_port = 6000;
53
54 // Default path
55 static string infile = "";
56 static string flight_dir = "";
57 static string serialdev = "";
58 static string outfile = "";
59
60 // Master time counter
61 float sim_time = 0.0f;
62 double frame_us = 0.0f;
63
64 // sim control
65 SGTimeStamp last_time_stamp;
66 SGTimeStamp current_time_stamp;
67
68 // altitude offset
69 double alt_offset = 0.0;
70
71 // skip initial seconds
72 double skip = 0.0;
73
74 // for speed estimate
75 double last_lat = 0.0, last_lon = 0.0;
76 double kts_filter = 0.0;
77
78 bool inited = false;
79
80 bool run_real_time = true;
81
82 bool ignore_checksum = false;
83
84 bool sg_swap = false;
85
86 bool use_ground_track_hdg = false;
87 bool use_ground_speed = false;
88
89 bool est_controls = false;
90
91 float gps_status = -1.0;
92
93
94 // The function htond is defined this way due to the way some
95 // processors and OSes treat floating point values.  Some will raise
96 // an exception whenever a "bad" floating point value is loaded into a
97 // floating point register.  Solaris is notorious for this, but then
98 // so is LynxOS on the PowerPC.  By translating the data in place,
99 // there is no need to load a FP register with the "corruped" floating
100 // point value.  By doing the BIG_ENDIAN test, I can optimize the
101 // routine for big-endian processors so it can be as efficient as
102 // possible
103 static void htond (double &x)
104 {
105     if ( sgIsLittleEndian() ) {
106         int    *Double_Overlay;
107         int     Holding_Buffer;
108
109         Double_Overlay = (int *) &x;
110         Holding_Buffer = Double_Overlay [0];
111
112         Double_Overlay [0] = htonl (Double_Overlay [1]);
113         Double_Overlay [1] = htonl (Holding_Buffer);
114     } else {
115         return;
116     }
117 }
118
119 // Float version
120 static void htonf (float &x)
121 {
122     if ( sgIsLittleEndian() ) {
123         int    *Float_Overlay;
124         int     Holding_Buffer;
125
126         Float_Overlay = (int *) &x;
127         Holding_Buffer = Float_Overlay [0];
128
129         Float_Overlay [0] = htonl (Holding_Buffer);
130     } else {
131         return;
132     }
133 }
134
135
136 static void ugear2fg( gps *gpspacket, imu *imupacket, nav *navpacket,
137                       servo *servopacket, health *healthpacket,
138                       FGNetFDM *fdm, FGNetCtrls *ctrls )
139 {
140     unsigned int i;
141
142     // Version sanity checking
143     fdm->version = FG_NET_FDM_VERSION;
144
145     // Aero parameters
146     fdm->longitude = navpacket->lon * SG_DEGREES_TO_RADIANS;
147     fdm->latitude = navpacket->lat * SG_DEGREES_TO_RADIANS;
148     fdm->altitude = navpacket->alt + alt_offset;
149     fdm->agl = -9999.0;
150     fdm->psi = imupacket->psi; // heading
151     fdm->phi = imupacket->phi; // roll
152     fdm->theta = imupacket->the; // pitch;
153
154     fdm->phidot = 0.0;
155     fdm->thetadot = 0.0;
156     fdm->psidot = 0.0;
157
158     // estimate speed
159     // double az1, az2, dist;
160     // geo_inverse_wgs_84( fdm->altitude, last_lat, last_lon,
161     //                     fdm->latitude, fdm->longitude, &az1, &az2, &dist );
162     // last_lat = fdm->latitude;
163     // last_lon = fdm->longitude;
164     // double v_ms = dist / (frame_us / 1000000);
165     // double v_kts = v_ms * SG_METER_TO_NM * 3600;
166     // kts_filter = (0.9 * kts_filter) + (0.1 * v_kts);
167     // printf("dist = %.5f  kts est = %.2f\n", dist, kts_filter);
168
169     double vn = navpacket->vn;
170     double ve = navpacket->ve;
171     double vd = navpacket->vd;
172
173     if ( use_ground_track_hdg ) {
174         fdm->psi = SGD_PI * 0.5 - atan2(vn, ve); // heading
175     }
176
177     double mps = 0.0;
178     if ( use_ground_speed ) {
179         mps = sqrt( vn*vn + ve*ve + vd*vd );
180     } else {
181         mps = imupacket->Pt;
182     }
183     // double mph = mps * 3600 / 1609.3440;
184     double kts = mps * SG_MPS_TO_KT;
185     fdm->vcas = kts;
186     // printf("speed = %.2f mph  %.2f kts\n", mph, kts );
187     static double Ps = 0.0, Ps_last = 0.0, t_last = 0.0;
188     Ps_last = Ps;
189     Ps = 0.92 * Ps + 0.08 * imupacket->Ps;
190     double climb = (Ps - Ps_last) / (imupacket->time - t_last);
191     t_last = imupacket->time;
192     static double climbf = 0.0;
193     climbf = 0.994 * climbf + 0.006 * climb;
194     fdm->climb_rate = climbf; // fps
195
196     static double Ps_error = 0.0;
197     static double Ps_count = 0;
198     const double span = 10000.0;
199     Ps_count += 1.0; if (Ps_count > (span-1.0)) { Ps_count = (span-1.0); }
200     double error = navpacket->alt - Ps;
201     Ps_error = (Ps_count/span) * Ps_error + ((span-Ps_count)/span) * error;
202     fdm->altitude = Ps +  Ps_error;
203
204     /* printf("%.3f, %.3f, %.3f, %.3f, %.8f, %.8f, %.3f, %.3f, %.3f, %.3f, %.3f\n",
205            imupacket->time, imupacket->the, -navpacket->vd, climbf,
206            navpacket->lat, navpacket->lon, gpspacket->alt, navpacket->alt,
207            imupacket->Ps, Ps, Ps + Ps_error); */
208
209     // cout << "climb rate = " << aero->hdota << endl;
210     fdm->v_north = 0.0;
211     fdm->v_east = 0.0;
212     fdm->v_down = 0.0;
213     fdm->v_body_u = 0.0;
214     fdm->v_body_v = 0.0;
215     fdm->v_body_w = 0.0;
216     fdm->stall_warning = 0.0;
217
218     fdm->A_X_pilot = 0.0;
219     fdm->A_Y_pilot = 0.0;
220     fdm->A_Z_pilot = 0.0 /* (should be -G) */;
221
222     // Engine parameters
223     fdm->num_engines = 1;
224     fdm->eng_state[0] = 2;
225     // cout << "state = " << fdm->eng_state[0] << endl;
226     double rpm = 5000.0 - ((double)servopacket->chn[2] / 65536.0)*3500.0;
227     if ( rpm < 0.0 ) { rpm = 0.0; }
228     if ( rpm > 5000.0 ) { rpm = 5000.0; }
229     fdm->rpm[0] = rpm;
230
231     fdm->fuel_flow[0] = 0.0;
232     fdm->egt[0] = 0.0;
233     // cout << "egt = " << aero->EGT << endl;
234     fdm->oil_temp[0] = 0.0;
235     fdm->oil_px[0] = 0.0;
236
237     // Consumables
238     fdm->num_tanks = 2;
239     fdm->fuel_quantity[0] = 0.0;
240     fdm->fuel_quantity[1] = 0.0;
241
242     // Gear and flaps
243     fdm->num_wheels = 3;
244     fdm->wow[0] = 0;
245     fdm->wow[1] = 0;
246     fdm->wow[2] = 0;
247
248     // the following really aren't used in this context
249     fdm->cur_time = 0;
250     fdm->warp = 0;
251     fdm->visibility = 0;
252
253     // cout << "Flap deflection = " << aero->dflap << endl;
254     fdm->left_flap = 0.0;
255     fdm->right_flap = 0.0;
256
257     if ( est_controls ) {
258         static float est_elev = 0.0;
259         static float est_aileron = 0.0;
260         static float est_rudder = 0.0;
261         est_elev = 0.99 * est_elev + 0.01 * (imupacket->q * 4);
262         est_aileron = 0.95 * est_aileron + 0.05 * (imupacket->p * 5);
263         est_rudder = 0.95 * est_rudder + 0.05 * (imupacket->r * 2);
264         ctrls->elevator = fdm->elevator = -est_elev;
265         ctrls->aileron = fdm->left_aileron = est_aileron;
266         fdm->right_aileron = -est_aileron;
267         ctrls->rudder = fdm->rudder = est_rudder;
268     } else {
269         ctrls->elevator = fdm->elevator = 1.0 - ((double)servopacket->chn[1] / 32768.0);
270         ctrls->aileron = fdm->left_aileron = 1.0 - ((double)servopacket->chn[0] / 32768.0);
271         fdm->right_aileron = ((double)servopacket->chn[0] / 32768.0) - 1.0;
272         ctrls->rudder = fdm->rudder = 1.0 - ((double)servopacket->chn[3] / 32768.0);
273         ctrls->elevator *= 3.0;
274         ctrls->aileron *= 3.0;
275     }
276     fdm->elevator_trim_tab = 0.0;
277     fdm->left_flap = 0.0;
278     fdm->right_flap = 0.0;
279     fdm->nose_wheel = 0.0;
280     fdm->speedbrake = 0.0;
281     fdm->spoilers = 0.0;
282
283     // Convert the net buffer to network format
284     fdm->version = htonl(fdm->version);
285
286     htond(fdm->longitude);
287     htond(fdm->latitude);
288     htond(fdm->altitude);
289     htonf(fdm->agl);
290     htonf(fdm->phi);
291     htonf(fdm->theta);
292     htonf(fdm->psi);
293     htonf(fdm->alpha);
294     htonf(fdm->beta);
295
296     htonf(fdm->phidot);
297     htonf(fdm->thetadot);
298     htonf(fdm->psidot);
299     htonf(fdm->vcas);
300     htonf(fdm->climb_rate);
301     htonf(fdm->v_north);
302     htonf(fdm->v_east);
303     htonf(fdm->v_down);
304     htonf(fdm->v_body_u);
305     htonf(fdm->v_body_v);
306     htonf(fdm->v_body_w);
307
308     htonf(fdm->A_X_pilot);
309     htonf(fdm->A_Y_pilot);
310     htonf(fdm->A_Z_pilot);
311
312     htonf(fdm->stall_warning);
313     htonf(fdm->slip_deg);
314
315     for ( i = 0; i < fdm->num_engines; ++i ) {
316         fdm->eng_state[i] = htonl(fdm->eng_state[i]);
317         htonf(fdm->rpm[i]);
318         htonf(fdm->fuel_flow[i]);
319         htonf(fdm->egt[i]);
320         htonf(fdm->cht[i]);
321         htonf(fdm->mp_osi[i]);
322         htonf(fdm->tit[i]);
323         htonf(fdm->oil_temp[i]);
324         htonf(fdm->oil_px[i]);
325     }
326     fdm->num_engines = htonl(fdm->num_engines);
327
328     for ( i = 0; i < fdm->num_tanks; ++i ) {
329         htonf(fdm->fuel_quantity[i]);
330     }
331     fdm->num_tanks = htonl(fdm->num_tanks);
332
333     for ( i = 0; i < fdm->num_wheels; ++i ) {
334         fdm->wow[i] = htonl(fdm->wow[i]);
335         htonf(fdm->gear_pos[i]);
336         htonf(fdm->gear_steer[i]);
337         htonf(fdm->gear_compression[i]);
338     }
339     fdm->num_wheels = htonl(fdm->num_wheels);
340
341     fdm->cur_time = htonl( fdm->cur_time );
342     fdm->warp = htonl( fdm->warp );
343     htonf(fdm->visibility);
344
345     htonf(fdm->elevator);
346     htonf(fdm->elevator_trim_tab);
347     htonf(fdm->left_flap);
348     htonf(fdm->right_flap);
349     htonf(fdm->left_aileron);
350     htonf(fdm->right_aileron);
351     htonf(fdm->rudder);
352     htonf(fdm->nose_wheel);
353     htonf(fdm->speedbrake);
354     htonf(fdm->spoilers);
355
356 #if 0
357     ctrls->version = FG_NET_CTRLS_VERSION;
358     ctrls->elevator_trim = 0.0;
359     ctrls->flaps = 0.0;
360
361     htonl(ctrls->version);
362     htond(ctrls->aileron);
363     htond(ctrls->rudder);
364     htond(ctrls->elevator);
365     htond(ctrls->elevator_trim);
366     htond(ctrls->flaps);
367 #endif
368 }
369
370
371 static void ugear2opengc( gps *gpspacket, imu *imupacket, nav *navpacket,
372                           servo *servopacket, health *healthpacket,
373                           ogcFGData *ogc )
374 {
375     // Version sanity checking
376     ogc->version_id = OGC_VERSION;
377
378     // Aero parameters
379     ogc->longitude = navpacket->lon;
380     ogc->latitude = navpacket->lat;
381     ogc->heading = imupacket->psi * SG_RADIANS_TO_DEGREES; // heading
382     ogc->bank = imupacket->phi * SG_RADIANS_TO_DEGREES; // roll
383     ogc->pitch = imupacket->the * SG_RADIANS_TO_DEGREES; // pitch;
384
385     ogc->phi_dot = 0.0;
386     ogc->theta_dot = 0.0;
387     ogc->psi_dot = 0.0;
388
389     ogc->alpha = 0.0;
390     ogc->beta = 0.0;
391     ogc->alpha_dot = 0.0;
392     ogc->beta_dot = 0.0;
393
394     ogc->left_aileron = 1.0 - ((double)servopacket->chn[0] / 32768.0);
395     ogc->right_aileron = ((double)servopacket->chn[0] / 32768.0) - 1.0;
396     ogc->elevator = 1.0 - ((double)servopacket->chn[1] / 32768.0);
397     ogc->elevator_trim = 0.0;
398     ogc->rudder = 1.0 - ((double)servopacket->chn[3] / 32768.0);
399     ogc->flaps = 0.0;
400     ogc->flaps_cmd = 0.0;
401
402     ogc->wind = 0.0;
403     ogc->wind_dir = 0.0;
404
405     // estimate speed
406     // double az1, az2, dist;
407     // geo_inverse_wgs_84( fdm->altitude, last_lat, last_lon,
408     //                     fdm->latitude, fdm->longitude, &az1, &az2, &dist );
409     // last_lat = fdm->latitude;
410     // last_lon = fdm->longitude;
411     // double v_ms = dist / (frame_us / 1000000);
412     // double v_kts = v_ms * SG_METER_TO_NM * 3600;
413     // kts_filter = (0.9 * kts_filter) + (0.1 * v_kts);
414     // printf("dist = %.5f  kts est = %.2f\n", dist, kts_filter);
415
416     double vn = navpacket->vn;
417     double ve = navpacket->ve;
418     double vd = navpacket->vd;
419
420     if ( use_ground_track_hdg ) {
421         ogc->heading = (SGD_PI * 0.5 - atan2(vn, ve)) * SG_RADIANS_TO_DEGREES;
422     }
423
424     if ( ogc->heading < 0 ) { ogc->heading += 360.0; }
425
426     double mps = 0.0;
427     if ( use_ground_speed ) {
428         mps = sqrt( vn*vn + ve*ve + vd*vd );
429     } else {
430         mps = imupacket->Pt;
431     }
432     // double mph = mps * 3600 / 1609.3440;
433     double kts = mps * SG_MPS_TO_KT;
434     ogc->v_kcas = kts;
435     // printf("speed = %.2f mph  %.2f kts\n", mph, kts );
436     static double Ps = 0.0, Ps_last = 0.0, t_last = 0.0;
437     Ps_last = Ps;
438     Ps = 0.92 * Ps + 0.08 * imupacket->Ps;
439     double climb = (Ps - Ps_last) / (imupacket->time - t_last);
440     t_last = imupacket->time;
441     static double climbf = 0.0;
442     climbf = 0.994 * climbf + 0.006 * climb;
443     ogc->vvi = climbf; // fps
444
445     // uncomment one of the following schemes for setting elevation:
446
447     // use the navigation (inertially augmented gps estimate)
448     // ogc->altitude = ogc->elevation
449     //     = (navpacket->alt + alt_offset * SG_METER_TO_FEET);
450
451     // use estimate error between pressure sensor and gps altitude over time
452     // use pressure sensor + error average for altitude estimate.
453     static double Ps_error = 0.0;
454     static double Ps_count = 0;
455     const double span = 10000.0;
456     Ps_count += 1.0; if (Ps_count > (span-1.0)) { Ps_count = (span-1.0); }
457     double error = navpacket->alt - Ps;
458     Ps_error = (Ps_count/span) * Ps_error + ((span-Ps_count)/span) * error;
459     ogc->elevation = (Ps +  Ps_error) * SG_METER_TO_FEET;
460
461     /* printf("%.3f, %.3f, %.3f, %.3f, %.8f, %.8f, %.3f, %.3f, %.3f, %.3f, %.3f\n",
462            imupacket->time, imupacket->the, -navpacket->vd, climbf,
463            navpacket->lat, navpacket->lon, gpspacket->alt, navpacket->alt,
464            imupacket->Ps, Ps, Ps + Ps_error); */
465
466     if ( est_controls ) {
467         static float est_elev = 0.0;
468         static float est_aileron = 0.0;
469         static float est_rudder = 0.0;
470         est_elev = 0.99 * est_elev + 0.01 * (imupacket->q * 4);
471         est_aileron = 0.95 * est_aileron + 0.05 * (imupacket->p * 5);
472         est_rudder = 0.95 * est_rudder + 0.05 * (imupacket->r * 2);
473         ogc->elevator = -est_elev;
474         ogc->left_aileron = est_aileron;
475         ogc->right_aileron = -est_aileron;
476         ogc->rudder = est_rudder;
477     } else {
478         ogc->elevator = 1.0 - ((double)servopacket->chn[1] / 32768.0);
479         ogc->left_aileron = 1.0 - ((double)servopacket->chn[0] / 32768.0);
480         ogc->right_aileron = ((double)servopacket->chn[0] / 32768.0) - 1.0;
481         ogc->rudder = 1.0 - ((double)servopacket->chn[3] / 32768.0);
482     }
483     ogc->elevator *= 4.0;
484     ogc->left_aileron *= 4.0;
485     ogc->right_aileron *= 4.0;
486     ogc->rudder *= 4.0;
487
488     // additional "abused" data fields
489     ogc->egt[0] = ogc->bank - healthpacket->target_roll_deg; // flight director target roll
490     ogc->egt[1] = -ogc->pitch + healthpacket->target_pitch_deg; // flight director target pitch
491     ogc->egt[2] = healthpacket->target_heading_deg; // target heading bug
492     ogc->egt[3] = healthpacket->target_climb_fps;   // target VVI bug
493     ogc->epr[0] = healthpacket->target_altitude_ft; // target altitude bug
494     ogc->epr[1] = 30.0;                              // target speed bug
495     ogc->epr[2] = gps_status;   // gps status box
496 }
497
498
499 static void send_data_udp( gps *gpspacket, imu *imupacket, nav *navpacket,
500                            servo *servopacket, health *healthpacket )
501 {
502     int ogcsize = sizeof( ogcFGData );
503     int fdmsize = sizeof( FGNetFDM );
504     // int ctrlsize = sizeof( FGNetCtrls );
505
506     // cout << "Running main loop" << endl;
507
508     ogcFGData fgogc;
509     FGNetFDM fgfdm;
510     FGNetCtrls fgctrls;
511
512     ugear2fg( gpspacket, imupacket, navpacket, servopacket, healthpacket,
513               &fgfdm, &fgctrls );
514     ugear2opengc( gpspacket, imupacket, navpacket, servopacket, healthpacket,
515                   &fgogc );
516     opengc_sock.send(&fgogc, ogcsize, 0);
517     fdm_sock.send(&fgfdm, fdmsize, 0);
518     // len = ctrls_sock.send(&fgctrls, ctrlsize, 0);
519 }
520
521
522 void usage( const string &argv0 ) {
523     cout << "Usage: " << argv0 << endl;
524     cout << "\t[ --help ]" << endl;
525     cout << "\t[ --infile <infile_name>" << endl;
526     cout << "\t[ --flight <flight_dir>" << endl;
527     cout << "\t[ --serial <dev_name>" << endl;
528     cout << "\t[ --outfile <outfile_name> (capture the data to a file)" << endl;
529     cout << "\t[ --hertz <hertz> ]" << endl;
530     cout << "\t[ --host <hostname> ]" << endl;
531     cout << "\t[ --broadcast ]" << endl;
532     cout << "\t[ --opengc-port <opengc output port #> ]" << endl;
533     cout << "\t[ --fdm-port <fdm output port #> ]" << endl;
534     cout << "\t[ --ctrls-port <ctrls output port #> ]" << endl;
535     cout << "\t[ --groundtrack-heading ]" << endl;
536     cout << "\t[ --ground-speed ]" << endl;
537     cout << "\t[ --estimate-control-deflections ]" << endl;
538     cout << "\t[ --altitude-offset <meters> ]" << endl;
539     cout << "\t[ --skip-seconds <seconds> ]" << endl;
540     cout << "\t[ --no-real-time ]" << endl;
541     cout << "\t[ --ignore-checksum ]" << endl;
542     cout << "\t[ --sg-swap ]" << endl;
543 }
544
545
546 int main( int argc, char **argv ) {
547     double hertz = 60.0;
548     string out_host = "localhost";
549     bool do_broadcast = false;
550
551     // process command line arguments
552     for ( int i = 1; i < argc; ++i ) {
553         if ( strcmp( argv[i], "--help" ) == 0 ) {
554             usage( argv[0] );
555             exit( 0 );
556         } else if ( strcmp( argv[i], "--hertz" ) == 0 ) {
557             ++i;
558             if ( i < argc ) {
559                 hertz = atof( argv[i] );
560             } else {
561                 usage( argv[0] );
562                 exit( -1 );
563             }
564         } else if ( strcmp( argv[i], "--infile" ) == 0 ) {
565             ++i;
566             if ( i < argc ) {
567                 infile = argv[i];
568             } else {
569                 usage( argv[0] );
570                 exit( -1 );
571             }
572         } else if ( strcmp( argv[i], "--flight" ) == 0 ) {
573             ++i;
574             if ( i < argc ) {
575                 flight_dir = argv[i];
576             } else {
577                 usage( argv[0] );
578                 exit( -1 );
579             }
580         } else if ( strcmp( argv[i], "--outfile" ) == 0 ) {
581             ++i;
582             if ( i < argc ) {
583                 outfile = argv[i];
584             } else {
585                 usage( argv[0] );
586                 exit( -1 );
587             }
588         } else if ( strcmp( argv[i], "--serial" ) == 0 ) {
589             ++i;
590             if ( i < argc ) {
591                 serialdev = argv[i];
592             } else {
593                 usage( argv[0] );
594                 exit( -1 );
595             }
596         } else if ( strcmp( argv[i], "--host" ) == 0 ) {
597             ++i;
598             if ( i < argc ) {
599                 out_host = argv[i];
600             } else {
601                 usage( argv[0] );
602                 exit( -1 );
603             }
604         } else if ( strcmp( argv[i], "--broadcast" ) == 0 ) {
605           do_broadcast = true;
606         } else if ( strcmp( argv[i], "--opengc-port" ) == 0 ) {
607             ++i;
608             if ( i < argc ) {
609                 opengc_port = atoi( argv[i] );
610             } else {
611                 usage( argv[0] );
612                 exit( -1 );
613             }
614         } else if ( strcmp( argv[i], "--fdm-port" ) == 0 ) {
615             ++i;
616             if ( i < argc ) {
617                 fdm_port = atoi( argv[i] );
618             } else {
619                 usage( argv[0] );
620                 exit( -1 );
621             }
622         } else if ( strcmp( argv[i], "--ctrls-port" ) == 0 ) {
623             ++i;
624             if ( i < argc ) {
625                 ctrls_port = atoi( argv[i] );
626             } else {
627                 usage( argv[0] );
628                 exit( -1 );
629             }
630         } else if ( strcmp (argv[i], "--groundtrack-heading" ) == 0 ) {
631             use_ground_track_hdg = true;
632         } else if ( strcmp (argv[i], "--ground-speed" ) == 0 ) {
633             use_ground_speed = true;
634         } else if (strcmp (argv[i], "--estimate-control-deflections" ) == 0) {
635             est_controls = true;
636         } else if ( strcmp( argv[i], "--altitude-offset" ) == 0 ) {
637             ++i;
638             if ( i < argc ) {
639                 alt_offset = atof( argv[i] );
640             } else {
641                 usage( argv[0] );
642                 exit( -1 );
643             }
644         } else if ( strcmp( argv[i], "--skip-seconds" ) == 0 ) {
645             ++i;
646             if ( i < argc ) {
647                 skip = atof( argv[i] );
648             } else {
649                 usage( argv[0] );
650                 exit( -1 );
651             }
652         } else if ( strcmp( argv[i], "--no-real-time" ) == 0 ) {
653             run_real_time = false;
654         } else if ( strcmp( argv[i], "--ignore-checksum" ) == 0 ) {
655             ignore_checksum = true;
656         } else if ( strcmp( argv[i], "--sg-swap" ) == 0 ) {
657             sg_swap = true;
658         } else {
659             usage( argv[0] );
660             exit( -1 );
661         }
662     }
663
664     // Setup up outgoing network connections
665
666     simgear::Socket::initSockets(); // We must call this before any other net stuff
667
668     if ( ! opengc_sock.open( false ) ) {  // open a UDP socket
669         cout << "error opening opengc output socket" << endl;
670         return -1;
671     }
672     if ( ! fdm_sock.open( false ) ) {  // open a UDP socket
673         cout << "error opening fdm output socket" << endl;
674         return -1;
675     }
676     if ( ! ctrls_sock.open( false ) ) {  // open a UDP socket
677         cout << "error opening ctrls output socket" << endl;
678         return -1;
679     }
680     cout << "open net channels" << endl;
681
682     opengc_sock.setBlocking( false );
683     fdm_sock.setBlocking( false );
684     ctrls_sock.setBlocking( false );
685     cout << "blocking false" << endl;
686
687     if ( do_broadcast ) {
688         opengc_sock.setBroadcast( true );
689         fdm_sock.setBroadcast( true );
690         ctrls_sock.setBroadcast( true );
691     }
692
693     if ( opengc_sock.connect( out_host.c_str(), opengc_port ) == -1 ) {
694         perror("connect");
695         cout << "error connecting to outgoing opengc port: " << out_host
696              << ":" << opengc_port << endl;
697         return -1;
698     }
699     cout << "connected outgoing opengc socket" << endl;
700
701     if ( fdm_sock.connect( out_host.c_str(), fdm_port ) == -1 ) {
702         perror("connect");
703         cout << "error connecting to outgoing fdm port: " << out_host
704              << ":" << fdm_port << endl;
705         return -1;
706     }
707     cout << "connected outgoing fdm socket" << endl;
708
709     if ( ctrls_sock.connect( out_host.c_str(), ctrls_port ) == -1 ) {
710         perror("connect");
711         cout << "error connecting to outgoing ctrls port: " << out_host
712              << ":" << ctrls_port << endl;
713         return -1;
714     }
715     cout << "connected outgoing ctrls socket" << endl;
716
717     if ( sg_swap ) {
718         track.set_stargate_swap_mode();
719     }
720
721     UGTelnet telnet( 5402 );
722     telnet.open();
723
724     if ( infile.length() || flight_dir.length() ) {
725         if ( infile.length() ) {
726             // Load data from a stream log data file
727             track.load_stream( infile, ignore_checksum );
728         } else if ( flight_dir.length() ) {
729             // Load data from a flight directory
730             track.load_flight( flight_dir );
731         }
732         cout << "Loaded " << track.gps_size() << " gps records." << endl;
733         cout << "Loaded " << track.imu_size() << " imu records." << endl;
734         cout << "Loaded " << track.nav_size() << " nav records." << endl;
735         cout << "Loaded " << track.servo_size() << " servo records." << endl;
736         cout << "Loaded " << track.health_size() << " health records." << endl;
737
738         int size = track.imu_size();
739
740         double current_time = track.get_imupt(0).time;
741         cout << "Track begin time is " << current_time << endl;
742         double end_time = track.get_imupt(size-1).time;
743         cout << "Track end time is " << end_time << endl;
744         cout << "Duration = " << end_time - current_time << endl;
745
746         if ( track.gps_size() > 0 ) {
747             double tmp = track.get_gpspt(track.gps_size()-1).ITOW;
748             int days = (int)(tmp / (24 * 60 * 60));
749             tmp -= days * 24 * 60 * 60;
750             int hours = (int)(tmp / (60 * 60));
751             tmp -= hours * 60 * 60;
752             int min = (int)(tmp / 60);
753             tmp -= min * 60;
754             double sec = tmp;
755             printf("[GPS  ]:ITOW= %.3f[sec]  %dd %02d:%02d:%06.3f\n",
756                    tmp, days, hours, min, sec);
757         }
758
759
760         // advance skip seconds forward
761         current_time += skip;
762
763         frame_us = 1000000.0 / hertz;
764         if ( frame_us < 0.0 ) {
765             frame_us = 0.0;
766         }
767
768         SGTimeStamp start_time;
769         start_time.stamp();
770         int gps_count = 0;
771         int imu_count = 0;
772         int nav_count = 0;
773         int servo_count = 0;
774         int health_count = 0;
775
776         gps gps0, gps1;
777         gps0 = gps1 = track.get_gpspt( 0 );
778
779         imu imu0, imu1;
780         imu0 = imu1 = track.get_imupt( 0 );
781
782         nav nav0, nav1;
783         nav0 = nav1 = track.get_navpt( 0 );
784
785         servo servo0, servo1;
786         servo0 = servo1 = track.get_servopt( 0 );
787
788         health health0, health1;
789         health0 = health1 = track.get_healthpt( 0 );
790
791         double last_lat = -999.9, last_lon = -999.9;
792
793         printf("<gpx>\n");
794         printf(" <trk>\n");
795         printf("  <trkseg>\n");
796         while ( current_time < end_time ) {
797             // cout << "current_time = " << current_time << " end_time = "
798             //      << end_time << endl;
799
800             // Advance gps pointer
801             while ( current_time > gps1.time
802                     && gps_count < track.gps_size() - 1 )
803             {
804                 gps0 = gps1;
805                 ++gps_count;
806                 // cout << "count = " << count << endl;
807                 gps1 = track.get_gpspt( gps_count );
808             }
809             // cout << "p0 = " << p0.get_time() << " p1 = " << p1.get_time()
810             //      << endl;
811
812             // Advance imu pointer
813             while ( current_time > imu1.time
814                     && imu_count < track.imu_size() - 1 )
815             {
816                 imu0 = imu1;
817                 ++imu_count;
818                 // cout << "count = " << count << endl;
819                 imu1 = track.get_imupt( imu_count );
820             }
821             //  cout << "pos0 = " << pos0.get_seconds()
822             // << " pos1 = " << pos1.get_seconds() << endl;
823
824             // Advance nav pointer
825             while ( current_time > nav1.time
826                     && nav_count < track.nav_size() - 1 )
827             {
828                 nav0 = nav1;
829                 ++nav_count;
830                 // cout << "nav count = " << nav_count << endl;
831                 nav1 = track.get_navpt( nav_count );
832             }
833             //  cout << "pos0 = " << pos0.get_seconds()
834             // << " pos1 = " << pos1.get_seconds() << endl;
835
836             // Advance servo pointer
837             while ( current_time > servo1.time
838                     && servo_count < track.servo_size() - 1 )
839             {
840                 servo0 = servo1;
841                 ++servo_count;
842                 // cout << "count = " << count << endl;
843                 servo1 = track.get_servopt( servo_count );
844             }
845             //  cout << "pos0 = " << pos0.get_seconds()
846             // << " pos1 = " << pos1.get_seconds() << endl;
847
848             // Advance health pointer
849             while ( current_time > health1.time
850                     && health_count < track.health_size() - 1 )
851             {
852                 health0 = health1;
853                 ++health_count;
854                 // cout << "count = " << count << endl;
855                 health1 = track.get_healthpt( health_count );
856             }
857             //  cout << "pos0 = " << pos0.get_seconds()
858             // << " pos1 = " << pos1.get_seconds() << endl;
859
860             double gps_percent;
861             if ( fabs(gps1.time - gps0.time) < 0.00001 ) {
862                 gps_percent = 0.0;
863             } else {
864                 gps_percent =
865                     (current_time - gps0.time) /
866                     (gps1.time - gps0.time);
867             }
868             // cout << "Percent = " << percent << endl;
869
870             double imu_percent;
871             if ( fabs(imu1.time - imu0.time) < 0.00001 ) {
872                 imu_percent = 0.0;
873             } else {
874                 imu_percent =
875                     (current_time - imu0.time) /
876                     (imu1.time - imu0.time);
877             }
878             // cout << "Percent = " << percent << endl;
879
880             double nav_percent;
881             if ( fabs(nav1.time - nav0.time) < 0.00001 ) {
882                 nav_percent = 0.0;
883             } else {
884                 nav_percent =
885                     (current_time - nav0.time) /
886                     (nav1.time - nav0.time);
887             }
888             // cout << "Percent = " << percent << endl;
889
890             double servo_percent;
891             if ( fabs(servo1.time - servo0.time) < 0.00001 ) {
892                 servo_percent = 0.0;
893             } else {
894                 servo_percent =
895                     (current_time - servo0.time) /
896                     (servo1.time - servo0.time);
897             }
898             // cout << "Percent = " << percent << endl;
899
900             double health_percent;
901             if ( fabs(health1.time - health0.time) < 0.00001 ) {
902                 health_percent = 0.0;
903             } else {
904                 health_percent =
905                     (current_time - health0.time) /
906                     (health1.time - health0.time);
907             }
908             // cout << "Percent = " << percent << endl;
909
910             gps gpspacket = UGEARInterpGPS( gps0, gps1, gps_percent );
911             imu imupacket = UGEARInterpIMU( imu0, imu1, imu_percent );
912             nav navpacket = UGEARInterpNAV( nav0, nav1, nav_percent );
913             servo servopacket = UGEARInterpSERVO( servo0, servo1,
914                                                   servo_percent );
915             health healthpacket = UGEARInterpHEALTH( health0, health1,
916                                                   health_percent );
917
918             // cout << current_time << " " << p0.lat_deg << ", " << p0.lon_deg
919             //      << endl;
920             // cout << current_time << " " << p1.lat_deg << ", " << p1.lon_deg
921             //      << endl;
922             // cout << (double)current_time << " " << pos.lat_deg << ", "
923             //      << pos.lon_deg << " " << att.yaw_deg << endl;
924             if ( gpspacket.lat > -500 ) {
925                 // printf( "%.3f  %.4f %.4f %.1f  %.2f %.2f %.2f\n",
926                 //         current_time,
927                 //         navpacket.lat, navpacket.lon, navpacket.alt,
928                 //         imupacket.psi, imupacket.the, imupacket.phi );
929                 double dlat = last_lat - navpacket.lat;
930                 double dlon = last_lon - navpacket.lon;
931                 double dist = sqrt( dlat*dlat + dlon*dlon );
932                 if ( dist > 0.01 ) {
933                     printf("   <trkpt lat=\"%.8f\" lon=\"%.8f\"></trkpt>\n",
934                            navpacket.lat, navpacket.lon );
935                     // printf(" </wpt>\n");
936                     last_lat = navpacket.lat;
937                     last_lon = navpacket.lon;
938                 }
939             }
940
941             if ( (fabs(gpspacket.lat) < 0.0001 &&
942                   fabs(gpspacket.lon) < 0.0001 &&
943                   fabs(gpspacket.alt) < 0.0001) )
944             {
945                 printf("WARNING: LOST GPS!!!\n");
946                 gps_status = -1.0;
947             } else {
948                 gps_status = 1.0;
949             }
950
951             send_data_udp( &gpspacket, &imupacket, &navpacket, &servopacket,
952                            &healthpacket );
953
954             if ( run_real_time ) {
955                 // Update the elapsed time.
956                 static bool first_time = true;
957                 if ( first_time ) {
958                     last_time_stamp.stamp();
959                     first_time = false;
960                 }
961
962                 current_time_stamp.stamp();
963                 /* Convert to ms */
964                 double elapsed_us = (current_time_stamp - last_time_stamp).toUSecs();
965                 if ( elapsed_us < (frame_us - 2000) ) {
966                     double requested_us = (frame_us - elapsed_us) - 2000 ;
967                     ulMilliSecondSleep ( (int)(requested_us / 1000.0) ) ;
968                 }
969                 current_time_stamp.stamp();
970                 while ( (current_time_stamp - last_time_stamp).toUSecs() < frame_us ) {
971                     current_time_stamp.stamp();
972                 }
973             }
974
975             current_time += (frame_us / 1000000.0);
976             last_time_stamp = current_time_stamp;
977         }
978
979         printf("   <trkpt lat=\"%.8f\" lon=\"%.8f\"></trkpt>\n",
980                nav1.lat, nav1.lon );
981
982         printf("  </trkseg>\n");
983         printf(" </trk>\n");
984         nav0 = track.get_navpt( 0 );
985         nav1 = track.get_navpt( track.nav_size() - 1 );
986         printf(" <wpt lat=\"%.8f\" lon=\"%.8f\"></wpt>\n",
987                nav0.lat, nav0.lon );
988         printf(" <wpt lat=\"%.8f\" lon=\"%.8f\"></wpt>\n",
989                nav1.lat, nav1.lon );
990         printf("<gpx>\n");
991
992         cout << "Processed " << imu_count << " entries in "
993              << current_time_stamp - start_time << " seconds."
994              << endl;
995     } else if ( serialdev.length() ) {
996         // process incoming data from the serial port
997
998         int count = 0;
999         double current_time = 0.0;
1000         double last_time = 0.0;
1001
1002         gps gpspacket; bzero( &gpspacket, sizeof(gpspacket) );
1003         imu imupacket; bzero( &imupacket, sizeof(imupacket) );
1004         nav navpacket; bzero( &navpacket, sizeof(navpacket) );
1005         servo servopacket; bzero( &servopacket, sizeof(servopacket) );
1006         health healthpacket; bzero( &healthpacket, sizeof(healthpacket) );
1007
1008         double gps_time = 0.0;
1009         double imu_time = 0.0;
1010         double nav_time = 0.0;
1011         double servo_time = 0.0;
1012         double health_time = 0.0;
1013         double command_time = 0.0;
1014         double command_heartbeat = 0.0;
1015
1016         // open the serial port device
1017         SGSerialPort uavcom( serialdev, 115200 );
1018         if ( !uavcom.is_enabled() ) {
1019             cout << "Cannot open: " << serialdev << endl;
1020             return false;
1021         }
1022
1023         // open up the data log file if requested
1024         if ( !outfile.length() ) {
1025             cout << "no --outfile <name> specified, cannot capture data!"
1026                  << endl;
1027             return false;
1028         }
1029         SGFile log( outfile );
1030         if ( !log.open( SG_IO_OUT ) ) {
1031             cout << "Cannot open: " << outfile << endl;
1032             return false;
1033         }
1034
1035         // add some test commands
1036         //command_mgr.add("ap,alt,1000");
1037         //command_mgr.add("home,158.0,32.5");
1038         //command_mgr.add("go,home");
1039         //command_mgr.add("go,route");
1040
1041         while ( uavcom.is_enabled() ) {
1042             // cout << "looking for next message ..." << endl;
1043             int id = track.next_message( &uavcom, &log, &gpspacket,
1044                                          &imupacket, &navpacket, &servopacket,
1045                                          &healthpacket, ignore_checksum );
1046             // cout << "message id = " << id << endl;
1047             count++;
1048
1049             telnet.process();
1050
1051             if ( id == GPS_PACKET ) {
1052                 if ( gpspacket.time > gps_time ) {
1053                     gps_time = gpspacket.time;
1054                     current_time = gps_time;
1055                 } else {
1056                   cout << "oops gps back in time: " << gpspacket.time << " " << gps_time << endl;
1057                 }
1058             } else if ( id == IMU_PACKET ) {
1059                 if ( imupacket.time > imu_time ) {
1060                     imu_time = imupacket.time;
1061                     current_time = imu_time;
1062                 } else {
1063                     cout << "oops imu back in time: " << imupacket.time << " " << imu_time << endl;
1064                 }
1065             } else if ( id == NAV_PACKET ) {
1066                 if ( navpacket.time > nav_time ) {
1067                     nav_time = navpacket.time;
1068                     current_time = nav_time;
1069                 } else {
1070                     cout << "oops nav back in time: " << navpacket.time << " " << nav_time << endl;
1071                 }
1072             } else if ( id == SERVO_PACKET ) {
1073                 if ( servopacket.time > servo_time ) {
1074                     servo_time = servopacket.time;
1075                     current_time = servo_time;
1076                 } else {
1077                     cout << "oops servo back in time: " << servopacket.time << " " << servo_time << endl;
1078                 }
1079             } else if ( id == HEALTH_PACKET ) {
1080                 if ( healthpacket.time > health_time ) {
1081                     health_time = healthpacket.time;
1082                     current_time = health_time;
1083                     printf("Received a health packet, sequence: %d\n",
1084                            (int)healthpacket.command_sequence);
1085                     command_mgr.update_cmd_sequence(healthpacket.command_sequence);
1086                 } else {
1087                     cout << "oops health back in time: " << healthpacket.time << " " << health_time << endl;
1088                 }
1089
1090             }
1091
1092             if ( (current_time > gps_time + 2) ||
1093                  (fabs(gpspacket.lat) < 0.0001 &&
1094                   fabs(gpspacket.lon) < 0.0001 &&
1095                   fabs(gpspacket.alt) < 0.0001) )
1096             {
1097                 printf("WARNING: LOST GPS!!!\n");
1098                 gps_status = -1.0;
1099             } else {
1100                 gps_status = 1.0;
1101             }
1102
1103             // Generate a ground station heart beat every 4 seconds
1104             if ( current_time >= command_heartbeat + 4 ) {
1105                 command_mgr.add("hb");
1106                 command_heartbeat = current_time;
1107             }
1108
1109             // Command update @ 1hz
1110             if ( current_time >= command_time + 1 ) {
1111                 command_mgr.update(&uavcom);
1112                 command_time = current_time;
1113             }
1114
1115             // Relay data on to FlightGear and LFSTech Glass
1116             if ( current_time >= last_time + (1/hertz) ) {
1117                 // if ( gpspacket.lat > -500 ) {
1118                 int londeg = (int)navpacket.lon;
1119                 // double lonmin = fabs(navpacket.lon - londeg);
1120                 int latdeg = (int)navpacket.lat;
1121                 // double latmin = fabs(navpacket.lat - latdeg);
1122                 londeg = abs(londeg);
1123                 latdeg = abs(latdeg);
1124                 /*printf( "%.2f  %c%02d:%.4f %c%03d:%.4f %.1f  %.2f %.2f %.2f\n",
1125                         current_time,
1126                         latdir, latdeg, latmin, londir, londeg, lonmin,
1127                         navpacket.alt,
1128                         imupacket.phi*SGD_RADIANS_TO_DEGREES,
1129                         imupacket.the*SGD_RADIANS_TO_DEGREES,
1130                         imupacket.psi*SGD_RADIANS_TO_DEGREES ); */
1131                 // }
1132
1133                 last_time = current_time;
1134                 send_data_udp( &gpspacket, &imupacket, &navpacket,
1135                                &servopacket, &healthpacket );
1136             }
1137         }
1138     }
1139
1140     return 0;
1141 }