1 // dclgps.cxx - a class to extend the operation of FG's current GPS
2 // code, and provide support for a KLN89-specific instrument. It
3 // is envisioned that eventually this file and class will be split
4 // up between current FG code and new KLN89-specific code and removed.
6 // Written by David Luff, started 2005.
8 // Copyright (C) 2005 - David C Luff: daveluff --AT-- ntlworld --D0T-- com
10 // This program is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU General Public License as
12 // published by the Free Software Foundation; either version 2 of the
13 // License, or (at your option) any later version.
15 // This program is distributed in the hope that it will be useful, but
16 // WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 // General Public License for more details.
20 // You should have received a copy of the GNU General Public License
21 // along with this program; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
28 #include <simgear/sg_inlines.h>
29 #include <simgear/structure/commands.hxx>
30 #include <simgear/timing/sg_time.hxx>
31 #include <simgear/magvar/magvar.hxx>
33 #include <Main/fg_props.hxx>
34 #include <Navaids/fix.hxx>
35 #include <Navaids/navrecord.hxx>
36 #include <Airports/simple.hxx>
42 // Command callbacks for FlightGear
44 static bool do_kln89_msg_pressed(const SGPropertyNode* arg) {
45 //cout << "do_kln89_msg_pressed called!\n";
46 DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
51 static bool do_kln89_obs_pressed(const SGPropertyNode* arg) {
52 //cout << "do_kln89_obs_pressed called!\n";
53 DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
58 static bool do_kln89_alt_pressed(const SGPropertyNode* arg) {
59 //cout << "do_kln89_alt_pressed called!\n";
60 DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
65 static bool do_kln89_nrst_pressed(const SGPropertyNode* arg) {
66 DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
71 static bool do_kln89_dto_pressed(const SGPropertyNode* arg) {
72 DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
77 static bool do_kln89_clr_pressed(const SGPropertyNode* arg) {
78 DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
83 static bool do_kln89_ent_pressed(const SGPropertyNode* arg) {
84 DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
89 static bool do_kln89_crsr_pressed(const SGPropertyNode* arg) {
90 DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
95 static bool do_kln89_knob1left1(const SGPropertyNode* arg) {
96 DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
101 static bool do_kln89_knob1right1(const SGPropertyNode* arg) {
102 DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
107 static bool do_kln89_knob2left1(const SGPropertyNode* arg) {
108 DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
113 static bool do_kln89_knob2right1(const SGPropertyNode* arg) {
114 DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
119 // End command callbacks
121 GPSWaypoint::GPSWaypoint() {
122 appType = GPS_APP_NONE;
125 GPSWaypoint::GPSWaypoint(const std::string& aIdent, float aLat, float aLon, GPSWpType aType) :
130 appType(GPS_APP_NONE)
134 GPSWaypoint::~GPSWaypoint() {}
136 string GPSWaypoint::GetAprId() {
137 if(appType == GPS_IAF) return(id + 'i');
138 else if(appType == GPS_FAF) return(id + 'f');
139 else if(appType == GPS_MAP) return(id + 'm');
140 else if(appType == GPS_MAHP) return(id + 'h');
145 GPSWpTypeFromFGPosType(FGPositioned::Type aType)
148 case FGPositioned::AIRPORT:
149 case FGPositioned::SEAPORT:
150 case FGPositioned::HELIPORT:
153 case FGPositioned::VOR:
156 case FGPositioned::NDB:
159 case FGPositioned::WAYPOINT:
162 case FGPositioned::FIX:
170 GPSWaypoint* GPSWaypoint::createFromPositioned(const FGPositioned* aPos)
173 return NULL; // happens if find returns no match
176 return new GPSWaypoint(aPos->ident(),
177 aPos->latitude() * SG_DEGREES_TO_RADIANS,
178 aPos->longitude() * SG_DEGREES_TO_RADIANS,
179 GPSWpTypeFromFGPosType(aPos->type())
183 ostream& operator << (ostream& os, GPSAppWpType type) {
185 case(GPS_IAF): return(os << "IAF");
186 case(GPS_IAP): return(os << "IAP");
187 case(GPS_FAF): return(os << "FAF");
188 case(GPS_MAP): return(os << "MAP");
189 case(GPS_MAHP): return(os << "MAHP");
190 case(GPS_HDR): return(os << "HEADER");
191 case(GPS_FENCE): return(os << "FENCE");
192 case(GPS_APP_NONE): return(os << "NONE");
194 return(os << "ERROR - Unknown switch in GPSAppWpType operator << ");
206 FGNPIAP::~FGNPIAP() {
209 ClockTime::ClockTime() {
214 ClockTime::ClockTime(int hr, int min) {
215 while(hr < 0) { hr += 24; }
217 while(min < 0) { min += 60; }
218 while(min > 60) { min -= 60; }
222 ClockTime::~ClockTime() {
225 GPSPage::GPSPage(DCLGPS* parent) {
230 GPSPage::~GPSPage() {
233 void GPSPage::Update(double dt) {}
235 void GPSPage::Knob1Left1() {}
236 void GPSPage::Knob1Right1() {}
238 void GPSPage::Knob2Left1() {
239 _parent->_activePage->LooseFocus();
241 if(_subPage < 0) _subPage = _nSubPages - 1;
244 void GPSPage::Knob2Right1() {
245 _parent->_activePage->LooseFocus();
247 if(_subPage >= _nSubPages) _subPage = 0;
250 void GPSPage::CrsrPressed() {}
251 void GPSPage::EntPressed() {}
252 void GPSPage::ClrPressed() {}
253 void GPSPage::DtoPressed() {}
254 void GPSPage::NrstPressed() {}
255 void GPSPage::AltPressed() {}
256 void GPSPage::OBSPressed() {}
257 void GPSPage::MsgPressed() {}
259 string GPSPage::GPSitoa(int n) {
261 snprintf(buf, 6, "%i", n);
266 void GPSPage::CleanUp() {}
267 void GPSPage::LooseFocus() {}
268 void GPSPage::SetId(const string& s) {}
270 // ------------------------------------------------------------------------------------- //
272 DCLGPS::DCLGPS(RenderArea2D* instrument) {
273 _instrument = instrument;
278 // Units - lets default to US units - FG can set them to other units from config during startup if desired.
279 _altUnits = GPS_ALT_UNITS_FT;
280 _baroUnits = GPS_PRES_UNITS_IN;
281 _velUnits = GPS_VEL_UNITS_KT;
282 _distUnits = GPS_DIST_UNITS_NM;
284 _lon_node = fgGetNode("/instrumentation/gps/indicated-longitude-deg", true);
285 _lat_node = fgGetNode("/instrumentation/gps/indicated-latitude-deg", true);
286 _alt_node = fgGetNode("/instrumentation/gps/indicated-altitude-ft", true);
287 _grnd_speed_node = fgGetNode("/instrumentation/gps/indicated-ground-speed-kt", true);
288 _true_track_node = fgGetNode("/instrumentation/gps/indicated-track-true-deg", true);
289 _mag_track_node = fgGetNode("/instrumentation/gps/indicated-track-magnetic-deg", true);
291 // Use FG's position values at construction in case FG's gps has not run first update yet.
292 _lon = fgGetDouble("/position/longitude-deg") * SG_DEGREES_TO_RADIANS;
293 _lat = fgGetDouble("/position/latitude-deg") * SG_DEGREES_TO_RADIANS;
294 _alt = fgGetDouble("/position/altitude-ft");
295 // Note - we can depriciate _gpsLat and _gpsLon if we implement error handling in FG
296 // gps code and not our own.
301 _groundSpeed_ms = 0.0;
302 _groundSpeed_kts = 0.0;
306 // Sensible defaults. These can be overriden by derived classes if desired.
308 _cdiScales.push_back(5.0);
309 _cdiScales.push_back(1.0);
310 _cdiScales.push_back(0.3);
311 _currentCdiScaleIndex = 0;
312 _targetCdiScaleIndex = 0;
313 _sourceCdiScaleIndex = 0;
314 _cdiScaleTransition = false;
315 _currentCdiScale = 5.0;
319 _activeWaypoint.id.clear();
321 _crosstrackDist = 0.0;
322 _headingBugTo = true;
324 _waypointAlert = false;
326 _departureTimeString = "----";
328 _powerOnTime.set_hr(0);
329 _powerOnTime.set_min(0);
330 _powerOnTimerSet = false;
333 // Configuration Initialisation
334 // Should this be in kln89.cxx ?
335 _turnAnticipationEnabled = false;
336 _suaAlertEnabled = false;
337 _altAlertEnabled = false;
341 _messageStack.clear();
345 _approachLoaded = false;
346 _approachArm = false;
347 _approachReallyArmed = false;
348 _approachActive = false;
349 _approachFP = new GPSFlightPlan;
354 delete _approachFP; // Don't need to delete the waypoints inside since they point to
355 // the waypoints in the approach database.
356 // TODO - may need to delete the approach database!!
359 void DCLGPS::draw() {
360 //cout << "draw called!\n";
364 void DCLGPS::init() {
365 globals->get_commands()->addCommand("kln89_msg_pressed", do_kln89_msg_pressed);
366 globals->get_commands()->addCommand("kln89_obs_pressed", do_kln89_obs_pressed);
367 globals->get_commands()->addCommand("kln89_alt_pressed", do_kln89_alt_pressed);
368 globals->get_commands()->addCommand("kln89_nrst_pressed", do_kln89_nrst_pressed);
369 globals->get_commands()->addCommand("kln89_dto_pressed", do_kln89_dto_pressed);
370 globals->get_commands()->addCommand("kln89_clr_pressed", do_kln89_clr_pressed);
371 globals->get_commands()->addCommand("kln89_ent_pressed", do_kln89_ent_pressed);
372 globals->get_commands()->addCommand("kln89_crsr_pressed", do_kln89_crsr_pressed);
373 globals->get_commands()->addCommand("kln89_knob1left1", do_kln89_knob1left1);
374 globals->get_commands()->addCommand("kln89_knob1right1", do_kln89_knob1right1);
375 globals->get_commands()->addCommand("kln89_knob2left1", do_kln89_knob2left1);
376 globals->get_commands()->addCommand("kln89_knob2right1", do_kln89_knob2right1);
378 // Not sure if this should be here, but OK for now.
379 CreateDefaultFlightPlans();
382 void DCLGPS::bind() {
383 fgTie("/instrumentation/gps/waypoint-alert", this, &DCLGPS::GetWaypointAlert);
384 fgTie("/instrumentation/gps/leg-mode", this, &DCLGPS::GetLegMode);
385 fgTie("/instrumentation/gps/obs-mode", this, &DCLGPS::GetOBSMode);
386 fgTie("/instrumentation/gps/approach-arm", this, &DCLGPS::GetApproachArm);
387 fgTie("/instrumentation/gps/approach-active", this, &DCLGPS::GetApproachActive);
388 fgTie("/instrumentation/gps/cdi-deflection", this, &DCLGPS::GetCDIDeflection);
389 fgTie("/instrumentation/gps/to-flag", this, &DCLGPS::GetToFlag);
392 void DCLGPS::unbind() {
393 fgUntie("/instrumentation/gps/waypoint-alert");
394 fgUntie("/instrumentation/gps/leg-mode");
395 fgUntie("/instrumentation/gps/obs-mode");
396 fgUntie("/instrumentation/gps/approach-arm");
397 fgUntie("/instrumentation/gps/approach-active");
398 fgUntie("/instrumentation/gps/cdi-deflection");
401 void DCLGPS::update(double dt) {
402 //cout << "update called!\n";
404 _lon = _lon_node->getDoubleValue() * SG_DEGREES_TO_RADIANS;
405 _lat = _lat_node->getDoubleValue() * SG_DEGREES_TO_RADIANS;
406 _alt = _alt_node->getDoubleValue();
407 _groundSpeed_kts = _grnd_speed_node->getDoubleValue();
408 _groundSpeed_ms = _groundSpeed_kts * 0.5144444444;
409 _track = _true_track_node->getDoubleValue();
410 _magTrackDeg = _mag_track_node->getDoubleValue();
411 // Note - we can depriciate _gpsLat and _gpsLon if we implement error handling in FG
412 // gps code and not our own.
415 // Check for abnormal position slew
416 if(GetGreatCircleDistance(_gpsLat, _gpsLon, _checkLat, _checkLon) > 1.0) {
417 OrientateToActiveFlightPlan();
422 // TODO - check for unit power before running this.
423 if(!_powerOnTimerSet) {
427 // Check if an alarm timer has expired
429 if(_alarmTime.hr() == atoi(fgGetString("/instrumentation/clock/indicated-hour"))
430 && _alarmTime.min() == atoi(fgGetString("/instrumentation/clock/indicated-min"))) {
431 _messageStack.push_back("*Timer Expired");
437 if(_groundSpeed_kts > 30.0) {
439 string th = fgGetString("/instrumentation/clock/indicated-hour");
440 string tm = fgGetString("/instrumentation/clock/indicated-min");
441 if(th.size() == 1) th = "0" + th;
442 if(tm.size() == 1) tm = "0" + tm;
443 _departureTimeString = th + tm;
446 // TODO - check - is this prone to drift error over time?
447 // Should we difference the departure and current times?
448 // What about when the user resets the time of day from the menu?
452 _time->update(_gpsLon * SG_DEGREES_TO_RADIANS, _gpsLat * SG_DEGREES_TO_RADIANS, 0, 0);
453 // FIXME - currently all the below assumes leg mode and no DTO or OBS cancelled.
454 if(_activeFP->IsEmpty()) {
455 // Not sure if we need to reset these each update or only when fp altered
456 _activeWaypoint.id.clear();
458 } else if(_activeFP->waypoints.size() == 1) {
459 _activeWaypoint.id.clear();
462 if(_activeWaypoint.id.empty() || _fromWaypoint.id.empty()) {
463 //cout << "Error, in leg mode with flightplan of 2 or more waypoints, but either active or from wp is NULL!\n";
464 OrientateToActiveFlightPlan();
468 if(_approachLoaded) {
469 if(!_approachReallyArmed && !_approachActive) {
470 // arm if within 30nm of airport.
471 // TODO - let user cancel approach arm using external GPS-APR switch
473 const FGAirport* ap = FindFirstAptById(_approachID, multi, true);
475 double d = GetGreatCircleDistance(_gpsLat, _gpsLon, ap->getLatitude() * SG_DEGREES_TO_RADIANS, ap->getLongitude() * SG_DEGREES_TO_RADIANS);
478 _approachReallyArmed = true;
479 _messageStack.push_back("*Press ALT To Set Baro");
480 // Not sure what we do if the user has already set CDI to 0.3 nm?
481 _targetCdiScaleIndex = 1;
482 if(_currentCdiScaleIndex == 1) {
484 } else if(_currentCdiScaleIndex == 0) {
485 _sourceCdiScaleIndex = 0;
486 _cdiScaleTransition = true;
487 _cdiTransitionTime = 30.0;
488 _currentCdiScale = _cdiScales[_currentCdiScaleIndex];
493 // Check for approach active - we can only activate approach if it is really armed.
494 if(_activeWaypoint.appType == GPS_FAF) {
495 //cout << "Active waypoint is FAF, id is " << _activeWaypoint.id << '\n';
496 if(GetGreatCircleDistance(_gpsLat, _gpsLon, _activeWaypoint.lat, _activeWaypoint.lon) <= 2.0 && !_obsMode) {
497 // Assume heading is OK for now
498 _approachArm = false; // TODO - check - maybe arm is left on when actv comes on?
499 _approachReallyArmed = false;
500 _approachActive = true;
501 _targetCdiScaleIndex = 2;
502 if(_currentCdiScaleIndex == 2) {
504 } else if(_currentCdiScaleIndex == 1) {
505 _sourceCdiScaleIndex = 1;
506 _cdiScaleTransition = true;
507 _cdiTransitionTime = 30.0; // TODO - compress it if time to FAF < 30sec
508 _currentCdiScale = _cdiScales[_currentCdiScaleIndex];
510 // Abort going active?
511 _approachActive = false;
518 // CDI scale transition stuff
519 if(_cdiScaleTransition) {
520 if(fabs(_currentCdiScale - _cdiScales[_targetCdiScaleIndex]) < 0.001) {
521 _currentCdiScale = _cdiScales[_targetCdiScaleIndex];
522 _currentCdiScaleIndex = _targetCdiScaleIndex;
523 _cdiScaleTransition = false;
525 double scaleDiff = (_targetCdiScaleIndex > _sourceCdiScaleIndex
526 ? _cdiScales[_sourceCdiScaleIndex] - _cdiScales[_targetCdiScaleIndex]
527 : _cdiScales[_targetCdiScaleIndex] - _cdiScales[_sourceCdiScaleIndex]);
528 //cout << "ScaleDiff = " << scaleDiff << '\n';
529 if(_targetCdiScaleIndex > _sourceCdiScaleIndex) {
530 // Scaling down eg. 5nm -> 1nm
531 _currentCdiScale -= (scaleDiff * dt / _cdiTransitionTime);
532 if(_currentCdiScale < _cdiScales[_targetCdiScaleIndex]) {
533 _currentCdiScale = _cdiScales[_targetCdiScaleIndex];
534 _currentCdiScaleIndex = _targetCdiScaleIndex;
535 _cdiScaleTransition = false;
538 _currentCdiScale += (scaleDiff * dt / _cdiTransitionTime);
539 if(_currentCdiScale > _cdiScales[_targetCdiScaleIndex]) {
540 _currentCdiScale = _cdiScales[_targetCdiScaleIndex];
541 _currentCdiScaleIndex = _targetCdiScaleIndex;
542 _cdiScaleTransition = false;
545 //cout << "_currentCdiScale = " << _currentCdiScale << '\n';
548 _currentCdiScale = _cdiScales[_currentCdiScaleIndex];
552 // Urgh - I've been setting the heading bug based on DTK,
553 // bug I think it should be based on heading re. active waypoint
554 // based on what the sim does after the final waypoint is passed.
555 // (DTK remains the same, but if track is held == DTK heading bug
556 // reverses to from once wp is passed).
558 if(_fromWaypoint != NULL) {
559 // TODO - how do we handle the change of track with distance over long legs?
560 _dtkTrue = GetGreatCircleCourse(_fromWaypoint->lat, _fromWaypoint->lon, _activeWaypoint->lat, _activeWaypoint->lon) * SG_RADIANS_TO_DEGREES;
561 _dtkMag = GetMagHeadingFromTo(_fromWaypoint->lat, _fromWaypoint->lon, _activeWaypoint->lat, _activeWaypoint->lon);
562 // Don't change the heading bug if speed is too low otherwise it flickers to/from at rest
563 if(_groundSpeed_ms > 5) {
564 //cout << "track = " << _track << ", dtk = " << _dtkTrue << '\n';
565 double courseDev = _track - _dtkTrue;
566 //cout << "courseDev = " << courseDev << ", normalized = ";
567 SG_NORMALIZE_RANGE(courseDev, -180.0, 180.0);
568 //cout << courseDev << '\n';
569 _headingBugTo = (fabs(courseDev) > 90.0 ? false : true);
574 // TODO - in DTO operation the position of initiation of DTO defines the "from waypoint".
577 if(!_activeWaypoint.id.empty()) {
578 double hdgTrue = GetGreatCircleCourse(_gpsLat, _gpsLon, _activeWaypoint.lat, _activeWaypoint.lon) * SG_RADIANS_TO_DEGREES;
579 if(_groundSpeed_ms > 5) {
580 //cout << "track = " << _track << ", hdgTrue = " << hdgTrue << '\n';
581 double courseDev = _track - hdgTrue;
582 //cout << "courseDev = " << courseDev << ", normalized = ";
583 SG_NORMALIZE_RANGE(courseDev, -180.0, 180.0);
584 //cout << courseDev << '\n';
585 _headingBugTo = (fabs(courseDev) > 90.0 ? false : true);
587 if(!_fromWaypoint.id.empty()) {
588 _dtkTrue = GetGreatCircleCourse(_fromWaypoint.lat, _fromWaypoint.lon, _activeWaypoint.lat, _activeWaypoint.lon) * SG_RADIANS_TO_DEGREES;
589 _dtkMag = GetMagHeadingFromTo(_fromWaypoint.lat, _fromWaypoint.lon, _activeWaypoint.lat, _activeWaypoint.lon);
596 _dist2Act = GetGreatCircleDistance(_gpsLat, _gpsLon, _activeWaypoint.lat, _activeWaypoint.lon) * SG_NM_TO_METER;
597 if(_groundSpeed_ms > 10.0) {
598 _eta = _dist2Act / _groundSpeed_ms;
599 if(_eta <= 36) { // TODO - this is slightly different if turn anticipation is enabled.
601 _waypointAlert = true; // TODO - not if the from flag is set.
605 // Check if we should sequence to next leg.
606 // Perhaps this should be done on distance instead, but 60s time (about 1 - 2 nm) seems reasonable for now.
607 //double reverseHeading = GetGreatCircleCourse(_activeWaypoint->lat, _activeWaypoint->lon, _fromWaypoint->lat, _fromWaypoint->lon);
608 // Hack - let's cheat and do it on heading bug for now. TODO - that stops us 'cutting the corner'
609 // when we happen to approach the inside turn of a waypoint - we should probably sequence at the midpoint
610 // of the heading difference between legs in this instance.
611 int idx = GetActiveWaypointIndex();
612 bool finalLeg = (idx == (int)(_activeFP->waypoints.size()) - 1 ? true : false);
613 bool finalDto = (_dto && idx == -1); // Dto operation to a waypoint not in the flightplan - we don't sequence in this instance
616 // Do nothing - not sure if Dto should switch off when arriving at the final waypoint of a flightplan
617 } else if(finalDto) {
619 } else if(_activeWaypoint.appType == GPS_MAP) {
620 // Don't sequence beyond the missed approach point
621 //cout << "ACTIVE WAYPOINT is MAP - not sequencing!!!!!\n";
623 //cout << "Sequencing...\n";
624 _fromWaypoint = _activeWaypoint;
625 _activeWaypoint = *_activeFP->waypoints[idx + 1];
627 // TODO - course alteration message format is dependent on whether we are slaved HSI/CDI indicator or not.
628 // For now assume we are not.
630 if(fgGetBool("/instrumentation/nav[0]/slaved-to-gps")) {
631 // TODO - avoid the hardwiring on nav[0]
632 s = "Adj Nav Crs to ";
634 string s = "GPS Course is ";
636 double d = GetMagHeadingFromTo(_fromWaypoint.lat, _fromWaypoint.lon, _activeWaypoint.lat, _activeWaypoint.lon);
637 while(d < 0.0) d += 360.0;
638 while(d >= 360.0) d -= 360.0;
640 snprintf(buf, 4, "%03i", (int)(d + 0.5));
642 _messageStack.push_back(s);
644 _waypointAlert = false;
652 // First attempt at a sensible cross-track correction calculation
653 // Uh? - I think this is implemented further down the file!
654 if(_fromWaypoint != NULL) {
657 _crosstrackDist = 0.0;
663 // I don't yet fully understand all the gotchas about where to source time from.
664 // This function sets the initial timer before the clock exports properties
665 // and the one below uses the clock to be consistent with the rest of the code.
666 // It might change soonish...
667 void DCLGPS::SetPowerOnTimer() {
668 struct tm *t = globals->get_time_params()->getGmt();
669 _powerOnTime.set_hr(t->tm_hour);
670 _powerOnTime.set_min(t->tm_min);
671 _powerOnTimerSet = true;
674 void DCLGPS::ResetPowerOnTimer() {
675 _powerOnTime.set_hr(atoi(fgGetString("/instrumentation/clock/indicated-hour")));
676 _powerOnTime.set_min(atoi(fgGetString("/instrumentation/clock/indicated-min")));
677 _powerOnTimerSet = true;
680 double DCLGPS::GetCDIDeflection() const {
681 double xtd = CalcCrossTrackDeviation(); //nm
682 return((xtd / _currentCdiScale) * 5.0 * 2.5 * -1.0);
685 void DCLGPS::DtoInitiate(const string& s) {
686 //cout << "DtoInitiate, s = " << s << '\n';
687 const GPSWaypoint* wp = FindFirstByExactId(s);
689 //cout << "Waypoint found, starting dto operation!\n";
691 _activeWaypoint = *wp;
692 _fromWaypoint.lat = _gpsLat;
693 _fromWaypoint.lon = _gpsLon;
694 _fromWaypoint.type = GPS_WP_VIRT;
695 _fromWaypoint.id = "DTOWP";
698 //cout << "Waypoint not found, ignoring dto request\n";
699 // Should bring up the user waypoint page, but we're not implementing that yet.
700 _dto = false; // TODO - implement this some day.
704 void DCLGPS::DtoCancel() {
706 // i.e. don't bother reorientating if we're just cancelling a DTO button press
707 // without having previously initiated DTO.
708 OrientateToActiveFlightPlan();
713 void DCLGPS::Knob1Left1() {}
714 void DCLGPS::Knob1Right1() {}
715 void DCLGPS::Knob2Left1() {}
716 void DCLGPS::Knob2Right1() {}
717 void DCLGPS::CrsrPressed() { _activePage->CrsrPressed(); }
718 void DCLGPS::EntPressed() { _activePage->EntPressed(); }
719 void DCLGPS::ClrPressed() { _activePage->ClrPressed(); }
720 void DCLGPS::DtoPressed() {}
721 void DCLGPS::NrstPressed() {}
722 void DCLGPS::AltPressed() {}
724 void DCLGPS::OBSPressed() {
725 _obsMode = !_obsMode;
727 if(!_activeWaypoint.id.empty()) {
728 _obsHeading = static_cast<int>(_dtkMag);
730 // TODO - the _fromWaypoint location will change as the OBS heading changes.
731 // Might need to store the OBS initiation position somewhere in case it is needed again.
732 SetOBSFromWaypoint();
736 // Set the _fromWaypoint position based on the active waypoint and OBS radial.
737 void DCLGPS::SetOBSFromWaypoint() {
738 if(!_obsMode) return;
739 if(_activeWaypoint.id.empty()) return;
741 // TODO - base the 180 deg correction on the to/from flag.
742 _fromWaypoint = GetPositionOnMagRadial(_activeWaypoint, 10, _obsHeading + 180.0);
743 _fromWaypoint.id = "OBSWP";
746 void DCLGPS::MsgPressed() {}
748 void DCLGPS::CDIFSDIncrease() {
749 if(_currentCdiScaleIndex == 0) {
750 _currentCdiScaleIndex = _cdiScales.size() - 1;
752 _currentCdiScaleIndex--;
756 void DCLGPS::CDIFSDDecrease() {
757 _currentCdiScaleIndex++;
758 if(_currentCdiScaleIndex == _cdiScales.size()) {
759 _currentCdiScaleIndex = 0;
763 void DCLGPS::DrawChar(char c, int field, int px, int py, bool bold) {
766 void DCLGPS::DrawText(const string& s, int field, int px, int py, bool bold) {
769 void DCLGPS::SetBaroUnits(int n, bool wrap) {
771 _baroUnits = (GPSPressureUnits)(wrap ? 3 : 1);
773 _baroUnits = (GPSPressureUnits)(wrap ? 1 : 3);
775 _baroUnits = (GPSPressureUnits)n;
779 void DCLGPS::CreateDefaultFlightPlans() {}
781 // Get the time to the active waypoint in seconds.
782 // Returns -1 if groundspeed < 30 kts
783 double DCLGPS::GetTimeToActiveWaypoint() {
784 if(_groundSpeed_kts < 30.0) {
791 // Get the time to the final waypoint in seconds.
792 // Returns -1 if groundspeed < 30 kts
793 double DCLGPS::GetETE() {
794 if(_groundSpeed_kts < 30.0) {
797 // TODO - handle OBS / DTO operation appropriately
798 if(_activeFP->waypoints.empty()) {
801 return(GetTimeToWaypoint(_activeFP->waypoints[_activeFP->waypoints.size() - 1]->id));
806 // Get the time to a given waypoint (spec'd by ID) in seconds.
807 // returns -1 if groundspeed is less than 30kts.
808 // If the waypoint is an unreached part of the active flight plan the time will be via each leg.
809 // otherwise it will be a direct-to time.
810 double DCLGPS::GetTimeToWaypoint(const string& id) {
811 if(_groundSpeed_kts < 30.0) {
816 int n1 = GetActiveWaypointIndex();
817 int n2 = GetWaypointIndex(id);
820 for(unsigned int i=n1+1; i<_activeFP->waypoints.size(); ++i) {
821 GPSWaypoint* wp1 = _activeFP->waypoints[i-1];
822 GPSWaypoint* wp2 = _activeFP->waypoints[i];
823 double distm = GetGreatCircleDistance(wp1->lat, wp1->lon, wp2->lat, wp2->lon) * SG_NM_TO_METER;
824 eta += (distm / _groundSpeed_ms);
827 } else if(id == _activeWaypoint.id) {
830 const GPSWaypoint* wp = FindFirstByExactId(id);
831 if(wp == NULL) return(-1.0);
832 double distm = GetGreatCircleDistance(_gpsLat, _gpsLon, wp->lat, wp->lon);
834 return(distm / _groundSpeed_ms);
836 return(-1.0); // Hopefully we never get here!
839 // Returns magnetic great-circle heading
840 // TODO - document units.
841 float DCLGPS::GetHeadingToActiveWaypoint() {
842 if(_activeWaypoint.id.empty()) {
845 double h = GetMagHeadingFromTo(_gpsLat, _gpsLon, _activeWaypoint.lat, _activeWaypoint.lon);
846 while(h <= 0.0) h += 360.0;
847 while(h > 360.0) h -= 360.0;
852 // Returns magnetic great-circle heading
853 // TODO - what units?
854 float DCLGPS::GetHeadingFromActiveWaypoint() {
855 if(_activeWaypoint.id.empty()) {
858 double h = GetMagHeadingFromTo(_activeWaypoint.lat, _activeWaypoint.lon, _gpsLat, _gpsLon);
859 while(h <= 0.0) h += 360.0;
860 while(h > 360.0) h -= 360.0;
865 void DCLGPS::ClearFlightPlan(int n) {
866 for(unsigned int i=0; i<_flightPlans[n]->waypoints.size(); ++i) {
867 delete _flightPlans[n]->waypoints[i];
869 _flightPlans[n]->waypoints.clear();
872 void DCLGPS::ClearFlightPlan(GPSFlightPlan* fp) {
873 for(unsigned int i=0; i<fp->waypoints.size(); ++i) {
874 delete fp->waypoints[i];
876 fp->waypoints.clear();
879 int DCLGPS::GetActiveWaypointIndex() {
880 for(unsigned int i=0; i<_flightPlans[0]->waypoints.size(); ++i) {
881 if(_flightPlans[0]->waypoints[i]->id == _activeWaypoint.id) return((int)i);
886 int DCLGPS::GetWaypointIndex(const string& id) {
887 for(unsigned int i=0; i<_flightPlans[0]->waypoints.size(); ++i) {
888 if(_flightPlans[0]->waypoints[i]->id == id) return((int)i);
893 void DCLGPS::OrientateToFlightPlan(GPSFlightPlan* fp) {
894 //cout << "Orientating...\n";
895 //cout << "_lat = " << _lat << ", _lon = " << _lon << ", _gpsLat = " << _gpsLat << ", gpsLon = " << _gpsLon << '\n';
897 _activeWaypoint.id.clear();
901 if(fp->waypoints.size() == 1) {
902 // TODO - may need to flag nav here if not dto or obs, or possibly handle it somewhere else.
903 _activeWaypoint = *fp->waypoints[0];
904 _fromWaypoint.id.clear();
907 _fromWaypoint = *fp->waypoints[0];
908 _activeWaypoint = *fp->waypoints[1];
909 double dmin = 1000000; // nm!!
910 // For now we will simply start on the leg closest to our current position.
911 // It's possible that more fancy algorithms may take either heading or track
912 // into account when setting inital leg - I'm not sure.
913 // This method should handle most cases perfectly OK though.
914 for(unsigned int i = 1; i < fp->waypoints.size(); ++i) {
915 //cout << "Pass " << i << ", dmin = " << dmin << ", leg is " << fp->waypoints[i-1]->id << " to " << fp->waypoints[i]->id << '\n';
916 // First get the cross track correction.
917 double d0 = fabs(CalcCrossTrackDeviation(*fp->waypoints[i-1], *fp->waypoints[i]));
918 // That is the shortest distance away we could be though - check for
919 // longer distances if we are 'off the end' of the leg.
920 double ht1 = GetGreatCircleCourse(fp->waypoints[i-1]->lat, fp->waypoints[i-1]->lon,
921 fp->waypoints[i]->lat, fp->waypoints[i]->lon)
922 * SG_RADIANS_TO_DEGREES;
923 // not simply the reverse of the above due to great circle navigation.
924 double ht2 = GetGreatCircleCourse(fp->waypoints[i]->lat, fp->waypoints[i]->lon,
925 fp->waypoints[i-1]->lat, fp->waypoints[i-1]->lon)
926 * SG_RADIANS_TO_DEGREES;
927 double hw1 = GetGreatCircleCourse(_gpsLat, _gpsLon,
928 fp->waypoints[i]->lat, fp->waypoints[i]->lon)
929 * SG_RADIANS_TO_DEGREES;
930 double hw2 = GetGreatCircleCourse(_gpsLat, _gpsLon,
931 fp->waypoints[i-1]->lat, fp->waypoints[i-1]->lon)
932 * SG_RADIANS_TO_DEGREES;
933 double h1 = ht1 - hw1;
934 double h2 = ht2 - hw2;
935 //cout << "d0, h1, h2 = " << d0 << ", " << h1 << ", " << h2 << '\n';
936 //cout << "Normalizing...\n";
937 SG_NORMALIZE_RANGE(h1, -180.0, 180.0);
938 SG_NORMALIZE_RANGE(h2, -180.0, 180.0);
939 //cout << "d0, h1, h2 = " << d0 << ", " << h1 << ", " << h2 << '\n';
940 if(fabs(h1) > 90.0) {
941 // We are past the end of the to waypoint
942 double d = GetGreatCircleDistance(_gpsLat, _gpsLon, fp->waypoints[i]->lat, fp->waypoints[i]->lon);
944 //cout << "h1 triggered, d0 now = " << d0 << '\n';
945 } else if(fabs(h2) > 90.0) {
946 // We are past the end (not yet at!) the from waypoint
947 double d = GetGreatCircleDistance(_gpsLat, _gpsLon, fp->waypoints[i-1]->lat, fp->waypoints[i-1]->lon);
949 //cout << "h2 triggered, d0 now = " << d0 << '\n';
952 //cout << "THIS LEG NOW ACTIVE!\n";
954 _fromWaypoint = *fp->waypoints[i-1];
955 _activeWaypoint = *fp->waypoints[i];
962 void DCLGPS::OrientateToActiveFlightPlan() {
963 OrientateToFlightPlan(_activeFP);
966 /***************************************/
968 // Utility function - create a flightplan from a list of waypoint ids and types
969 void DCLGPS::CreateFlightPlan(GPSFlightPlan* fp, vector<string> ids, vector<GPSWpType> wps) {
970 if(fp == NULL) fp = new GPSFlightPlan;
972 if(!fp->waypoints.empty()) {
973 for(i=0; i<fp->waypoints.size(); ++i) {
974 delete fp->waypoints[i];
976 fp->waypoints.clear();
978 if(ids.size() != wps.size()) {
979 cout << "ID and Waypoint types list size mismatch in GPS::CreateFlightPlan - no flightplan created!\n";
982 for(i=0; i<ids.size(); ++i) {
986 GPSWaypoint* wp = new GPSWaypoint;
990 ap = FindFirstAptById(ids[i], multi, true);
995 wp->lat = ap->getLatitude() * SG_DEGREES_TO_RADIANS;
996 wp->lon = ap->getLongitude() * SG_DEGREES_TO_RADIANS;
998 fp->waypoints.push_back(wp);
1002 np = FindFirstVorById(ids[i], multi, true);
1007 wp->lat = np->get_lat() * SG_DEGREES_TO_RADIANS;
1008 wp->lon = np->get_lon() * SG_DEGREES_TO_RADIANS;
1010 fp->waypoints.push_back(wp);
1014 np = FindFirstNDBById(ids[i], multi, true);
1019 wp->lat = np->get_lat() * SG_DEGREES_TO_RADIANS;
1020 wp->lon = np->get_lon() * SG_DEGREES_TO_RADIANS;
1022 fp->waypoints.push_back(wp);
1035 /***************************************/
1037 class DCLGPSFilter : public FGPositioned::Filter
1040 virtual bool pass(const FGPositioned* aPos) const {
1041 switch (aPos->type()) {
1042 case FGPositioned::AIRPORT:
1043 // how about heliports and seaports?
1044 case FGPositioned::NDB:
1045 case FGPositioned::VOR:
1046 case FGPositioned::WAYPOINT:
1047 case FGPositioned::FIX:
1049 default: return false; // reject all other types
1055 GPSWaypoint* DCLGPS::FindFirstById(const string& id) const
1057 DCLGPSFilter filter;
1058 FGPositionedRef result = FGPositioned::findNextWithPartialId(NULL, id, &filter);
1059 return GPSWaypoint::createFromPositioned(result);
1062 GPSWaypoint* DCLGPS::FindFirstByExactId(const string& id) const
1064 SGGeod pos(SGGeod::fromRad(_lon, _lat));
1065 FGPositionedRef result = FGPositioned::findClosestWithIdent(id, pos);
1066 return GPSWaypoint::createFromPositioned(result);
1069 // TODO - add the ASCII / alphabetical stuff from the Atlas version
1070 FGPositioned* DCLGPS::FindTypedFirstById(const string& id, FGPositioned::Type ty, bool &multi, bool exact)
1073 FGPositioned::TypeFilter filter(ty);
1076 FGPositioned::List matches =
1077 FGPositioned::findAllWithIdentSortedByRange(id, SGGeod::fromRad(_lon, _lat), &filter);
1078 multi = (matches.size() > 1);
1079 return matches.empty() ? NULL : matches.front().ptr();
1082 return FGPositioned::findNextWithPartialId(NULL, id, &filter);
1085 FGNavRecord* DCLGPS::FindFirstVorById(const string& id, bool &multi, bool exact)
1087 return dynamic_cast<FGNavRecord*>(FindTypedFirstById(id, FGPositioned::VOR, multi, exact));
1090 FGNavRecord* DCLGPS::FindFirstNDBById(const string& id, bool &multi, bool exact)
1092 return dynamic_cast<FGNavRecord*>(FindTypedFirstById(id, FGPositioned::NDB, multi, exact));
1095 const FGFix* DCLGPS::FindFirstIntById(const string& id, bool &multi, bool exact)
1097 return dynamic_cast<FGFix*>(FindTypedFirstById(id, FGPositioned::FIX, multi, exact));
1100 const FGAirport* DCLGPS::FindFirstAptById(const string& id, bool &multi, bool exact)
1102 return dynamic_cast<FGAirport*>(FindTypedFirstById(id, FGPositioned::AIRPORT, multi, exact));
1105 FGNavRecord* DCLGPS::FindClosestVor(double lat_rad, double lon_rad) {
1106 FGPositioned::TypeFilter filter(FGPositioned::VOR);
1107 double cutoff = 1000; // nautical miles
1108 FGPositionedRef v = FGPositioned::findClosest(SGGeod::fromRad(lon_rad, lat_rad), cutoff, &filter);
1113 return dynamic_cast<FGNavRecord*>(v.ptr());
1116 //----------------------------------------------------------------------------------------------------------
1118 // Takes lat and lon in RADIANS!!!!!!!
1119 double DCLGPS::GetMagHeadingFromTo(double latA, double lonA, double latB, double lonB) {
1120 double h = GetGreatCircleCourse(latA, lonA, latB, lonB);
1121 h *= SG_RADIANS_TO_DEGREES;
1122 // TODO - use the real altitude below instead of 0.0!
1123 //cout << "MagVar = " << sgGetMagVar(_gpsLon, _gpsLat, 0.0, _time->getJD()) * SG_RADIANS_TO_DEGREES << '\n';
1124 h -= sgGetMagVar(_gpsLon, _gpsLat, 0.0, _time->getJD()) * SG_RADIANS_TO_DEGREES;
1125 while(h >= 360.0) h -= 360.0;
1126 while(h < 0.0) h += 360.0;
1130 // ---------------- Great Circle formulae from "The Aviation Formulary" -------------
1131 // Note that all of these assume that the world is spherical.
1133 double Rad2Nm(double theta) {
1134 return(((180.0*60.0)/SG_PI)*theta);
1137 double Nm2Rad(double d) {
1138 return((SG_PI/(180.0*60.0))*d);
1143 The great circle distance d between two points with coordinates {lat1,lon1} and {lat2,lon2} is given by:
1145 d=acos(sin(lat1)*sin(lat2)+cos(lat1)*cos(lat2)*cos(lon1-lon2))
1147 A mathematically equivalent formula, which is less subject to rounding error for short distances is:
1149 d=2*asin(sqrt((sin((lat1-lat2)/2))^2 +
1150 cos(lat1)*cos(lat2)*(sin((lon1-lon2)/2))^2))
1154 // Returns distance in nm, takes lat & lon in RADIANS
1155 double DCLGPS::GetGreatCircleDistance(double lat1, double lon1, double lat2, double lon2) const {
1156 double d = 2.0 * asin(sqrt(((sin((lat1-lat2)/2.0))*(sin((lat1-lat2)/2.0))) +
1157 cos(lat1)*cos(lat2)*(sin((lon1-lon2)/2.0))*(sin((lon1-lon2)/2.0))));
1161 // fmod dosen't do what we want :-(
1162 static double mod(double d1, double d2) {
1163 return(d1 - d2*floor(d1/d2));
1166 // Returns great circle course from point 1 to point 2
1167 // Input and output in RADIANS.
1168 double DCLGPS::GetGreatCircleCourse (double lat1, double lon1, double lat2, double lon2) const {
1171 // Special case the poles
1172 if(cos(lat1) < SG_EPSILON) {
1174 // Starting from North Pole
1177 // Starting from South Pole
1181 // Urgh - the formula below is for negative lon +ve !!!???
1182 double d = GetGreatCircleDistance(lat1, lon1, lat2, lon2);
1183 cout << "d = " << d;
1185 //cout << ", d_theta = " << d;
1186 //cout << ", and d = " << Rad2Nm(d) << ' ';
1187 if(sin(lon2 - lon1) < 0) {
1189 h = acos((sin(lat2)-sin(lat1)*cos(d))/(sin(d)*cos(lat1)));
1192 h = 2.0 * SG_PI - acos((sin(lat2)-sin(lat1)*cos(d))/(sin(d)*cos(lat1)));
1195 cout << h * SG_RADIANS_TO_DEGREES << '\n';
1198 return( mod(atan2(sin(lon2-lon1)*cos(lat2),
1199 cos(lat1)*sin(lat2)-sin(lat1)*cos(lat2)*cos(lon2-lon1)),
1203 // Return a position on a radial from wp1 given distance d (nm) and magnetic heading h (degrees)
1204 // Note that d should be less that 1/4 Earth diameter!
1205 GPSWaypoint DCLGPS::GetPositionOnMagRadial(const GPSWaypoint& wp1, double d, double h) {
1206 h += sgGetMagVar(wp1.lon, wp1.lat, 0.0, _time->getJD()) * SG_RADIANS_TO_DEGREES;
1207 return(GetPositionOnRadial(wp1, d, h));
1210 // Return a position on a radial from wp1 given distance d (nm) and TRUE heading h (degrees)
1211 // Note that d should be less that 1/4 Earth diameter!
1212 GPSWaypoint DCLGPS::GetPositionOnRadial(const GPSWaypoint& wp1, double d, double h) {
1213 while(h < 0.0) h += 360.0;
1214 while(h > 360.0) h -= 360.0;
1216 h *= SG_DEGREES_TO_RADIANS;
1217 d *= (SG_PI / (180.0 * 60.0));
1219 double lat=asin(sin(wp1.lat)*cos(d)+cos(wp1.lat)*sin(d)*cos(h));
1222 lon=wp1.lon; // endpoint a pole
1224 lon=mod(wp1.lon+asin(sin(h)*sin(d)/cos(lat))+SG_PI,2*SG_PI)-SG_PI;
1230 wp.type = GPS_WP_VIRT;
1234 // Returns cross-track deviation in Nm.
1235 double DCLGPS::CalcCrossTrackDeviation() const {
1236 return(CalcCrossTrackDeviation(_fromWaypoint, _activeWaypoint));
1239 // Returns cross-track deviation of the current position between two arbitary waypoints in nm.
1240 double DCLGPS::CalcCrossTrackDeviation(const GPSWaypoint& wp1, const GPSWaypoint& wp2) const {
1241 //if(wp1 == NULL || wp2 == NULL) return(0.0);
1242 if(wp1.id.empty() || wp2.id.empty()) return(0.0);
1243 double xtd = asin(sin(Nm2Rad(GetGreatCircleDistance(wp1.lat, wp1.lon, _gpsLat, _gpsLon)))
1244 * sin(GetGreatCircleCourse(wp1.lat, wp1.lon, _gpsLat, _gpsLon) - GetGreatCircleCourse(wp1.lat, wp1.lon, wp2.lat, wp2.lon)));
1245 return(Rad2Nm(xtd));