]> git.mxchange.org Git - flightgear.git/blob - utils/GPSsmooth/MIDG_main.cxx
considering u,v,wbody-fps are the ECEF velocity expressed in body axis, change in...
[flightgear.git] / utils / GPSsmooth / MIDG_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 #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/sg_serial.hxx>
20 #include <simgear/io/raw_socket.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 "MIDG-II.hxx"
28
29
30 using std::cout;
31 using std::endl;
32 using std::string;
33
34
35 // Network channels
36 static simgear::Socket fdm_sock, ctrls_sock;
37
38 // midg data
39 MIDGTrack track;
40
41 // Default ports
42 static int fdm_port = 5505;
43 static int ctrls_port = 5506;
44
45 // Default path
46 static string infile = "";
47 static string serialdev = "";
48 static string outfile = "";
49
50 // Master time counter
51 float sim_time = 0.0f;
52 double frame_us = 0.0f;
53
54 // sim control
55 SGTimeStamp last_time_stamp;
56 SGTimeStamp current_time_stamp;
57
58 // altitude offset
59 double alt_offset = 0.0;
60
61 // skip initial seconds
62 double skip = 0.0;
63
64 // for speed estimate
65 // double last_lat = 0.0, last_lon = 0.0;
66 // double kts_filter = 0.0;
67
68 bool inited = false;
69
70
71 // The function htond is defined this way due to the way some
72 // processors and OSes treat floating point values.  Some will raise
73 // an exception whenever a "bad" floating point value is loaded into a
74 // floating point register.  Solaris is notorious for this, but then
75 // so is LynxOS on the PowerPC.  By translating the data in place,
76 // there is no need to load a FP register with the "corruped" floating
77 // point value.  By doing the BIG_ENDIAN test, I can optimize the
78 // routine for big-endian processors so it can be as efficient as
79 // possible
80 static void htond (double &x)
81 {
82     if ( sgIsLittleEndian() ) {
83         int    *Double_Overlay;
84         int     Holding_Buffer;
85
86         Double_Overlay = (int *) &x;
87         Holding_Buffer = Double_Overlay [0];
88
89         Double_Overlay [0] = htonl (Double_Overlay [1]);
90         Double_Overlay [1] = htonl (Holding_Buffer);
91     } else {
92         return;
93     }
94 }
95
96 // Float version
97 static void htonf (float &x)
98 {
99     if ( sgIsLittleEndian() ) {
100         int    *Float_Overlay;
101         int     Holding_Buffer;
102
103         Float_Overlay = (int *) &x;
104         Holding_Buffer = Float_Overlay [0];
105
106         Float_Overlay [0] = htonl (Holding_Buffer);
107     } else {
108         return;
109     }
110 }
111
112
113 static void midg2fg( const MIDGpos pos, const MIDGatt att,
114                      FGNetFDM *fdm, FGNetCtrls *ctrls )
115 {
116     unsigned int i;
117
118     // Version sanity checking
119     fdm->version = FG_NET_FDM_VERSION;
120
121     // Aero parameters
122     fdm->longitude = pos.lon_deg * SGD_DEGREES_TO_RADIANS;
123     fdm->latitude = pos.lat_deg * SGD_DEGREES_TO_RADIANS;
124     fdm->altitude = pos.altitude_msl + alt_offset;
125     fdm->agl = -9999.0;
126     fdm->psi = att.yaw_rad; // heading
127     fdm->phi = att.roll_rad; // roll
128     fdm->theta = att.pitch_rad; // pitch;
129
130     fdm->phidot = 0.0;
131     fdm->thetadot = 0.0;
132     fdm->psidot = 0.0;
133
134     // estimate speed
135     // double az1, az2, dist;
136     // geo_inverse_wgs_84( pos.altitude_msl, last_lat, last_lon,
137     //                     pos.lat_deg, pos.lon_deg, &az1, &az2, &dist );
138     // double v_ms = dist / (frame_us / 1000000);
139     // double v_kts = v_ms * SG_METER_TO_NM * 3600;
140     // kts_filter = (0.99 * kts_filter) + (0.01 * v_kts);
141     fdm->vcas = pos.speed_kts;
142     // last_lat = pos.lat_deg;
143     // last_lon = pos.lon_deg;
144     // cout << "kts_filter = " << kts_filter << " vel = " << pos.speed_kts << endl;
145
146     fdm->climb_rate = 0; // fps
147     // cout << "climb rate = " << aero->hdota << endl;
148     fdm->v_north = 0.0;
149     fdm->v_east = 0.0;
150     fdm->v_down = 0.0;
151     fdm->v_body_u = 0.0;
152     fdm->v_body_v = 0.0;
153     fdm->v_body_w = 0.0;
154     fdm->stall_warning = 0.0;
155
156     fdm->A_X_pilot = 0.0;
157     fdm->A_Y_pilot = 0.0;
158     fdm->A_Z_pilot = 0.0 /* (should be -G) */;
159
160     // Engine parameters
161     fdm->num_engines = 1;
162     fdm->eng_state[0] = 2;
163     // cout << "state = " << fdm->eng_state[0] << endl;
164     double rpm = ((pos.speed_kts - 15.0) / 65.0) * 2000.0 + 500.0;
165     if ( rpm < 0.0 ) { rpm = 0.0; }
166     if ( rpm > 3000.0 ) { rpm = 3000.0; }
167     fdm->rpm[0] = rpm;
168
169     fdm->fuel_flow[0] = 0.0;
170     fdm->egt[0] = 0.0;
171     // cout << "egt = " << aero->EGT << endl;
172     fdm->oil_temp[0] = 0.0;
173     fdm->oil_px[0] = 0.0;
174
175     // Consumables
176     fdm->num_tanks = 2;
177     fdm->fuel_quantity[0] = 0.0;
178     fdm->fuel_quantity[1] = 0.0;
179
180     // Gear and flaps
181     fdm->num_wheels = 3;
182     fdm->wow[0] = 0;
183     fdm->wow[1] = 0;
184     fdm->wow[2] = 0;
185
186     // the following really aren't used in this context
187     fdm->cur_time = 0;
188     fdm->warp = 0;
189     fdm->visibility = 0;
190
191     // cout << "Flap deflection = " << aero->dflap << endl;
192     fdm->left_flap = 0.0;
193     fdm->right_flap = 0.0;
194
195     fdm->elevator = -fdm->theta * 1.0;
196     fdm->elevator_trim_tab = 0.0;
197     fdm->left_flap = 0.0;
198     fdm->right_flap = 0.0;
199     fdm->left_aileron = fdm->phi * 1.0;
200     fdm->right_aileron = -fdm->phi * 1.0;
201     fdm->rudder = 0.0;
202     fdm->nose_wheel = 0.0;
203     fdm->speedbrake = 0.0;
204     fdm->spoilers = 0.0;
205
206     // Convert the net buffer to network format
207     fdm->version = htonl(fdm->version);
208
209     htond(fdm->longitude);
210     htond(fdm->latitude);
211     htond(fdm->altitude);
212     htonf(fdm->agl);
213     htonf(fdm->phi);
214     htonf(fdm->theta);
215     htonf(fdm->psi);
216     htonf(fdm->alpha);
217     htonf(fdm->beta);
218
219     htonf(fdm->phidot);
220     htonf(fdm->thetadot);
221     htonf(fdm->psidot);
222     htonf(fdm->vcas);
223     htonf(fdm->climb_rate);
224     htonf(fdm->v_north);
225     htonf(fdm->v_east);
226     htonf(fdm->v_down);
227     htonf(fdm->v_body_u);
228     htonf(fdm->v_body_v);
229     htonf(fdm->v_body_w);
230
231     htonf(fdm->A_X_pilot);
232     htonf(fdm->A_Y_pilot);
233     htonf(fdm->A_Z_pilot);
234
235     htonf(fdm->stall_warning);
236     htonf(fdm->slip_deg);
237
238     for ( i = 0; i < fdm->num_engines; ++i ) {
239         fdm->eng_state[i] = htonl(fdm->eng_state[i]);
240         htonf(fdm->rpm[i]);
241         htonf(fdm->fuel_flow[i]);
242         htonf(fdm->egt[i]);
243         htonf(fdm->cht[i]);
244         htonf(fdm->mp_osi[i]);
245         htonf(fdm->tit[i]);
246         htonf(fdm->oil_temp[i]);
247         htonf(fdm->oil_px[i]);
248     }
249     fdm->num_engines = htonl(fdm->num_engines);
250
251     for ( i = 0; i < fdm->num_tanks; ++i ) {
252         htonf(fdm->fuel_quantity[i]);
253     }
254     fdm->num_tanks = htonl(fdm->num_tanks);
255
256     for ( i = 0; i < fdm->num_wheels; ++i ) {
257         fdm->wow[i] = htonl(fdm->wow[i]);
258         htonf(fdm->gear_pos[i]);
259         htonf(fdm->gear_steer[i]);
260         htonf(fdm->gear_compression[i]);
261     }
262     fdm->num_wheels = htonl(fdm->num_wheels);
263
264     fdm->cur_time = htonl( fdm->cur_time );
265     fdm->warp = htonl( fdm->warp );
266     htonf(fdm->visibility);
267
268     htonf(fdm->elevator);
269     htonf(fdm->elevator_trim_tab);
270     htonf(fdm->left_flap);
271     htonf(fdm->right_flap);
272     htonf(fdm->left_aileron);
273     htonf(fdm->right_aileron);
274     htonf(fdm->rudder);
275     htonf(fdm->nose_wheel);
276     htonf(fdm->speedbrake);
277     htonf(fdm->spoilers);
278 }
279
280
281 static void send_data( const MIDGpos pos, const MIDGatt att ) {
282     int fdmsize = sizeof( FGNetFDM );
283
284     FGNetFDM fgfdm;
285     FGNetCtrls fgctrls;
286
287     midg2fg( pos, att, &fgfdm, &fgctrls );
288     fdm_sock.send(&fgfdm, fdmsize, 0);
289 }
290
291
292 void usage( const string &argv0 ) {
293     cout << "Usage: " << argv0 << endl;
294     cout << "\t[ --help ]" << endl;
295     cout << "\t[ --infile <infile_name>" << endl;
296     cout << "\t[ --serial <dev_name>" << endl;
297     cout << "\t[ --outfile <outfile_name> (capture the data to a file)" << endl;
298     cout << "\t[ --hertz <hertz> ]" << endl;
299     cout << "\t[ --host <hostname> ]" << endl;
300     cout << "\t[ --broadcast ]" << endl;
301     cout << "\t[ --fdm-port <fdm output port #> ]" << endl;
302     cout << "\t[ --ctrls-port <ctrls output port #> ]" << endl;
303     cout << "\t[ --altitude-offset <meters> ]" << endl;
304     cout << "\t[ --skip-seconds <seconds> ]" << endl;
305 }
306
307
308 int main( int argc, char **argv ) {
309     double hertz = 60.0;
310     string out_host = "localhost";
311     bool do_broadcast = false;
312
313     // process command line arguments
314     for ( int i = 1; i < argc; ++i ) {
315         if ( strcmp( argv[i], "--help" ) == 0 ) {
316             usage( argv[0] );
317             exit( 0 );
318         } else if ( strcmp( argv[i], "--hertz" ) == 0 ) {
319             ++i;
320             if ( i < argc ) {
321                 hertz = atof( argv[i] );
322             } else {
323                 usage( argv[0] );
324                 exit( -1 );
325             }
326         } else if ( strcmp( argv[i], "--infile" ) == 0 ) {
327             ++i;
328             if ( i < argc ) {
329                 infile = argv[i];
330             } else {
331                 usage( argv[0] );
332                 exit( -1 );
333             }
334         } else if ( strcmp( argv[i], "--outfile" ) == 0 ) {
335             ++i;
336             if ( i < argc ) {
337                 outfile = argv[i];
338             } else {
339                 usage( argv[0] );
340                 exit( -1 );
341             }
342         } else if ( strcmp( argv[i], "--serial" ) == 0 ) {
343             ++i;
344             if ( i < argc ) {
345                 serialdev = argv[i];
346             } else {
347                 usage( argv[0] );
348                 exit( -1 );
349             }
350         } else if ( strcmp( argv[i], "--host" ) == 0 ) {
351             ++i;
352             if ( i < argc ) {
353                 out_host = argv[i];
354             } else {
355                 usage( argv[0] );
356                 exit( -1 );
357             }
358         } else if ( strcmp( argv[i], "--broadcast" ) == 0 ) {
359           do_broadcast = true;
360         } else if ( strcmp( argv[i], "--fdm-port" ) == 0 ) {
361             ++i;
362             if ( i < argc ) {
363                 fdm_port = atoi( argv[i] );
364             } else {
365                 usage( argv[0] );
366                 exit( -1 );
367             }
368         } else if ( strcmp( argv[i], "--ctrls-port" ) == 0 ) {
369             ++i;
370             if ( i < argc ) {
371                 ctrls_port = atoi( argv[i] );
372             } else {
373                 usage( argv[0] );
374                 exit( -1 );
375             }
376         } else if ( strcmp( argv[i], "--altitude-offset" ) == 0 ) {
377             ++i;
378             if ( i < argc ) {
379                 alt_offset = atof( argv[i] );
380             } else {
381                 usage( argv[0] );
382                 exit( -1 );
383             }
384         } else if ( strcmp( argv[i], "--skip-seconds" ) == 0 ) {
385             ++i;
386             if ( i < argc ) {
387                 skip = atof( argv[i] );
388             } else {
389                 usage( argv[0] );
390                 exit( -1 );
391             }
392         } else {
393             usage( argv[0] );
394             exit( -1 );
395         }
396     }
397
398     // Setup up outgoing network connections
399
400     simgear::Socket::initSockets(); // We must call this before any other net stuff
401
402     if ( ! fdm_sock.open( false ) ) {  // open a UDP socket
403         cout << "error opening fdm output socket" << endl;
404         return -1;
405     }
406     if ( ! ctrls_sock.open( false ) ) {  // open a UDP socket
407         cout << "error opening ctrls output socket" << endl;
408         return -1;
409     }
410     cout << "open net channels" << endl;
411
412     fdm_sock.setBlocking( false );
413     ctrls_sock.setBlocking( false );
414     cout << "blocking false" << endl;
415
416     if ( do_broadcast ) {
417         fdm_sock.setBroadcast( true );
418         ctrls_sock.setBroadcast( true );
419     }
420
421     if ( fdm_sock.connect( out_host.c_str(), fdm_port ) == -1 ) {
422         perror("connect");
423         cout << "error connecting to outgoing fdm port: " << out_host
424              << ":" << fdm_port << endl;
425         return -1;
426     }
427     cout << "connected outgoing fdm socket" << endl;
428
429     if ( ctrls_sock.connect( out_host.c_str(), ctrls_port ) == -1 ) {
430         perror("connect");
431         cout << "error connecting to outgoing ctrls port: " << out_host
432              << ":" << ctrls_port << endl;
433         return -1;
434     }
435     cout << "connected outgoing ctrls socket" << endl;
436
437     if ( infile.length() ) {
438         // Load data from a track data
439         track.load( infile );
440         cout << "Loaded " << track.pos_size() << " position records." << endl;
441         cout << "Loaded " << track.att_size() << " attitude records." << endl;
442
443         int size = track.pos_size();
444
445         double current_time = track.get_pospt(0).get_seconds();
446         cout << "Track begin time is " << current_time << endl;
447         double end_time = track.get_pospt(size-1).get_seconds();
448         cout << "Track end time is " << end_time << endl;
449         cout << "Duration = " << end_time - current_time << endl;
450
451         // advance skip seconds forward
452         current_time += skip;
453
454         frame_us = 1000000.0 / hertz;
455         if ( frame_us < 0.0 ) {
456             frame_us = 0.0;
457         }
458
459         SGTimeStamp start_time;
460         start_time.stamp();
461         int pos_count = 0;
462         int att_count = 0;
463
464         MIDGpos pos0, pos1;
465         pos0 = pos1 = track.get_pospt( 0 );
466
467         MIDGatt att0, att1;
468         att0 = att1 = track.get_attpt( 0 );
469
470         while ( current_time < end_time ) {
471             // cout << "current_time = " << current_time << " end_time = "
472             //      << end_time << endl;
473
474             // Advance position pointer
475             while ( current_time > pos1.get_seconds()
476                     && pos_count < track.pos_size() )
477             {
478                 pos0 = pos1;
479                 ++pos_count;
480                 // cout << "count = " << count << endl;
481                 pos1 = track.get_pospt( pos_count );
482             }
483             // cout << "p0 = " << p0.get_time() << " p1 = " << p1.get_time()
484             //      << endl;
485
486             // Advance attitude pointer
487             while ( current_time > att1.get_seconds()
488                     && att_count < track.att_size() )
489             {
490                 att0 = att1;
491                 ++att_count;
492                 // cout << "count = " << count << endl;
493                 att1 = track.get_attpt( att_count );
494             }
495             //  cout << "pos0 = " << pos0.get_seconds()
496             // << " pos1 = " << pos1.get_seconds() << endl;
497
498             double pos_percent;
499             if ( fabs(pos1.get_seconds() - pos0.get_seconds()) < 0.00001 ) {
500                 pos_percent = 0.0;
501             } else {
502                 pos_percent =
503                     (current_time - pos0.get_seconds()) /
504                     (pos1.get_seconds() - pos0.get_seconds());
505             }
506             // cout << "Percent = " << percent << endl;
507             double att_percent;
508             if ( fabs(att1.get_seconds() - att0.get_seconds()) < 0.00001 ) {
509                 att_percent = 0.0;
510             } else {
511                 att_percent =
512                     (current_time - att0.get_seconds()) /
513                     (att1.get_seconds() - att0.get_seconds());
514             }
515             // cout << "Percent = " << percent << endl;
516
517             MIDGpos pos = MIDGInterpPos( pos0, pos1, pos_percent );
518             MIDGatt att = MIDGInterpAtt( att0, att1, att_percent );
519             // cout << current_time << " " << p0.lat_deg << ", " << p0.lon_deg
520             //      << endl;
521             // cout << current_time << " " << p1.lat_deg << ", " << p1.lon_deg
522             //      << endl;
523             // cout << (double)current_time << " " << pos.lat_deg << ", "
524             //      << pos.lon_deg << " " << att.yaw_deg << endl;
525             if ( pos.lat_deg > -500 ) {
526             printf( "%.3f  %.4f %.4f %.1f  %.2f %.2f %.2f\n",
527                     current_time,
528                     pos.lat_deg, pos.lon_deg, pos.altitude_msl,
529                     att.yaw_rad * 180.0 / SG_PI,
530                     att.pitch_rad * 180.0 / SG_PI,
531                     att.roll_rad * 180.0 / SG_PI );
532             }
533
534             send_data( pos, att );
535
536             // Update the elapsed time.
537             static bool first_time = true;
538             if ( first_time ) {
539                 last_time_stamp.stamp();
540                 first_time = false;
541             }
542
543             current_time_stamp.stamp();
544             /* Convert to ms */
545             double elapsed_us = (current_time_stamp - last_time_stamp).toUSecs();
546             if ( elapsed_us < (frame_us - 2000) ) {
547                 double requested_us = (frame_us - elapsed_us) - 2000 ;
548                 ulMilliSecondSleep ( (int)(requested_us / 1000.0) ) ;
549             }
550             current_time_stamp.stamp();
551             while ( (current_time_stamp - last_time_stamp).toUSecs() < frame_us ) {
552                 current_time_stamp.stamp();
553             }
554
555             current_time += (frame_us / 1000000.0);
556             last_time_stamp = current_time_stamp;
557         }
558
559         cout << "Processed " << pos_count << " entries in "
560              << current_time_stamp - start_time << " seconds."
561              << endl;
562     } else if ( serialdev.length() ) {
563         // process incoming data from the serial port
564
565         int count = 0;
566
567         MIDGpos pos;
568         MIDGatt att;
569
570         uint32_t pos_time = 1;
571         uint32_t att_time = 1;
572
573         // open the serial port device
574         SGSerialPort input( serialdev, 115200 );
575         if ( !input.is_enabled() ) {
576             cout << "Cannot open: " << serialdev << endl;
577             return false;
578         }
579
580         // open up the data log file if requested
581         if ( !outfile.length() ) {
582             cout << "no --outfile <name> specified, cannot capture data!"
583                  << endl;
584             return false;
585         }
586         SGFile output( outfile );
587         if ( !output.open( SG_IO_OUT ) ) {
588             cout << "Cannot open: " << outfile << endl;
589             return false;
590         }
591
592         while ( input.is_enabled() ) {
593             // cout << "looking for next message ..." << endl;
594             int id = track.next_message( &input, &output, &pos, &att );
595             cout << "message id = " << id << endl;
596             count++;
597
598             if ( id == 10 ) {
599                 if ( att.get_msec() > att_time ) {
600                     att_time = att.get_msec();
601                     //current_time = att_time;
602                 } else {
603                     cout << "oops att back in time" << endl;
604                 }
605             } else if ( id == 12 ) {
606                 if ( pos.get_msec() > pos_time ) {
607                     pos_time = pos.get_msec();
608                     //current_time = pos_time;
609                 } else {
610                     cout << "oops pos back in time" << endl;
611                 }
612             }
613
614             if ( pos.lat_deg > -500 ) {
615             // printf( "%.3f  %.4f %.4f %.1f  %.2f %.2f %.2f\n",
616             //         current_time,
617             //         pos.lat_deg, pos.lon_deg, pos.altitude_msl,
618             //         att.yaw_rad * 180.0 / SG_PI,
619             //         att.pitch_rad * 180.0 / SG_PI,
620             //         att.roll_rad * 180.0 / SG_PI );
621             }
622
623             send_data( pos, att );
624         }
625     }
626
627     return 0;
628 }