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