2 * fgcom - VoIP-Client for the FlightGear-Radio-Infrastructure
4 * This program realizes the usage of the VoIP infractructure based
5 * on flight data which is send from FlightGear with an external
6 * protocol to this application.
8 * Clement de l'Hamaide - Jan 2014
9 * Re-writting of FGCom standalone
11 * This program is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU General Public License as
13 * published by the Free Software Foundation; either version 2 of the
14 * License, or (at your option) any later version.
16 * This program is distributed in the hope that it will be useful, but
17 * WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
32 #include <simgear/sg_inlines.h>
33 #include <simgear/math/SGMath.hxx>
34 #include <simgear/io/raw_socket.hxx>
35 #include <simgear/misc/strutils.hxx>
36 #include <simgear/debug/logstream.hxx>
37 #include <simgear/timing/timestamp.hxx>
39 #include <3rdparty/iaxclient/lib/iaxclient.h>
42 #include "positions.hxx" // provides _positionsData[];
46 int _currentFreqKhz = -1;
49 int _registrationId = -1;
50 bool _libInitialized = false;
53 bool _connected = false;
54 double _frequency = -1;
56 double _silenceThd = -35.0;
57 std::string _app = "FGCOM-";
58 std::string _host = "127.0.0.1";
59 std::string _server = "fgcom.flightgear.org";
60 std::string _airport = "ZZZZ";
61 std::string _callsign = "guest";
62 std::string _username = "guest";
63 std::string _password = "guest";
67 std::multimap<int, Airport> _airportsData;
69 const int special_freq[] = { // Define some freq who need to be used with icao = ZZZZ
82 int main(int argc, char** argv)
85 signal(SIGTERM, quit);
87 simgear::requestConsole();
88 sglog().setLogLevels(SG_ALL, SG_INFO);
89 _app += FGCOM_VERSION;
93 for(int count = 1; count < argc; count++) {
94 std::string item = argv[count];
95 std::string option = item.substr(2, item.find("=")-2);
96 std::string value = item.substr(item.find("=")+1, item.size());
97 if(option == "server") _server = value;
98 if(option == "host") _host = value;
99 if(option == "port") _port = atoi(value.c_str());
100 if(option == "callsign") _callsign = value;
101 if(option == "frequency") _frequency = atof(value.c_str());
102 if(option == "atis") _atis = atof(value.c_str());
103 if(option == "airport") _airport = simgear::strutils::uppercase(value);
104 if(option == "username") _username = value;
105 if(option == "password") _password = value;
106 if(option == "silence-threshold") _silenceThd = atof(value.c_str());
107 if(option == "debug") sglog().setLogLevels(SG_ALL, SG_DEBUG);
108 if(option == "help") return usage();
109 if(option == "version") return version();
112 if(_frequency == 910.000)
114 if(_frequency <= 136.975 && _frequency >= 118.000)
116 if(_atis <= 136.975 && _atis >= 118.000 && _airport != "ZZZZ")
119 SG_LOG(SG_GENERAL, SG_INFO, "FGCom " << FGCOM_VERSION << " compiled " << __DATE__
120 << ", at " << __TIME__ );
121 SG_LOG(SG_GENERAL, SG_INFO, "For help usage, use --help");
122 SG_LOG(SG_GENERAL, SG_INFO, "Starting FGCom session as " << _username << ":xxxxxxxxx@" << _server);
124 if( !(_libInitialized = lib_init()) )
127 if (_username != "guest" && _password != "guest")
128 _registrationId = lib_registration();
131 SG_LOG( SG_GENERAL, SG_DEBUG, "Entering main loop in mode PILOT" );
133 simgear::Socket::initSockets();
134 simgear::Socket sgSocket;
135 sgSocket.open(false);
136 sgSocket.bind(_host.c_str(), _port);
137 sgSocket.setBlocking(false);
138 lib_setVolume(0.0, 1.0);
139 static char currentPacket[MAXBUFLEN+2], previousPacket[MAXBUFLEN+2];
140 struct Data currentData, previousData, previousPosData;
141 double currentFreq = -1, previousFreq = -1;
142 std::string currentIcao = "";
143 ActiveComm activeComm = COM1;
145 _airportsData = getAirportsData();
146 SG_LOG(SG_GENERAL, SG_INFO, "");
149 int bytes = sgSocket.recv(currentPacket, sizeof(currentPacket)-1, 0);
153 currentPacket[bytes] = '\0';
154 if( strcmp(currentPacket, previousPacket) != 0 ) {
155 std::string packet(currentPacket);
156 std::vector<std::string> properties = simgear::strutils::split(packet, ",");
157 for(size_t i=0; i < properties.size(); i++) {
158 std::vector<std::string> prop = simgear::strutils::split(properties[i], "=");
159 if(prop[0] == "PTT") currentData.ptt = atoi(prop[1].c_str());
160 if(prop[0] == "LAT") currentData.lat = atof(prop[1].c_str());
161 if(prop[0] == "LON") currentData.lon = atof(prop[1].c_str());
162 if(prop[0] == "ALT") currentData.alt = atof(prop[1].c_str());
163 if(prop[0] == "COM1_FRQ") currentData.com1 = atof(prop[1].c_str());
164 if(prop[0] == "COM2_FRQ") currentData.com2 = atof(prop[1].c_str());
165 if(prop[0] == "OUTPUT_VOL") currentData.outputVol = atof(prop[1].c_str());
166 if(prop[0] == "SILENCE_THD") currentData.silenceThd = atof(prop[1].c_str());
167 if(prop[0] == "CALLSIGN") currentData.callsign = prop[1];
170 if(currentData.ptt != previousData.ptt) {
171 if(currentData.ptt == 2) {
172 if(activeComm == COM1) {
174 currentFreq = currentData.com2;
177 currentFreq = currentData.com1;
179 SG_LOG( SG_GENERAL, SG_INFO, "Select radio " << activeComm << " on " << currentFreq << " MHz" );
180 } else if(currentData.ptt) {
181 SG_LOG( SG_GENERAL, SG_INFO, "[SPEAK] unmute mic, mute speaker" );
182 lib_setVolume(1.0, 0.0);
184 SG_LOG( SG_GENERAL, SG_INFO, "[LISTEN] mute mic, unmute speaker" );
185 lib_setVolume(0.0, currentData.outputVol);
189 if(currentData.outputVol != previousData.outputVol)
190 lib_setVolume(0.0, currentData.outputVol);
192 if(currentData.silenceThd != previousData.silenceThd)
193 lib_setSilenceThreshold(currentData.silenceThd);
195 if(currentData.callsign != previousData.callsign)
196 lib_setCallerId(currentData.callsign);
198 if(currentData.com1 != previousData.com1 && activeComm == COM1) {
199 currentFreq = currentData.com1;
200 SG_LOG( SG_GENERAL, SG_INFO, "Select frequency " << currentFreq << " MHz on radio " << activeComm );
203 if(currentData.com2 != previousData.com2 && activeComm == COM2) {
204 currentFreq = currentData.com2;
205 SG_LOG( SG_GENERAL, SG_INFO, "Select frequency " << currentFreq << " MHz on radio " << activeComm );
208 if(previousFreq != currentFreq || currentData.callsign != previousData.callsign) {
209 _currentFreqKhz = 10 * static_cast<int>(currentFreq * 100 + 0.25);
210 currentIcao = getClosestAirportForFreq(currentFreq, currentData.lat, currentData.lon, currentData.alt);
212 if(isInRange(currentIcao, currentData.lat, currentData.lon, currentData.alt)) {
213 _connected = lib_call(currentIcao, currentFreq);
214 SG_LOG( SG_GENERAL, SG_INFO, "Connecting " << currentIcao << " on " << currentFreq << " MHz" );
217 _connected = lib_hangup();
218 SG_LOG( SG_GENERAL, SG_INFO, "Disconnecting " << currentIcao << " on " << currentFreq << " MHz (out of range)" );
223 if( currentData.lat <= previousPosData.lat - 0.05 ||
224 currentData.lon <= previousPosData.lon - 0.05 ||
225 currentData.alt <= previousPosData.alt - 50.0 ||
226 currentData.lat >= previousPosData.lat + 0.05 ||
227 currentData.lon >= previousPosData.lon + 0.05 ||
228 currentData.alt >= previousPosData.alt + 50.0) {
230 currentIcao = getClosestAirportForFreq(currentFreq, currentData.lat, currentData.lon, currentData.alt);
232 if(!isInRange(currentIcao, currentData.lat, currentData.lon, currentData.alt)) {
233 _connected = lib_hangup();
234 SG_LOG( SG_GENERAL, SG_INFO, "Disconnecting " << currentIcao << " on " << currentFreq << " MHz (out of range)" );
237 if(isInRange(currentIcao, currentData.lat, currentData.lon, currentData.alt)) {
238 _connected = lib_call(currentIcao, currentFreq);
239 SG_LOG( SG_GENERAL, SG_INFO, "Connecting " << currentIcao << " on " << currentFreq << " MHz" );
242 previousPosData = currentData;
244 previousFreq = currentFreq;
245 previousData = currentData;
247 strcpy(previousPacket, currentPacket);
250 } else { // if(mode == PILOT)
251 int sessionDuration = 1000;
254 SG_LOG( SG_GENERAL, SG_DEBUG, "Entering main loop in mode OBS (max duration: 6 hours)" );
255 sessionDuration *= 2160; // 6 hours for OBS mode
256 lib_setVolume(0.0, 1.0);
257 lib_setCallerId("::OBS::");
258 num = computePhoneNumber(_frequency, _airport);
260 lib_setVolume(1.0, 1.0);
262 sessionDuration *= 65; // 65 seconds for TEST mode
263 SG_LOG( SG_GENERAL, SG_DEBUG, "Entering main loop in mode TEST (max duration: 65 seconds)" );
265 num = computePhoneNumber(_frequency, _airport);
266 } else if(mode == ATC) {
267 sessionDuration *= 45; // 45 seconds for ATC mode
268 SG_LOG( SG_GENERAL, SG_DEBUG, "Entering main loop in mode ATC (max duration: 45 seconds)" );
269 num = computePhoneNumber(_atis, _airport, true);
272 _connected = lib_directCall(_airport, _frequency, num);
274 while (_p.elapsedMSec() <= sessionDuration && _running){
275 SGTimeStamp::sleepForMSec(2000);
284 // function: getAirportsData
285 // action: parse positionsData.hxx then build multimap
287 std::multimap<int, Airport> getAirportsData()
289 std::vector<std::string> lines;
290 std::multimap<int, Airport> aptData;
291 SG_LOG(SG_GENERAL, SG_INFO, "Loading airports information...");
293 for(size_t i=0; i < sizeof(_positionsData)/sizeof(*_positionsData); i++) { // _positionsData is provided by positions.hxx
294 std::vector<std::string> entries = simgear::strutils::split(_positionsData[i], ",");
295 if(entries.size() == 6) {
296 // [0]=ICAO, [1]=Frequency, [2]=Latitude, [3]=Longitude, [4]=ID/Type, [5]=Name
297 std::string entryIcao = entries[0];
298 double entryFreq = atof(entries[1].c_str());
299 double entryLat = atof(entries[2].c_str());
300 double entryLon = atof(entries[3].c_str());
301 std::string entryType = entries[4];
302 std::string entryName = entries[5];
304 int aptFreqKhz = 10 * static_cast<int>(entryFreq * 100 + 0.25);
306 apt.icao = entryIcao;
307 apt.frequency = entryFreq;
308 apt.latitude = entryLat;
309 apt.longitude = entryLon;
310 apt.type = entryType;
311 apt.name = entryName;
312 aptData.insert( std::pair<int, Airport>(aptFreqKhz, apt) );
318 // function: orderByDistanceNm
319 // action: sort airportsInRange vector by distanceNm ASC in getClosestAirportForFreq()
321 bool orderByDistanceNm(Airport a, Airport b)
323 return a.distanceNm < b.distanceNm;
326 // function: gestClosestAircraftForFreq
327 // action: return ICAO of closest airport with given frequency and define his position
329 std::string getClosestAirportForFreq(double freq, double acftLat, double acftLon, double acftAlt)
331 for(size_t i=0; i<sizeof(special_freq)/sizeof(special_freq[0]); i++) { // Check if it's a special freq
332 if( special_freq[i] == _currentFreqKhz )
333 return std::string("ZZZZ");
336 std::string icao = "";
339 int freqKhz = 10 * static_cast<int>(freq * 100 + 0.25);
340 SGGeod acftPos = SGGeod::fromDegFt(acftLon, acftLat, acftAlt);
341 std::vector<Airport> airportsInRange;
343 std::pair <std::multimap<int, Airport>::iterator, std::multimap<int, Airport>::iterator> ret;
344 ret = _airportsData.equal_range(freqKhz);
345 for (std::multimap<int, Airport>::iterator it=ret.first; it!=ret.second; ++it) {
346 SGGeod aptPos = SGGeod::fromDeg(it->second.longitude, it->second.latitude);
347 double distNm = SGGeodesy::distanceNm(aptPos, acftPos);
348 if(distNm <= _maxRange){
349 it->second.distanceNm = distNm;
350 airportsInRange.push_back(it->second);
354 if(!airportsInRange.size())
357 std::sort(airportsInRange.begin(), airportsInRange.end(), orderByDistanceNm);
359 aptLon = airportsInRange[0].longitude;
360 aptLat = airportsInRange[0].latitude;
361 icao = airportsInRange[0].icao;
362 _airportPos = SGGeod::fromDeg(aptLon, aptLat);
364 SG_LOG(SG_GENERAL, SG_INFO, "Airport " << airportsInRange[0].icao << " " << airportsInRange[0].name << " - "
365 << airportsInRange[0].type << " on " << airportsInRange[0].frequency
366 << " - is in range " << airportsInRange[0].distanceNm << "nm ("
367 << (SG_NM_TO_METER*airportsInRange[0].distanceNm)/1000 <<"km)");
371 // function: isInRange
372 // action: return TRUE if airport/freq is in range, else return FALSE
374 bool isInRange(std::string icao, double acftLat, double acftLon, double acftAlt)
376 for(size_t i=0; i<sizeof(special_freq)/sizeof(special_freq[0]); i++) { // Check if it's a special freq
377 if( special_freq[i] == _currentFreqKhz )
384 SGGeod acftPos = SGGeod::fromDegFt(acftLon, acftLat, acftAlt);
385 double distNm = SGGeodesy::distanceNm(_airportPos, acftPos);
386 double delta_elevation_ft = fabs(acftPos.getElevationFt() - _airportPos.getElevationFt());
387 double rangeNm = 1.23 * sqrt(delta_elevation_ft);
389 if (rangeNm > _maxRange) rangeNm = _maxRange;
390 if (rangeNm < _minRange) rangeNm = _minRange;
391 if( distNm > rangeNm ) return false;
396 // action: set _running flag to false
400 SG_LOG( SG_GENERAL, SG_INFO, "Exiting FGCom" );
404 SG_LOG(SG_GENERAL, SG_INFO, "You can close the terminal now");
409 // action: display FGCom usage then quit
413 std::cout << "FGCom " << FGCOM_VERSION << " usage:" << std::endl;
414 std::cout << " --server=fgcom.flightgear.org - Server to connect" << std::endl;
415 std::cout << " --host=127.0.0.1 - Host to listen i.e where FG is running" << std::endl;
416 std::cout << " --port=16661 - Port to use" << std::endl;
417 std::cout << " --callsign=guest - Callsign during session e.g F-ELYD" << std::endl;
418 std::cout << " --frequency=xxx.xxx - Frequency e.g 120.500" << std::endl;
419 std::cout << " --airport=YYYY - ICAO of airport e.g KSFO" << std::endl;
420 std::cout << " --username=guest - Username for registration" << std::endl;
421 std::cout << " --password=guest - Password for registration" << std::endl;
422 std::cout << " --silence-threshold=-35 - Silence threshold in dB (-60 < range < 0 )" << std::endl;
423 std::cout << " --debug - Enable debug output" << std::endl;
424 std::cout << " --help - Show this message" << std::endl;
425 std::cout << " --version - Show version" << std::endl;
426 std::cout << "" << std::endl;
427 std::cout << " None of these options are required, you can simply start FGCom without option at all: it works" << std::endl;
428 std::cout << " For further information, please visit: http://wiki.flightgear.org/FGCom_3.0" << std::endl;
429 std::cout << "" << std::endl;
430 std::cout << " About silence-threshold:" << std::endl;
431 std::cout << " This is the limit, in dB, when FGCom consider no voice in your microphone." << std::endl;
432 std::cout << " --silence-threshold=-60 is similar to micro always ON" << std::endl;
433 std::cout << " --silence-threshold=0 is similar to micro always OFF" << std::endl;
434 std::cout << " Default value is -35.0 dB" << std::endl;
435 std::cout << "" << std::endl;
436 std::cout << " In order to make an echo-test, you have to start FGCom like:" << std::endl;
437 std::cout << " fgcom --frequency=910" << std::endl;
438 std::cout << "" << std::endl;
439 std::cout << " In order to listen a frequency, you have to start FGCom like:" << std::endl;
440 std::cout << " fgcom --frequency=xxx.xxx --airport=YYYY" << std::endl;
441 std::cout << " where xxx.xxx is the frequency of the ICAO airport YYYY that you want to listen to" << std::endl;
442 std::cout << "" << std::endl;
443 std::cout << " In order to record an ATIS message, you have to start FGCom like:" << std::endl;
444 std::cout << " fgcom --atis=xxx.xxx --airport=YYYY" << std::endl;
445 std::cout << " where xxx.xxx is the ATIS frequency of the ICAO airport YYYY" << std::endl;
446 std::cout << "" << std::endl;
451 // action: display FGCom version then quit
455 SG_LOG(SG_GENERAL, SG_INFO, "FGCom " << FGCOM_VERSION << " compiled " << __DATE__
456 << ", at " << __TIME__ );
457 std::cout << "" << std::endl;
461 // function: computePhoneNumber
462 // action: return phone number
464 std::string computePhoneNumber(double freq, std::string icao, bool atis)
467 return std::string();
469 char phoneNumber[256];
472 int prefix = atis ? 99 : 01;
474 sprintf( tmp, "%4s", icao.c_str() );
477 "%02d%02d%02d%02d%02d%06d",
483 (int) (freq * 1000 + 0.5) );
486 snprintf( phoneNumber,
496 // function: lib_setVolume
497 // action: set input/output volume
499 void lib_setVolume(double input, double output)
501 SG_CLAMP_RANGE<double>(input, 0.0, 1.0);
502 SG_CLAMP_RANGE<double>(output, 0.0, 1.0);
503 SG_LOG(SG_GENERAL, SG_DEBUG, "Set volume input=" << input << " , output=" << output);
504 iaxc_input_level_set(input);
505 iaxc_output_level_set(output);
508 // function: lib_setSilenceThreshold
509 // action: set silence threshold
511 void lib_setSilenceThreshold(double thd)
513 SG_CLAMP_RANGE<double>(thd, -60, 0);
514 SG_LOG(SG_GENERAL, SG_DEBUG, "Set silence threshold=" << thd);
515 iaxc_set_silence_threshold(thd);
518 // function: lib_setCallerId
519 // action: set caller id for the session
521 void lib_setCallerId(std::string callsign)
523 SG_LOG(SG_GENERAL, SG_DEBUG, "Set caller ID=" << callsign);
524 iaxc_set_callerid (callsign.c_str(), _app.c_str());
527 // function: lib_init
528 // action: init the library
532 SG_LOG(SG_GENERAL, SG_DEBUG, "Initializing IAX library");
534 iaxc_set_networking( (iaxc_sendto_t)sendto, (iaxc_recvfrom_t)recvfrom );
536 if (iaxc_initialize(4)) {
537 SG_LOG( SG_GENERAL, SG_ALERT, "Error: cannot initialize IAXClient !\nHINT: Have you checked the mic and speakers ?" );
541 iaxc_set_callerid( _callsign.c_str(), _app.c_str() );
542 iaxc_set_formats(IAXC_FORMAT_SPEEX, IAXC_FORMAT_ULAW|IAXC_FORMAT_SPEEX);
543 iaxc_set_speex_settings(1, 5, 0, 1, 0, 3);
544 iaxc_set_filters(IAXC_FILTER_AGC | IAXC_FILTER_DENOISE);
545 iaxc_set_event_callback(iaxc_callback);
546 iaxc_start_processing_thread ();
547 lib_setSilenceThreshold(_silenceThd);
551 // function: lib_shutdown
552 // action: stop the library
556 SG_LOG(SG_GENERAL, SG_DEBUG, "Shutdown IAX library");
558 if(_registrationId != -1)
559 iaxc_unregister(_registrationId);
563 // function: lib_call
564 // action: register a user on remote server then return the registration ID
566 int lib_registration()
568 SG_LOG(SG_GENERAL, SG_DEBUG, "Request registration");
569 SG_LOG(SG_GENERAL, SG_DEBUG, " username: " << _username);
570 SG_LOG(SG_GENERAL, SG_DEBUG, " password: xxxxxxxx");
571 SG_LOG(SG_GENERAL, SG_DEBUG, " server: " << _server);
572 int regId = iaxc_register( _username.c_str(), _password.c_str(), _server.c_str());
574 SG_LOG( SG_GENERAL, SG_ALERT, "Warning: cannot register '" << _username << "' at '" << _server );
579 // function: lib_call
580 // action: kill current call then do a new call
582 bool lib_call(std::string icao, double freq)
584 SG_LOG(SG_GENERAL, SG_DEBUG, "Request new call");
585 SG_LOG(SG_GENERAL, SG_DEBUG, " icao: " << icao);
586 SG_LOG(SG_GENERAL, SG_DEBUG, " freq: " << freq);
588 iaxc_millisleep(300);
589 std::string num = computePhoneNumber(freq, icao);
592 _callId = iaxc_call(num.c_str());
594 SG_LOG( SG_GENERAL, SG_ALERT, "Warning: cannot call: " << num );
600 bool lib_directCall(std::string icao, double freq, std::string num)
602 SG_LOG(SG_GENERAL, SG_DEBUG, "Request new call");
603 SG_LOG(SG_GENERAL, SG_DEBUG, " icao: " << icao);
604 SG_LOG(SG_GENERAL, SG_DEBUG, " freq: " << freq);
606 iaxc_millisleep(300);
609 _callId = iaxc_call(num.c_str());
611 SG_LOG( SG_GENERAL, SG_ALERT, "Warning: cannot call: " << num );
617 // function: lib_hangup
618 // action: kill current call
624 SG_LOG(SG_GENERAL, SG_DEBUG, "Request hangup");
625 iaxc_dump_all_calls();
630 // function: iaxc_callback
631 // action: parse IAX event then call event handler
633 int iaxc_callback(iaxc_event e)
636 case IAXC_EVENT_TEXT:
637 if(e.ev.text.type == IAXC_TEXT_TYPE_STATUS ||
638 e.ev.text.type == IAXC_TEXT_TYPE_IAX)
639 SG_LOG( SG_GENERAL, SG_INFO, "Message: " << e.ev.text.message );