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