]> git.mxchange.org Git - flightgear.git/blob - utils/GPSsmooth/MIDG_main.cxx
118c6198bf960c8c0c6190394bb98898a2c3d79c
[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_wind_body_north = 0.0;
152     fdm->v_wind_body_east = 0.0;
153     fdm->v_wind_body_down = 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_wind_body_north);
228     htonf(fdm->v_wind_body_east);
229     htonf(fdm->v_wind_body_down);
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 len;
283     int fdmsize = sizeof( FGNetFDM );
284
285     // cout << "Running main loop" << endl;
286
287     FGNetFDM fgfdm;
288     FGNetCtrls fgctrls;
289
290     midg2fg( pos, att, &fgfdm, &fgctrls );
291     len = fdm_sock.send(&fgfdm, fdmsize, 0);
292 }
293
294
295 void usage( const string &argv0 ) {
296     cout << "Usage: " << argv0 << endl;
297     cout << "\t[ --help ]" << endl;
298     cout << "\t[ --infile <infile_name>" << endl;
299     cout << "\t[ --serial <dev_name>" << endl;
300     cout << "\t[ --outfile <outfile_name> (capture the data to a file)" << endl;
301     cout << "\t[ --hertz <hertz> ]" << endl;
302     cout << "\t[ --host <hostname> ]" << endl;
303     cout << "\t[ --broadcast ]" << endl;
304     cout << "\t[ --fdm-port <fdm output port #> ]" << endl;
305     cout << "\t[ --ctrls-port <ctrls output port #> ]" << endl;
306     cout << "\t[ --altitude-offset <meters> ]" << endl;
307     cout << "\t[ --skip-seconds <seconds> ]" << endl;
308 }
309
310
311 int main( int argc, char **argv ) {
312     double hertz = 60.0;
313     string out_host = "localhost";
314     bool do_broadcast = false;
315
316     // process command line arguments
317     for ( int i = 1; i < argc; ++i ) {
318         if ( strcmp( argv[i], "--help" ) == 0 ) {
319             usage( argv[0] );
320             exit( 0 );
321         } else if ( strcmp( argv[i], "--hertz" ) == 0 ) {
322             ++i;
323             if ( i < argc ) {
324                 hertz = atof( argv[i] );
325             } else {
326                 usage( argv[0] );
327                 exit( -1 );
328             }
329         } else if ( strcmp( argv[i], "--infile" ) == 0 ) {
330             ++i;
331             if ( i < argc ) {
332                 infile = argv[i];
333             } else {
334                 usage( argv[0] );
335                 exit( -1 );
336             }
337         } else if ( strcmp( argv[i], "--outfile" ) == 0 ) {
338             ++i;
339             if ( i < argc ) {
340                 outfile = argv[i];
341             } else {
342                 usage( argv[0] );
343                 exit( -1 );
344             }
345         } else if ( strcmp( argv[i], "--serial" ) == 0 ) {
346             ++i;
347             if ( i < argc ) {
348                 serialdev = argv[i];
349             } else {
350                 usage( argv[0] );
351                 exit( -1 );
352             }
353         } else if ( strcmp( argv[i], "--host" ) == 0 ) {
354             ++i;
355             if ( i < argc ) {
356                 out_host = argv[i];
357             } else {
358                 usage( argv[0] );
359                 exit( -1 );
360             }
361         } else if ( strcmp( argv[i], "--broadcast" ) == 0 ) {
362           do_broadcast = true;
363         } else if ( strcmp( argv[i], "--fdm-port" ) == 0 ) {
364             ++i;
365             if ( i < argc ) {
366                 fdm_port = atoi( argv[i] );
367             } else {
368                 usage( argv[0] );
369                 exit( -1 );
370             }
371         } else if ( strcmp( argv[i], "--ctrls-port" ) == 0 ) {
372             ++i;
373             if ( i < argc ) {
374                 ctrls_port = atoi( argv[i] );
375             } else {
376                 usage( argv[0] );
377                 exit( -1 );
378             }
379         } else if ( strcmp( argv[i], "--altitude-offset" ) == 0 ) {
380             ++i;
381             if ( i < argc ) {
382                 alt_offset = atof( argv[i] );
383             } else {
384                 usage( argv[0] );
385                 exit( -1 );
386             }
387         } else if ( strcmp( argv[i], "--skip-seconds" ) == 0 ) {
388             ++i;
389             if ( i < argc ) {
390                 skip = atof( argv[i] );
391             } else {
392                 usage( argv[0] );
393                 exit( -1 );
394             }
395         } else {
396             usage( argv[0] );
397             exit( -1 );
398         }
399     }
400
401     // Setup up outgoing network connections
402
403     simgear::Socket::initSockets(); // We must call this before any other net stuff
404
405     if ( ! fdm_sock.open( false ) ) {  // open a UDP socket
406         cout << "error opening fdm output socket" << endl;
407         return -1;
408     }
409     if ( ! ctrls_sock.open( false ) ) {  // open a UDP socket
410         cout << "error opening ctrls output socket" << endl;
411         return -1;
412     }
413     cout << "open net channels" << endl;
414
415     fdm_sock.setBlocking( false );
416     ctrls_sock.setBlocking( false );
417     cout << "blocking false" << endl;
418
419     if ( do_broadcast ) {
420         fdm_sock.setBroadcast( true );
421         ctrls_sock.setBroadcast( true );
422     }
423
424     if ( fdm_sock.connect( out_host.c_str(), fdm_port ) == -1 ) {
425         perror("connect");
426         cout << "error connecting to outgoing fdm port: " << out_host
427              << ":" << fdm_port << endl;
428         return -1;
429     }
430     cout << "connected outgoing fdm socket" << endl;
431
432     if ( ctrls_sock.connect( out_host.c_str(), ctrls_port ) == -1 ) {
433         perror("connect");
434         cout << "error connecting to outgoing ctrls port: " << out_host
435              << ":" << ctrls_port << endl;
436         return -1;
437     }
438     cout << "connected outgoing ctrls socket" << endl;
439
440     if ( infile.length() ) {
441         // Load data from a track data
442         track.load( infile );
443         cout << "Loaded " << track.pos_size() << " position records." << endl;
444         cout << "Loaded " << track.att_size() << " attitude records." << endl;
445
446         int size = track.pos_size();
447
448         double current_time = track.get_pospt(0).get_seconds();
449         cout << "Track begin time is " << current_time << endl;
450         double end_time = track.get_pospt(size-1).get_seconds();
451         cout << "Track end time is " << end_time << endl;
452         cout << "Duration = " << end_time - current_time << endl;
453
454         // advance skip seconds forward
455         current_time += skip;
456
457         frame_us = 1000000.0 / hertz;
458         if ( frame_us < 0.0 ) {
459             frame_us = 0.0;
460         }
461
462         SGTimeStamp start_time;
463         start_time.stamp();
464         int pos_count = 0;
465         int att_count = 0;
466
467         MIDGpos pos0, pos1;
468         pos0 = pos1 = track.get_pospt( 0 );
469     
470         MIDGatt att0, att1;
471         att0 = att1 = track.get_attpt( 0 );
472     
473         while ( current_time < end_time ) {
474             // cout << "current_time = " << current_time << " end_time = "
475             //      << end_time << endl;
476
477             // Advance position pointer
478             while ( current_time > pos1.get_seconds()
479                     && pos_count < track.pos_size() )
480             {
481                 pos0 = pos1;
482                 ++pos_count;
483                 // cout << "count = " << count << endl;
484                 pos1 = track.get_pospt( pos_count );
485             }
486             // cout << "p0 = " << p0.get_time() << " p1 = " << p1.get_time()
487             //      << endl;
488
489             // Advance attitude pointer
490             while ( current_time > att1.get_seconds()
491                     && att_count < track.att_size() )
492             {
493                 att0 = att1;
494                 ++att_count;
495                 // cout << "count = " << count << endl;
496                 att1 = track.get_attpt( att_count );
497             }
498             //  cout << "pos0 = " << pos0.get_seconds()
499             // << " pos1 = " << pos1.get_seconds() << endl;
500
501             double pos_percent;
502             if ( fabs(pos1.get_seconds() - pos0.get_seconds()) < 0.00001 ) {
503                 pos_percent = 0.0;
504             } else {
505                 pos_percent =
506                     (current_time - pos0.get_seconds()) /
507                     (pos1.get_seconds() - pos0.get_seconds());
508             }
509             // cout << "Percent = " << percent << endl;
510             double att_percent;
511             if ( fabs(att1.get_seconds() - att0.get_seconds()) < 0.00001 ) {
512                 att_percent = 0.0;
513             } else {
514                 att_percent =
515                     (current_time - att0.get_seconds()) /
516                     (att1.get_seconds() - att0.get_seconds());
517             }
518             // cout << "Percent = " << percent << endl;
519
520             MIDGpos pos = MIDGInterpPos( pos0, pos1, pos_percent );
521             MIDGatt att = MIDGInterpAtt( att0, att1, att_percent );
522             // cout << current_time << " " << p0.lat_deg << ", " << p0.lon_deg
523             //      << endl;
524             // cout << current_time << " " << p1.lat_deg << ", " << p1.lon_deg
525             //      << endl;
526             // cout << (double)current_time << " " << pos.lat_deg << ", "
527             //      << pos.lon_deg << " " << att.yaw_deg << endl;
528             if ( pos.lat_deg > -500 ) {
529             printf( "%.3f  %.4f %.4f %.1f  %.2f %.2f %.2f\n",
530                     current_time,
531                     pos.lat_deg, pos.lon_deg, pos.altitude_msl,
532                     att.yaw_rad * 180.0 / SG_PI,
533                     att.pitch_rad * 180.0 / SG_PI,
534                     att.roll_rad * 180.0 / SG_PI );
535             }
536
537             send_data( pos, att );
538
539             // Update the elapsed time.
540             static bool first_time = true;
541             if ( first_time ) {
542                 last_time_stamp.stamp();
543                 first_time = false;
544             }
545
546             current_time_stamp.stamp();
547             /* Convert to ms */
548             double elapsed_us = (current_time_stamp - last_time_stamp).toUSecs();
549             if ( elapsed_us < (frame_us - 2000) ) {
550                 double requested_us = (frame_us - elapsed_us) - 2000 ;
551                 ulMilliSecondSleep ( (int)(requested_us / 1000.0) ) ;
552             }
553             current_time_stamp.stamp();
554             while ( (current_time_stamp - last_time_stamp).toUSecs() < frame_us ) {
555                 current_time_stamp.stamp();
556             }
557
558             current_time += (frame_us / 1000000.0);
559             last_time_stamp = current_time_stamp;
560         }
561
562         cout << "Processed " << pos_count << " entries in "
563              << current_time_stamp - start_time << " seconds."
564              << endl;
565     } else if ( serialdev.length() ) {
566         // process incoming data from the serial port
567
568         int count = 0;
569         double current_time = 0.0;
570
571         MIDGpos pos;
572         MIDGatt att;
573
574         uint32_t pos_time = 1;
575         uint32_t att_time = 1;
576
577         // open the serial port device
578         SGSerialPort input( serialdev, 115200 );
579         if ( !input.is_enabled() ) {
580             cout << "Cannot open: " << serialdev << endl;
581             return false;
582         }
583
584         // open up the data log file if requested
585         if ( !outfile.length() ) {
586             cout << "no --outfile <name> specified, cannot capture data!"
587                  << endl;
588             return false;
589         }
590         SGFile output( outfile );
591         if ( !output.open( SG_IO_OUT ) ) {
592             cout << "Cannot open: " << outfile << endl;
593             return false;
594         }
595
596         while ( input.is_enabled() ) {
597             // cout << "looking for next message ..." << endl;
598             int id = track.next_message( &input, &output, &pos, &att );
599             cout << "message id = " << id << endl;
600             count++;
601
602             if ( id == 10 ) {
603                 if ( att.get_msec() > att_time ) {
604                     att_time = att.get_msec();
605                     current_time = att_time;
606                 } else {
607                     cout << "oops att back in time" << endl;
608                 }
609             } else if ( id == 12 ) {
610                 if ( pos.get_msec() > pos_time ) {
611                     pos_time = pos.get_msec();
612                     current_time = pos_time;
613                 } else {
614                     cout << "oops pos back in time" << endl;
615                 }
616             }
617
618             if ( pos.lat_deg > -500 ) {
619             // printf( "%.3f  %.4f %.4f %.1f  %.2f %.2f %.2f\n",
620             //         current_time,
621             //         pos.lat_deg, pos.lon_deg, pos.altitude_msl,
622             //         att.yaw_rad * 180.0 / SG_PI,
623             //         att.pitch_rad * 180.0 / SG_PI,
624             //         att.roll_rad * 180.0 / SG_PI );
625             }
626
627             send_data( pos, att );
628         }
629     }
630
631     return 0;
632 }