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