]> git.mxchange.org Git - flightgear.git/blob - src/Network/fgcom.cxx
FGCom: Should fix continous mic ON by checking state in main loop instead of listener
[flightgear.git] / src / Network / fgcom.cxx
1 // fgcom.cxx -- FGCom: Voice communication
2 //
3 // Written by Clement de l'Hamaide, started Mai 2013.
4 //
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License as
7 // published by the Free Software Foundation; either version 2 of the
8 // License, or (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful, but
11 // WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 // General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18
19 #ifdef HAVE_CONFIG_H
20 #  include <config.h>
21 #endif
22
23 #include "fgcom.hxx"
24
25 // standard library includes
26 #include <cstdio>
27
28 // simgear includes
29 #include <simgear/compiler.h>
30 #include <simgear/sg_inlines.h>
31 #include <simgear/debug/logstream.hxx>
32 #include <simgear/math/sg_geodesy.hxx>
33 #include <simgear/timing/timestamp.hxx>
34
35 // flightgear includes
36 #include <Main/fg_props.hxx>
37 #include <Main/globals.hxx>
38 #include <ATC/CommStation.hxx>
39 #include <Airports/airport.hxx>
40 #include <Navaids/navlist.hxx>
41
42 #include <utils/iaxclient/lib/iaxclient.h>
43
44
45 #define NUM_CALLS 4
46 #define MAX_RANGE 100.0
47 #define MIN_RANGE  20.0
48 #define DEFAULT_SERVER "fgcom.flightgear.org"
49 #define IAX_DELAY 300  // delay between calls in milliseconds
50 #define TEST_FREQ 910.00
51 #define NULL_ICAO "ZZZZ"
52
53 const int special_freq[] = { // Define some freq who need to be used with NULL_ICAO
54         910000,
55         911000,
56         700000,
57         123450,
58         122750,
59         121500,
60         123500,
61         121000,
62         723340 };
63
64
65 FGCom::FGCom() :
66     _register(true)
67 {
68   _listener_active = 0;
69 }
70
71
72
73 FGCom::~FGCom()
74 {
75 }
76
77
78
79 void FGCom::bind()
80 {
81   SGPropertyNode *node     = fgGetNode("/sim/fgcom", 0, true);
82   _test_node               = node->getChild( "test", 0, true );
83   _server_node             = node->getChild( "server", 0, true );
84   _enabled_node            = node->getChild( "enabled", 0, true );
85   _micBoost_node           = node->getChild( "mic-boost", 0, true );
86   _micLevel_node           = node->getChild( "mic-level", 0, true );
87   _speakerLevel_node       = node->getChild( "speaker-level", 0, true );
88   _selectedInput_node      = node->getChild( "device-input", 0, true );
89   _selectedOutput_node     = node->getChild( "device-output", 0, true );
90
91   SGPropertyNode *reg_node = node->getChild("register", 0, true);
92   _register_node           = reg_node->getChild( "enabled", 0, true );
93   _username_node           = reg_node->getChild( "username", 0, true );
94   _password_node           = reg_node->getChild( "password", 0, true );
95
96   //_nav0_node               = fgGetNode("/instrumentation/nav[0]/frequencies/selected-mhz", true);
97   //_nav1_node               = fgGetNode("/instrumentation/nav[1]/frequencies/selected-mhz", true);
98   _comm0_node              = fgGetNode("/instrumentation/comm[0]/frequencies/selected-mhz", true);
99   //_comm1_node              = fgGetNode("/instrumentation/comm[1]/frequencies/selected-mhz", true);
100   _ptt0_node               = fgGetNode("/instrumentation/comm[0]/ptt", true); //FIXME: what about /instrumentation/comm[1]/ptt ?
101   _callsign_node           = fgGetNode("/sim/multiplay/callsign", true);
102
103   // Set default values if not provided
104   if ( !_enabled_node->hasValue() )
105       _enabled_node->setBoolValue(true);
106
107   if ( !_test_node->hasValue() )
108       _test_node->setBoolValue(false);
109
110   if ( !_micBoost_node->hasValue() )
111       _micBoost_node->setIntValue(1);
112
113   if ( !_server_node->hasValue() )
114       _server_node->setStringValue(DEFAULT_SERVER);
115
116   if ( !_speakerLevel_node->hasValue() )
117       _speakerLevel_node->setFloatValue(1.0);
118
119   if ( !_micLevel_node->hasValue() )
120       _micLevel_node->setFloatValue(1.0);
121
122   if ( !_register_node->hasValue() )
123       _register_node->setBoolValue(false);
124
125   if ( !_username_node->hasValue() )
126       _username_node->setStringValue("guest");
127
128   if ( !_password_node->hasValue() )
129       _password_node->setStringValue("guest");
130
131   _selectedOutput_node->addChangeListener(this);
132   _selectedInput_node->addChangeListener(this);
133   _speakerLevel_node->addChangeListener(this);
134   _micBoost_node->addChangeListener(this);
135   _micLevel_node->addChangeListener(this);
136   _enabled_node->addChangeListener(this);
137   _comm0_node->addChangeListener(this);
138   //_comm1_node->addChangeListener(this);
139   //_nav0_node->addChangeListener(this);
140   //_nav1_node->addChangeListener(this);
141   //_ptt0_node->addChangeListener(this);
142   _test_node->addChangeListener(this);
143 }
144
145
146
147 void FGCom::unbind()
148 {
149 }
150
151
152
153 void FGCom::init()
154 {
155   _enabled          = _enabled_node->getBoolValue();
156   _server           = _server_node->getStringValue();
157   _register         = _register_node->getBoolValue();
158   _username         = _username_node->getStringValue();
159   _password         = _password_node->getStringValue();
160
161   _currentComm0     = _comm0_node->getDoubleValue();
162   //_currentComm1     = _comm1_node->getDoubleValue();
163   //_currentNav0      = _nav0_node->getDoubleValue();
164   //_currentNav1      = _nav1_node->getDoubleValue();
165
166   _comm0Changed     = false;
167   //_comm1Changed     = false;
168   //_nav0Changed      = false;
169   //_nav1Changed      = false;
170 }
171
172
173
174 void FGCom::postinit()
175 {
176     if( !_enabled ) {
177         return;
178     }
179     
180     //WARNING: this _must_ be executed after sound system is totally initialized !
181     if( iaxc_initialize(NUM_CALLS) ) {
182         SG_LOG(SG_IO, SG_ALERT, "FGCom: cannot initialize iaxclient!");
183         _enabled = false;
184         return;
185     }
186     
187     // FIXME: To be implemented in IAX audio driver
188     //iaxc_mic_boost_set( _micBoost_node->getIntValue() );
189     iaxc_set_formats( IAXC_FORMAT_GSM, IAXC_FORMAT_GSM );
190     iaxc_start_processing_thread ();
191     
192     if ( _register ) {
193       _regId = iaxc_register( const_cast<char*>(_username.c_str()),
194                               const_cast<char*>(_password.c_str()),
195                               const_cast<char*>(_server.c_str()) );
196         if( _regId == -1 ) {
197             SG_LOG(SG_IO, SG_INFO, "FGCom: cannot register iaxclient!");
198             return;
199         }
200     }
201
202     /*
203       Here we will create the list of available audio devices
204       Each audio device has a name, an ID, and a list of capabilities
205       If an audio device can output sound, available-output=true 
206       If an audio device can input sound, available-input=true 
207
208       /sim/fgcom/selected-input (int)
209       /sim/fgcom/selected-output (int)
210
211       /sim/fgcom/device[n]/id (int)
212       /sim/fgcom/device[n]/name (string)
213       /sim/fgcom/device[n]/available-input (bool)
214       /sim/fgcom/device[n]/available-output (bool)
215     */
216
217     //FIXME: OpenAL driver use an hard-coded device
218     //       so all following is unused finally until someone
219     //       implement "multi-device" support in IAX audio driver
220     SGPropertyNode *node     = fgGetNode("/sim/fgcom", 0, true);
221
222     struct iaxc_audio_device *devs;
223     int nDevs, input, output, ring;
224
225     iaxc_audio_devices_get(&devs,&nDevs, &input, &output, &ring);
226
227     for(int i=0; i<nDevs; i++ ) {
228       SGPropertyNode *in_node = node->getChild("device", i, true);
229
230       // devID
231       _deviceID_node[i] = in_node->getChild("id", 0, true);
232       _deviceID_node[i]->setIntValue(devs[i].devID);
233
234       // name
235       _deviceName_node[i] = in_node->getChild("name", 0, true);
236       _deviceName_node[i]->setStringValue(devs[i].name);
237
238       // input capability
239       _deviceInput_node[i] = in_node->getChild("available-input", 0, true);
240       if( devs[i].capabilities & IAXC_AD_INPUT )
241         _deviceInput_node[i]->setBoolValue(true);
242       else 
243         _deviceInput_node[i]->setBoolValue(false);
244
245       // output capability
246       _deviceOutput_node[i] = in_node->getChild("available-output", 0, true);
247       if( devs[i].capabilities & IAXC_AD_OUTPUT )
248         _deviceOutput_node[i]->setBoolValue(true);
249       else 
250         _deviceOutput_node[i]->setBoolValue(false);
251
252       // use default device at start
253       if( devs[i].capabilities & IAXC_AD_INPUT_DEFAULT )
254         _selectedInput_node->setIntValue(devs[i].devID);
255       if( devs[i].capabilities & IAXC_AD_OUTPUT_DEFAULT )
256         _selectedOutput_node->setIntValue(devs[i].devID);
257     }
258
259     // Mute the mic and set speaker at start
260     iaxc_input_level_set( 0.0 );
261     iaxc_output_level_set( _speakerLevel_node->getFloatValue() );
262
263     iaxc_millisleep(50);
264
265     // Do the first call at start
266     const double freq = _comm0_node->getDoubleValue();
267     _currentFreqKhz = 10 * static_cast<int>(freq * 100 + 0.25);
268     std::string num = computePhoneNumber(freq, getAirportCode(freq));
269     if( !num.empty() ) {
270       SG_LOG( SG_IO, SG_INFO, "FGCom comm[0] number=" << num );
271       _callComm0 = iaxc_call(num.c_str());
272     }
273     if( _callComm0 == -1 )
274       SG_LOG( SG_IO, SG_ALERT, "FGCom cannot call selected freq" );
275 }
276
277
278
279 void FGCom::updateCall(bool& changed, int& callNo, double freqMHz)
280 {
281
282     _currentFreqKhz = 10 * static_cast<int>(freqMHz * 100 + 0.25);
283
284     if (!changed) {
285         if( !isInRange(freqMHz) ) {
286             iaxc_dump_call_number(callNo);
287             callNo = -1;
288             return;
289         } else {
290             if(callNo != -1)
291                 return;
292         }
293     }
294     
295     SG_LOG( SG_IO, SG_INFO, "FGCom manage change" );
296     changed = false; // FIXME, out-params are confusing
297
298     if( callNo != -1 ) {
299         iaxc_dump_call_number( callNo );
300         callNo = -1;
301     }
302
303     if(_p.elapsedMSec() > IAX_DELAY) {
304         std::string num = computePhoneNumber(freqMHz, getAirportCode(freqMHz));
305         if( !isInRange(freqMHz) )
306             return;
307         if( !num.empty() ) {
308             SG_LOG( SG_IO, SG_INFO, "FGCom number=" << num );
309             callNo = iaxc_call_ex(num.c_str(), _callsign.c_str(), NULL, 0 /* no video */);
310
311             if( callNo == -1 )
312                 SG_LOG( SG_IO, SG_ALERT, "FGCom cannot call selected freq" );
313         }
314     } else {
315         changed = true;
316     }
317 }
318
319
320
321 void FGCom::update(double dt)
322 {
323     if ( !_enabled ) {
324         return;
325     }
326
327     if( _ptt0_node->getBoolValue() ) {
328       iaxc_input_level_set( _micLevel_node->getFloatValue() ); //0.0 = min , 1.0 = max
329       iaxc_output_level_set( 0.0 );
330     } else {
331       iaxc_input_level_set( 0.0 );
332       iaxc_output_level_set( _speakerLevel_node->getFloatValue() );
333     }
334
335     // For now we manage FGCom for only one freq because IAXClient
336     // is not able to handle multiple calls at same time.
337     updateCall(_comm0Changed, _callComm0, _comm0_node->getDoubleValue());
338     // updateCall(_comm1Changed, _callComm1, _comm1_node->getDoubleValue());
339     // updateCall(_nav0Changed, _callNav0, _nav0_node->getDoubleValue());
340     // updateCall(_nav1Changed, _callNav1, _nav1_node->getDoubleValue());
341 }
342
343
344
345 void FGCom::shutdown()
346 {
347     if( !_enabled ) {
348         return;
349     }
350     
351   SG_LOG( SG_IO, SG_INFO, "FGCom shutdown()" );
352   _enabled = false;
353
354   iaxc_unregister(_regId);
355   iaxc_stop_processing_thread();
356   iaxc_shutdown();
357 }
358
359
360
361 void FGCom::valueChanged(SGPropertyNode *prop)
362 {
363   if (prop == _enabled_node) {
364     SG_LOG( SG_IO, SG_INFO, "FGCom enabled= " << prop->getBoolValue() );
365     if( prop->getBoolValue() ) {
366       init();
367       postinit();
368     } else {
369       shutdown();
370     }
371     return;
372   }
373
374   /*if (prop == _ptt0_node && _enabled) {
375     if( _ptt0_node->getBoolValue() ) {
376       iaxc_input_level_set( _micLevel_node->getFloatValue() ); //0.0 = min , 1.0 = max
377       iaxc_output_level_set( 0.0 );
378     } else {
379       iaxc_input_level_set( 0.0 );
380       iaxc_output_level_set( _speakerLevel_node->getFloatValue() );
381     }
382   }*/
383
384   if (prop == _test_node) {
385     SG_LOG( SG_IO, SG_INFO, "FGCom test= " << prop->getBoolValue() );
386     testMode( prop->getBoolValue() );
387     return;
388   }
389
390   //FIXME: not implemented in IAX audio driver (audio_openal.c)
391   if (prop == _micBoost_node && _enabled) {
392     int micBoost = prop->getIntValue();
393     SG_LOG( SG_IO, SG_INFO, "FGCom mic-boost= " << micBoost );
394     SG_CLAMP_RANGE<int>( micBoost, 0, 1 );
395     iaxc_mic_boost_set( micBoost ) ; // 0 = enabled , 1 = disabled
396     return;
397   }
398
399   //FIXME: not implemented in IAX audio driver (audio_openal.c)
400   if ((prop == _selectedInput_node || prop == _selectedOutput_node) && _enabled) {
401     int selectedInput = _selectedInput_node->getIntValue();
402     int selectedOutput = _selectedOutput_node->getIntValue();
403     SG_LOG( SG_IO, SG_INFO, "FGCom selected-input= " << selectedInput );
404     SG_LOG( SG_IO, SG_INFO, "FGCom selected-output= " << selectedOutput );
405     iaxc_audio_devices_set(selectedInput, selectedOutput, 0);
406     return;
407   }
408
409   if (_listener_active)
410     return;
411
412   _listener_active++;
413
414   if (prop == _speakerLevel_node && _enabled) {
415     float speakerLevel = prop->getFloatValue();
416     SG_LOG( SG_IO, SG_INFO, "FGCom speaker-level= " << speakerLevel );
417     SG_CLAMP_RANGE<float>( speakerLevel, 0.0, 1.0 );
418     _speakerLevel_node->setFloatValue(speakerLevel);
419     //iaxc_output_level_set(speakerLevel);
420   }
421
422   if (prop == _micLevel_node && _enabled) {
423     float micLevel = prop->getFloatValue();
424     SG_LOG( SG_IO, SG_INFO, "FGCom mic-level= " << micLevel );
425     SG_CLAMP_RANGE<float>( micLevel, 0.0, 1.0 );
426     _micLevel_node->setFloatValue(micLevel);
427     //iaxc_input_level_set(micLevel);
428   }
429
430   if (prop == _comm0_node) {
431     if( _currentComm0 != prop->getDoubleValue() ) {
432       SG_LOG( SG_IO, SG_INFO, "FGCom comm[0]/freq= " << prop->getDoubleValue() );
433       _currentComm0 = prop->getDoubleValue();
434       _p.stamp();
435       _comm0Changed = true;
436     }
437   }
438 /*
439   if (prop == _comm1_node) {
440     if( _currentComm1 != prop->getDoubleValue() ) {
441       SG_LOG( SG_IO, SG_INFO, "FGCom comm[1]/freq= " << prop->getDoubleValue() );
442       _currentComm1 = prop->getDoubleValue();
443       _p.stamp();
444       _comm1Changed = true;
445     }
446   }
447
448   if (prop == _nav0_node) {
449     if( _currentNav0 != prop->getDoubleValue() ) {
450       SG_LOG( SG_IO, SG_INFO, "FGCom nav[0]/freq= " << prop->getDoubleValue() );
451       _currentNav0 = prop->getDoubleValue();
452       _nav0Changed = true;
453     }
454   }
455
456   if (prop == _nav1_node) {
457     if( _currentNav1 != prop->getDoubleValue() ) {
458       SG_LOG( SG_IO, SG_INFO, "FGCom nav[1]/freq= " << prop->getDoubleValue() );
459       _currentNav1 = prop->getDoubleValue();
460       _nav1Changed = true;
461     }
462   }
463 */
464
465   _listener_active--;
466 }
467
468
469
470 void FGCom::testMode(bool testMode)
471 {
472   if(testMode) {
473     _enabled = false;
474     iaxc_dump_call_number(_callComm0);
475     iaxc_input_level_set( _micLevel_node->getFloatValue() );
476     iaxc_output_level_set( _speakerLevel_node->getFloatValue() );
477     std::string num = computePhoneNumber(TEST_FREQ, NULL_ICAO);
478     if( num.size() > 0 ) {
479       SG_LOG( SG_IO, SG_INFO, "FGCom test mode =" << num );
480       iaxc_millisleep(IAX_DELAY);
481       _callComm0 = iaxc_call(num.c_str());
482     }
483     if( _callComm0 == -1 )
484       SG_LOG( SG_IO, SG_ALERT, "FGCom cannot call selected freq (test mode)" );
485   } else {
486     iaxc_dump_call_number(_callComm0);
487     iaxc_millisleep(IAX_DELAY);
488     _callComm0 = -1;
489     _enabled = true;
490   }
491 }
492
493
494
495 /*
496   \param freq The requested frequency e.g 120.825
497   \return The ICAO code as string e.g LFMV
498 */
499
500 std::string FGCom::getAirportCode(const double& freq)
501 {
502   SGGeod aircraftPos = globals->get_aircraft_position();
503
504   for(size_t i=0; i<sizeof(special_freq)/sizeof(special_freq[0]); i++) { // Check if it's a special freq
505     if(special_freq[i] == _currentFreqKhz) {
506       SG_LOG( SG_IO, SG_INFO, "FGCom getAirportCode: " << freq << " is specially associated to " << NULL_ICAO );
507       return NULL_ICAO;
508     }
509   }
510
511   flightgear::CommStation* apt = flightgear::CommStation::findByFreq(_currentFreqKhz, aircraftPos);
512   if( !apt ) {
513     SG_LOG( SG_IO, SG_INFO, "FGCom getAirportCode: not found" );
514     return std::string();
515   }
516   SG_LOG( SG_IO, SG_INFO, "FGCom getAirportCode: found " << apt->airport()->ident() );
517
518   _aptPos = apt->geod();
519   return apt->airport()->ident();
520 }
521
522
523
524 /*
525   \param freq The requested frequency e.g 112.7
526   \return The ICAO code as string e.g ITS
527 */
528 /*
529 std::string FGCom::getVorCode(const double& freq) const
530 {
531   SGGeod aircraftPos = globals->get_aircraft_position();
532   FGNavList::TypeFilter filter(FGPositioned::VOR);
533
534   FGNavRecord* vor = FGNavList::findByFreq( freq, aircraftPos, &filter);
535   if( !vor ) {
536     SG_LOG( SG_IO, SG_INFO, "FGCom getVorCode: not found" );
537     return std::string();
538   }
539   SG_LOG( SG_IO, SG_INFO, "FGCom getVorCode: found " << vor->get_ident(); );
540
541   return vor->get_ident();
542 }
543 */
544
545
546 /*
547   \param freq The requested frequency e.g 120.825
548   \param iaco The associated ICAO code e.g LFMV
549   \return The phone number as string i.e username:password@fgcom.flightgear.org/0176707786120825
550 */
551
552 std::string FGCom::computePhoneNumber(const double& freq, const std::string& icao) const
553 {
554   if( icao.empty() )
555     return std::string(); 
556
557   char phoneNumber[256];
558   char exten[32];
559   char tmp[5];
560
561   /*Convert ICAO to ASCII */
562   sprintf( tmp, "%4s", icao.c_str() );
563
564   /*Built the phone number */
565   sprintf( exten,
566            "%02d%02d%02d%02d%02d%06d",
567            01,
568            tmp[0],
569            tmp[1],
570            tmp[2],
571            tmp[3],
572            (int) (freq * 1000 + 0.5) );
573   exten[16] = '\0';
574
575   snprintf( phoneNumber,
576             sizeof (phoneNumber),
577             "%s:%s@%s/%s",
578             _username.c_str(),
579             _password.c_str(),
580             _server.c_str(),
581             exten);
582
583   return phoneNumber;
584 }
585
586
587
588 /*
589   \return A boolean value, 1=in range, 0=out of range
590 */
591
592 bool FGCom::isInRange(const double &freq) const
593 {
594     for(size_t i=0; i<sizeof(special_freq)/sizeof(special_freq[0]); i++) { // Check if it's a special freq
595       if( (special_freq[i]) == _currentFreqKhz ) {
596         return 1;
597       }
598     }
599
600     SGGeod acftPos = globals->get_aircraft_position();
601     double distNm = SGGeodesy::distanceNm(_aptPos, acftPos);
602     double delta_elevation_ft = fabs(acftPos.getElevationFt() - _aptPos.getElevationFt());
603     double rangeNm = 1.23 * sqrt(delta_elevation_ft);
604
605     if (rangeNm > MAX_RANGE) rangeNm = MAX_RANGE;
606     if (rangeNm < MIN_RANGE) rangeNm = MIN_RANGE;
607     if( distNm > rangeNm )   return 0;
608     return 1;
609 }
610
611