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