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