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 #include <iostream>
12 #include <string>
13 
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/io/raw_socket.hxx>
20 #include <simgear/serial/serial.hxx>
21 #include <simgear/math/sg_geodesy.hxx>
22 #include <simgear/timing/timestamp.hxx>
23 
24 #include <Network/net_ctrls.hxx>
25 #include <Network/net_fdm.hxx>
26 
27 #include "UGear.hxx"
28 #include "UGear_command.hxx"
29 #include "UGear_opengc.hxx"
30 #include "UGear_telnet.hxx"
31 
32 
33 using std::cout;
34 using std::endl;
35 using std::string;
36 
37 
38 // Network channels
39 static simgear::Socket fdm_sock, ctrls_sock, opengc_sock;
40 
41 // ugear data
42 UGTrack track;
43 
44 // Default ports
45 static int fdm_port = 5505;
46 static int ctrls_port = 5506;
47 static int opengc_port = 6000;
48 
49 // Default path
50 static string infile = "";
51 static string flight_dir = "";
52 static string serialdev = "";
53 static string outfile = "";
54 
55 // Master time counter
56 float sim_time = 0.0f;
57 double frame_us = 0.0f;
58 
59 // sim control
60 SGTimeStamp last_time_stamp;
61 SGTimeStamp current_time_stamp;
62 
63 // altitude offset
64 double alt_offset = 0.0;
65 
66 // skip initial seconds
67 double skip = 0.0;
68 
69 // for speed estimate
70 double last_lat = 0.0, last_lon = 0.0;
71 double kts_filter = 0.0;
72 
73 bool inited = false;
74 
75 bool run_real_time = true;
76 
77 bool ignore_checksum = false;
78 
79 bool sg_swap = false;
80 
81 bool use_ground_track_hdg = false;
82 bool use_ground_speed = false;
83 
84 bool est_controls = false;
85 
86 float gps_status = -1.0;
87 
88 
89 // The function htond is defined this way due to the way some
90 // processors and OSes treat floating point values.  Some will raise
91 // an exception whenever a "bad" floating point value is loaded into a
92 // floating point register.  Solaris is notorious for this, but then
93 // so is LynxOS on the PowerPC.  By translating the data in place,
94 // there is no need to load a FP register with the "corruped" floating
95 // point value.  By doing the BIG_ENDIAN test, I can optimize the
96 // routine for big-endian processors so it can be as efficient as
97 // possible
htond(double & x)98 static void htond (double &x)
99 {
100     if ( sgIsLittleEndian() ) {
101         int    *Double_Overlay;
102         int     Holding_Buffer;
103 
104         Double_Overlay = (int *) &x;
105         Holding_Buffer = Double_Overlay [0];
106 
107         Double_Overlay [0] = htonl (Double_Overlay [1]);
108         Double_Overlay [1] = htonl (Holding_Buffer);
109     } else {
110         return;
111     }
112 }
113 
114 // Float version
htonf(float & x)115 static void htonf (float &x)
116 {
117     if ( sgIsLittleEndian() ) {
118         int    *Float_Overlay;
119         int     Holding_Buffer;
120 
121         Float_Overlay = (int *) &x;
122         Holding_Buffer = Float_Overlay [0];
123 
124         Float_Overlay [0] = htonl (Holding_Buffer);
125     } else {
126         return;
127     }
128 }
129 
130 
ugear2fg(gps * gpspacket,imu * imupacket,nav * navpacket,servo * servopacket,health * healthpacket,FGNetFDM * fdm,FGNetCtrls * ctrls)131 static void ugear2fg( gps *gpspacket, imu *imupacket, nav *navpacket,
132 		      servo *servopacket, health *healthpacket,
133 		      FGNetFDM *fdm, FGNetCtrls *ctrls )
134 {
135     unsigned int i;
136 
137     // Version sanity checking
138     fdm->version = FG_NET_FDM_VERSION;
139 
140     // Aero parameters
141     fdm->longitude = navpacket->lon * SG_DEGREES_TO_RADIANS;
142     fdm->latitude = navpacket->lat * SG_DEGREES_TO_RADIANS;
143     fdm->altitude = navpacket->alt + alt_offset;
144     fdm->agl = -9999.0;
145     fdm->psi = imupacket->psi; // heading
146     fdm->phi = imupacket->phi; // roll
147     fdm->theta = imupacket->the; // pitch;
148 
149     fdm->phidot = 0.0;
150     fdm->thetadot = 0.0;
151     fdm->psidot = 0.0;
152 
153     // estimate speed
154     // double az1, az2, dist;
155     // geo_inverse_wgs_84( fdm->altitude, last_lat, last_lon,
156     //                     fdm->latitude, fdm->longitude, &az1, &az2, &dist );
157     // last_lat = fdm->latitude;
158     // last_lon = fdm->longitude;
159     // double v_ms = dist / (frame_us / 1000000);
160     // double v_kts = v_ms * SG_METER_TO_NM * 3600;
161     // kts_filter = (0.9 * kts_filter) + (0.1 * v_kts);
162     // printf("dist = %.5f  kts est = %.2f\n", dist, kts_filter);
163 
164     double vn = navpacket->vn;
165     double ve = navpacket->ve;
166     double vd = navpacket->vd;
167 
168     if ( use_ground_track_hdg ) {
169         fdm->psi = SGD_PI * 0.5 - atan2(vn, ve); // heading
170     }
171 
172     double mps = 0.0;
173     if ( use_ground_speed ) {
174         mps = sqrt( vn*vn + ve*ve + vd*vd );
175     } else {
176         mps = imupacket->Pt;
177     }
178     // double mph = mps * 3600 / 1609.3440;
179     double kts = mps * SG_MPS_TO_KT;
180     fdm->vcas = kts;
181     // printf("speed = %.2f mph  %.2f kts\n", mph, kts );
182     static double Ps = 0.0, Ps_last = 0.0, t_last = 0.0;
183     Ps_last = Ps;
184     Ps = 0.92 * Ps + 0.08 * imupacket->Ps;
185     double climb = (Ps - Ps_last) / (imupacket->time - t_last);
186     t_last = imupacket->time;
187     static double climbf = 0.0;
188     climbf = 0.994 * climbf + 0.006 * climb;
189     fdm->climb_rate = climbf; // fps
190 
191     static double Ps_error = 0.0;
192     static double Ps_count = 0;
193     const double span = 10000.0;
194     Ps_count += 1.0; if (Ps_count > (span-1.0)) { Ps_count = (span-1.0); }
195     double error = navpacket->alt - Ps;
196     Ps_error = (Ps_count/span) * Ps_error + ((span-Ps_count)/span) * error;
197     fdm->altitude = Ps +  Ps_error;
198 
199     /* printf("%.3f, %.3f, %.3f, %.3f, %.8f, %.8f, %.3f, %.3f, %.3f, %.3f, %.3f\n",
200            imupacket->time, imupacket->the, -navpacket->vd, climbf,
201            navpacket->lat, navpacket->lon, gpspacket->alt, navpacket->alt,
202            imupacket->Ps, Ps, Ps + Ps_error); */
203 
204     // cout << "climb rate = " << aero->hdota << endl;
205     fdm->v_north = 0.0;
206     fdm->v_east = 0.0;
207     fdm->v_down = 0.0;
208     fdm->v_body_u = 0.0;
209     fdm->v_body_v = 0.0;
210     fdm->v_body_w = 0.0;
211     fdm->stall_warning = 0.0;
212 
213     fdm->A_X_pilot = 0.0;
214     fdm->A_Y_pilot = 0.0;
215     fdm->A_Z_pilot = 0.0 /* (should be -G) */;
216 
217     // Engine parameters
218     fdm->num_engines = 1;
219     fdm->eng_state[0] = 2;
220     // cout << "state = " << fdm->eng_state[0] << endl;
221     double rpm = 5000.0 - ((double)servopacket->chn[2] / 65536.0)*3500.0;
222     if ( rpm < 0.0 ) { rpm = 0.0; }
223     if ( rpm > 5000.0 ) { rpm = 5000.0; }
224     fdm->rpm[0] = rpm;
225 
226     fdm->fuel_flow[0] = 0.0;
227     fdm->egt[0] = 0.0;
228     // cout << "egt = " << aero->EGT << endl;
229     fdm->oil_temp[0] = 0.0;
230     fdm->oil_px[0] = 0.0;
231 
232     // Consumables
233     fdm->num_tanks = 2;
234     fdm->fuel_quantity[0] = 0.0;
235     fdm->fuel_quantity[1] = 0.0;
236 
237     // Gear and flaps
238     fdm->num_wheels = 3;
239     fdm->wow[0] = 0;
240     fdm->wow[1] = 0;
241     fdm->wow[2] = 0;
242 
243     // the following really aren't used in this context
244     fdm->cur_time = 0;
245     fdm->warp = 0;
246     fdm->visibility = 0;
247 
248     // cout << "Flap deflection = " << aero->dflap << endl;
249     fdm->left_flap = 0.0;
250     fdm->right_flap = 0.0;
251 
252     if ( est_controls ) {
253         static float est_elev = 0.0;
254         static float est_aileron = 0.0;
255         static float est_rudder = 0.0;
256         est_elev = 0.99 * est_elev + 0.01 * (imupacket->q * 4);
257         est_aileron = 0.95 * est_aileron + 0.05 * (imupacket->p * 5);
258         est_rudder = 0.95 * est_rudder + 0.05 * (imupacket->r * 2);
259         ctrls->elevator = fdm->elevator = -est_elev;
260         ctrls->aileron = fdm->left_aileron = est_aileron;
261         fdm->right_aileron = -est_aileron;
262         ctrls->rudder = fdm->rudder = est_rudder;
263     } else {
264         ctrls->elevator = fdm->elevator = 1.0 - ((double)servopacket->chn[1] / 32768.0);
265         ctrls->aileron = fdm->left_aileron = 1.0 - ((double)servopacket->chn[0] / 32768.0);
266         fdm->right_aileron = ((double)servopacket->chn[0] / 32768.0) - 1.0;
267         ctrls->rudder = fdm->rudder = 1.0 - ((double)servopacket->chn[3] / 32768.0);
268 	ctrls->elevator *= 3.0;
269 	ctrls->aileron *= 3.0;
270     }
271     fdm->elevator_trim_tab = 0.0;
272     fdm->left_flap = 0.0;
273     fdm->right_flap = 0.0;
274     fdm->nose_wheel = 0.0;
275     fdm->speedbrake = 0.0;
276     fdm->spoilers = 0.0;
277 
278     // Convert the net buffer to network format
279     fdm->version = htonl(fdm->version);
280 
281     htond(fdm->longitude);
282     htond(fdm->latitude);
283     htond(fdm->altitude);
284     htonf(fdm->agl);
285     htonf(fdm->phi);
286     htonf(fdm->theta);
287     htonf(fdm->psi);
288     htonf(fdm->alpha);
289     htonf(fdm->beta);
290 
291     htonf(fdm->phidot);
292     htonf(fdm->thetadot);
293     htonf(fdm->psidot);
294     htonf(fdm->vcas);
295     htonf(fdm->climb_rate);
296     htonf(fdm->v_north);
297     htonf(fdm->v_east);
298     htonf(fdm->v_down);
299     htonf(fdm->v_body_u);
300     htonf(fdm->v_body_v);
301     htonf(fdm->v_body_w);
302 
303     htonf(fdm->A_X_pilot);
304     htonf(fdm->A_Y_pilot);
305     htonf(fdm->A_Z_pilot);
306 
307     htonf(fdm->stall_warning);
308     htonf(fdm->slip_deg);
309 
310     for ( i = 0; i < fdm->num_engines; ++i ) {
311         fdm->eng_state[i] = htonl(fdm->eng_state[i]);
312         htonf(fdm->rpm[i]);
313         htonf(fdm->fuel_flow[i]);
314         htonf(fdm->egt[i]);
315         htonf(fdm->cht[i]);
316         htonf(fdm->mp_osi[i]);
317         htonf(fdm->tit[i]);
318         htonf(fdm->oil_temp[i]);
319         htonf(fdm->oil_px[i]);
320     }
321     fdm->num_engines = htonl(fdm->num_engines);
322 
323     for ( i = 0; i < fdm->num_tanks; ++i ) {
324         htonf(fdm->fuel_quantity[i]);
325     }
326     fdm->num_tanks = htonl(fdm->num_tanks);
327 
328     for ( i = 0; i < fdm->num_wheels; ++i ) {
329         fdm->wow[i] = htonl(fdm->wow[i]);
330         htonf(fdm->gear_pos[i]);
331         htonf(fdm->gear_steer[i]);
332         htonf(fdm->gear_compression[i]);
333     }
334     fdm->num_wheels = htonl(fdm->num_wheels);
335 
336     fdm->cur_time = htonl( fdm->cur_time );
337     fdm->warp = htonl( fdm->warp );
338     htonf(fdm->visibility);
339 
340     htonf(fdm->elevator);
341     htonf(fdm->elevator_trim_tab);
342     htonf(fdm->left_flap);
343     htonf(fdm->right_flap);
344     htonf(fdm->left_aileron);
345     htonf(fdm->right_aileron);
346     htonf(fdm->rudder);
347     htonf(fdm->nose_wheel);
348     htonf(fdm->speedbrake);
349     htonf(fdm->spoilers);
350 
351 #if 0
352     ctrls->version = FG_NET_CTRLS_VERSION;
353     ctrls->elevator_trim = 0.0;
354     ctrls->flaps = 0.0;
355 
356     htonl(ctrls->version);
357     htond(ctrls->aileron);
358     htond(ctrls->rudder);
359     htond(ctrls->elevator);
360     htond(ctrls->elevator_trim);
361     htond(ctrls->flaps);
362 #endif
363 }
364 
365 
ugear2opengc(gps * gpspacket,imu * imupacket,nav * navpacket,servo * servopacket,health * healthpacket,ogcFGData * ogc)366 static void ugear2opengc( gps *gpspacket, imu *imupacket, nav *navpacket,
367                           servo *servopacket, health *healthpacket,
368                           ogcFGData *ogc )
369 {
370     // Version sanity checking
371     ogc->version_id = OGC_VERSION;
372 
373     // Aero parameters
374     ogc->longitude = navpacket->lon;
375     ogc->latitude = navpacket->lat;
376     ogc->heading = imupacket->psi * SG_RADIANS_TO_DEGREES; // heading
377     ogc->bank = imupacket->phi * SG_RADIANS_TO_DEGREES; // roll
378     ogc->pitch = imupacket->the * SG_RADIANS_TO_DEGREES; // pitch;
379 
380     ogc->phi_dot = 0.0;
381     ogc->theta_dot = 0.0;
382     ogc->psi_dot = 0.0;
383 
384     ogc->alpha = 0.0;
385     ogc->beta = 0.0;
386     ogc->alpha_dot = 0.0;
387     ogc->beta_dot = 0.0;
388 
389     ogc->left_aileron = 1.0 - ((double)servopacket->chn[0] / 32768.0);
390     ogc->right_aileron = ((double)servopacket->chn[0] / 32768.0) - 1.0;
391     ogc->elevator = 1.0 - ((double)servopacket->chn[1] / 32768.0);
392     ogc->elevator_trim = 0.0;
393     ogc->rudder = 1.0 - ((double)servopacket->chn[3] / 32768.0);
394     ogc->flaps = 0.0;
395     ogc->flaps_cmd = 0.0;
396 
397     ogc->wind = 0.0;
398     ogc->wind_dir = 0.0;
399 
400     // estimate speed
401     // double az1, az2, dist;
402     // geo_inverse_wgs_84( fdm->altitude, last_lat, last_lon,
403     //                     fdm->latitude, fdm->longitude, &az1, &az2, &dist );
404     // last_lat = fdm->latitude;
405     // last_lon = fdm->longitude;
406     // double v_ms = dist / (frame_us / 1000000);
407     // double v_kts = v_ms * SG_METER_TO_NM * 3600;
408     // kts_filter = (0.9 * kts_filter) + (0.1 * v_kts);
409     // printf("dist = %.5f  kts est = %.2f\n", dist, kts_filter);
410 
411     double vn = navpacket->vn;
412     double ve = navpacket->ve;
413     double vd = navpacket->vd;
414 
415     if ( use_ground_track_hdg ) {
416         ogc->heading = (SGD_PI * 0.5 - atan2(vn, ve)) * SG_RADIANS_TO_DEGREES;
417     }
418 
419     if ( ogc->heading < 0 ) { ogc->heading += 360.0; }
420 
421     double mps = 0.0;
422     if ( use_ground_speed ) {
423         mps = sqrt( vn*vn + ve*ve + vd*vd );
424     } else {
425         mps = imupacket->Pt;
426     }
427     // double mph = mps * 3600 / 1609.3440;
428     double kts = mps * SG_MPS_TO_KT;
429     ogc->v_kcas = kts;
430     // printf("speed = %.2f mph  %.2f kts\n", mph, kts );
431     static double Ps = 0.0, Ps_last = 0.0, t_last = 0.0;
432     Ps_last = Ps;
433     Ps = 0.92 * Ps + 0.08 * imupacket->Ps;
434     double climb = (Ps - Ps_last) / (imupacket->time - t_last);
435     t_last = imupacket->time;
436     static double climbf = 0.0;
437     climbf = 0.994 * climbf + 0.006 * climb;
438     ogc->vvi = climbf; // fps
439 
440     // uncomment one of the following schemes for setting elevation:
441 
442     // use the navigation (inertially augmented gps estimate)
443     // ogc->altitude = ogc->elevation
444     //     = (navpacket->alt + alt_offset * SG_METER_TO_FEET);
445 
446     // use estimate error between pressure sensor and gps altitude over time
447     // use pressure sensor + error average for altitude estimate.
448     static double Ps_error = 0.0;
449     static double Ps_count = 0;
450     const double span = 10000.0;
451     Ps_count += 1.0; if (Ps_count > (span-1.0)) { Ps_count = (span-1.0); }
452     double error = navpacket->alt - Ps;
453     Ps_error = (Ps_count/span) * Ps_error + ((span-Ps_count)/span) * error;
454     ogc->elevation = (Ps +  Ps_error) * SG_METER_TO_FEET;
455 
456     /* printf("%.3f, %.3f, %.3f, %.3f, %.8f, %.8f, %.3f, %.3f, %.3f, %.3f, %.3f\n",
457            imupacket->time, imupacket->the, -navpacket->vd, climbf,
458            navpacket->lat, navpacket->lon, gpspacket->alt, navpacket->alt,
459            imupacket->Ps, Ps, Ps + Ps_error); */
460 
461     if ( est_controls ) {
462         static float est_elev = 0.0;
463         static float est_aileron = 0.0;
464         static float est_rudder = 0.0;
465         est_elev = 0.99 * est_elev + 0.01 * (imupacket->q * 4);
466         est_aileron = 0.95 * est_aileron + 0.05 * (imupacket->p * 5);
467         est_rudder = 0.95 * est_rudder + 0.05 * (imupacket->r * 2);
468         ogc->elevator = -est_elev;
469         ogc->left_aileron = est_aileron;
470         ogc->right_aileron = -est_aileron;
471         ogc->rudder = est_rudder;
472     } else {
473         ogc->elevator = 1.0 - ((double)servopacket->chn[1] / 32768.0);
474         ogc->left_aileron = 1.0 - ((double)servopacket->chn[0] / 32768.0);
475         ogc->right_aileron = ((double)servopacket->chn[0] / 32768.0) - 1.0;
476         ogc->rudder = 1.0 - ((double)servopacket->chn[3] / 32768.0);
477     }
478     ogc->elevator *= 4.0;
479     ogc->left_aileron *= 4.0;
480     ogc->right_aileron *= 4.0;
481     ogc->rudder *= 4.0;
482 
483     // additional "abused" data fields
484     ogc->egt[0] = ogc->bank - healthpacket->target_roll_deg; // flight director target roll
485     ogc->egt[1] = -ogc->pitch + healthpacket->target_pitch_deg; // flight director target pitch
486     ogc->egt[2] = healthpacket->target_heading_deg; // target heading bug
487     ogc->egt[3] = healthpacket->target_climb_fps;   // target VVI bug
488     ogc->epr[0] = healthpacket->target_altitude_ft; // target altitude bug
489     ogc->epr[1] = 30.0;                              // target speed bug
490     ogc->epr[2] = gps_status;   // gps status box
491 }
492 
493 
send_data_udp(gps * gpspacket,imu * imupacket,nav * navpacket,servo * servopacket,health * healthpacket)494 static void send_data_udp( gps *gpspacket, imu *imupacket, nav *navpacket,
495                            servo *servopacket, health *healthpacket )
496 {
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     opengc_sock.send(&fgogc, ogcsize, 0);
512     fdm_sock.send(&fgfdm, fdmsize, 0);
513     // len = ctrls_sock.send(&fgctrls, ctrlsize, 0);
514 }
515 
516 
usage(const string & argv0)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 
main(int argc,char ** argv)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     simgear::Socket::initSockets(); // 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; memset( &gpspacket, 0, sizeof gpspacket );
998 	imu imupacket; memset( &imupacket, 0, sizeof imupacket );
999 	nav navpacket; memset( &navpacket, 0, sizeof navpacket );
1000 	servo servopacket; memset( &servopacket, 0, sizeof servopacket );
1001 	health healthpacket; memset( &healthpacket, 0, 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                 londeg = abs(londeg);
1118                 latdeg = abs(latdeg);
1119                 /*printf( "%.2f  %c%02d:%.4f %c%03d:%.4f %.1f  %.2f %.2f %.2f\n",
1120                         current_time,
1121                         latdir, latdeg, latmin, londir, londeg, lonmin,
1122                         navpacket.alt,
1123                         imupacket.phi*SGD_RADIANS_TO_DEGREES,
1124                         imupacket.the*SGD_RADIANS_TO_DEGREES,
1125                         imupacket.psi*SGD_RADIANS_TO_DEGREES ); */
1126                 // }
1127 
1128                 last_time = current_time;
1129                 send_data_udp( &gpspacket, &imupacket, &navpacket,
1130                                &servopacket, &healthpacket );
1131             }
1132         }
1133     }
1134 
1135     return 0;
1136 }
1137