public void TestInitialise() { _Comparer = Factory.Singleton.Resolve<IAircraftComparer>(); _Lhs = new Mock<IAircraft>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties().Object; _Rhs = new Mock<IAircraft>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties().Object; }
/// <summary> /// Sets the appropriate column on the aircraft passed across to either a high or low value, depending on the parameters. /// </summary> /// <param name="aircraft"></param> /// <param name="columnName"></param> /// <param name="setLowValue"></param> private void InitialiseAircraft(IAircraft aircraft, string columnName, bool setLowValue) { switch(columnName) { case AircraftComparerColumn.Altitude: aircraft.Altitude = setLowValue ? 100 : 200; break; case AircraftComparerColumn.Callsign: aircraft.Callsign = setLowValue ? "ABC" : "XYZ"; break; case AircraftComparerColumn.Destination: aircraft.Destination = setLowValue ? "ABC" : "XYZ"; break; case AircraftComparerColumn.DistanceFromHere: aircraft.Latitude = aircraft.Longitude = setLowValue ? 1F : 2F; break; case AircraftComparerColumn.FirstSeen: aircraft.FirstSeen = setLowValue ? new DateTime(2001, 1, 2, 10, 20, 21, 100) : new DateTime(2001, 1, 2, 10, 20, 21, 200); break; case AircraftComparerColumn.FlightsCount: aircraft.FlightsCount = setLowValue ? 100 : 200; break; case AircraftComparerColumn.GroundSpeed: aircraft.GroundSpeed = setLowValue ? 100 : 200; break; case AircraftComparerColumn.Icao24: aircraft.Icao24 = setLowValue ? "123456" : "ABCDEF"; break; case AircraftComparerColumn.Icao24Country: aircraft.Icao24Country = setLowValue ? "ABC" : "XYZ"; break; case AircraftComparerColumn.Model: aircraft.Model = setLowValue ? "ABC" : "XYZ"; break; case AircraftComparerColumn.NumberOfEngines: aircraft.NumberOfEngines = setLowValue ? "ABC" : "XYZ"; break; case AircraftComparerColumn.Operator: aircraft.Operator = setLowValue ? "ABC" : "XYZ"; break; case AircraftComparerColumn.OperatorIcao: aircraft.OperatorIcao = setLowValue ? "ABC" : "XYZ"; break; case AircraftComparerColumn.Origin: aircraft.Origin = setLowValue ? "ABC" : "XYZ"; break; case AircraftComparerColumn.Registration: aircraft.Registration = setLowValue ? "ABC" : "XYZ"; break; case AircraftComparerColumn.Species: aircraft.Species = setLowValue ? Species.Amphibian : Species.Landplane; break; case AircraftComparerColumn.Squawk: aircraft.Squawk = setLowValue ? 5 : 5000; break; case AircraftComparerColumn.Type: aircraft.Type = setLowValue ? "ABC" : "XYZ"; break; case AircraftComparerColumn.VerticalRate: aircraft.VerticalRate = setLowValue ? 100 : 200; break; case AircraftComparerColumn.WakeTurbulenceCategory: aircraft.WakeTurbulenceCategory = setLowValue ? WakeTurbulenceCategory.Light : WakeTurbulenceCategory.Heavy; break; default: throw new NotImplementedException(); } }
private static void IncreaseSpeedOfSeaBird(IAircraft seabird) { Console.WriteLine("\nExperiment 3: Increase the speed of the Seabird:"); (seabird as ISeacraft).IncreaseRevs(); (seabird as ISeacraft).IncreaseRevs(); if (seabird.Airborne) Console.WriteLine("Seabird flying at height " + seabird.Height + " metres and speed " + (seabird as ISeacraft).Speed + " knots"); Console.WriteLine("Experiments successful; the Seabird flies!"); }
/// <summary> /// See interface docs. /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> public int Compare(IAircraft x, IAircraft y) { int result = Object.ReferenceEquals(x, y) ? 0 : -1; if(result != 0) { for(int i = result = 0;result == 0 && i < SortBy.Count;++i) { result = CompareColumn(x, y, result, SortBy[i].Key, SortBy[i].Value); } } return result; }
public void TestInitialise() { _ClassFactorySnapshot = Factory.TakeSnapshot(); _FlightSimulatorX = TestUtilities.CreateMockImplementation<IFlightSimulatorX>(); _FlightSimulatorX.Setup(fsx => fsx.IsInstalled).Returns(true); _ConfigurationStorage = TestUtilities.CreateMockSingleton<IConfigurationStorage>(); _Configuration = new Configuration(); _ConfigurationStorage.Setup(c => c.Load()).Returns(_Configuration); _Log = TestUtilities.CreateMockSingleton<ILog>(); _Presenter = Factory.Singleton.Resolve<IFlightSimulatorXPresenter>(); _Provider = new Mock<IFlightSimulatorXPresenterProvider>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties(); _Provider.Setup(p => p.UtcNow).Returns(DateTime.UtcNow); _LimitTimedInvokeCallbacks = 1; int callbacks = 0; _Provider.Setup(p => p.TimedInvokeOnBackgroundThread(It.IsAny<Action>(), It.IsAny<int>())).Callback((Action callback, int milliseconds) => { if(callbacks++ < _LimitTimedInvokeCallbacks) callback(); }); _Presenter.Provider = _Provider.Object; _SelectedAircraft = new Mock<IAircraft>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties().Object; _View = new Mock<IFlightSimulatorXView>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties(); _View.Setup(v => v.CanBeRefreshed).Returns(true); _View.Setup(v => v.SelectedRealAircraft).Returns(_SelectedAircraft); _BaseStationAircraftList = new Mock<IBaseStationAircraftList>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties(); _FlightSimulatorAircraftList = new Mock<ISimpleAircraftList>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties(); long trash1, trash2; _RealAircraftList = new List<IAircraft>(); _BaseStationAircraftList.Setup(b => b.TakeSnapshot(out trash1, out trash2)).Returns(_RealAircraftList); _FSXAircraftList = new List<IAircraft>(); var syncLock = new object(); _FlightSimulatorAircraftList.Setup(f => f.Aircraft).Returns(_FSXAircraftList); _FlightSimulatorAircraftList.Setup(f => f.ListSyncLock).Returns(syncLock); _WebServer = new Mock<IWebServer>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties(); _Presenter.BaseStationAircraftList = _BaseStationAircraftList.Object; _Presenter.FlightSimulatorAircraftList = _FlightSimulatorAircraftList.Object; _Presenter.WebServer = _WebServer.Object; }
/// <summary> /// Returns a model given an aircraft list and a point to measure from. /// </summary> /// <param name="aircraftList"></param> /// <param name="originLatitude"></param> /// <param name="originLongitude"></param> /// <returns></returns> public static ProximityGadgetAircraftJson ToModel(IEnumerable <IAircraft> aircraftList, double?originLatitude, double?originLongitude) { ProximityGadgetAircraftJson result = null; if (aircraftList != null) { result = new ProximityGadgetAircraftJson(); if (originLatitude == null || originLongitude == null) { result.WarningMessage = "Position not supplied"; } else { IAircraft closestAircraft = null; double? closestDistance = null; foreach (var aircraft in aircraftList) { double?distance = null; if (aircraft.Latitude != null && aircraft.Longitude != null) { distance = GreatCircleMaths.Distance(originLatitude, originLongitude, aircraft.Latitude, aircraft.Longitude); if (distance != null && closestAircraft == null || distance < closestDistance) { closestAircraft = aircraft; closestDistance = distance; } } if (aircraft.Emergency == true) { result.EmergencyAircraft.Add(ProximityGadgetClosestAircraftJson.ToModel(aircraft, originLatitude, originLongitude)); } } if (closestAircraft != null) { result.ClosestAircraft = ProximityGadgetClosestAircraftJson.ToModel(closestAircraft, originLatitude, originLongitude); } } } return(result); }
/// <summary> /// Updates an existing aircraft in the list. /// </summary> /// <param name="aircraft"></param> /// <param name="item"></param> private void UpdateAircraftInList(IAircraft aircraft, ListViewItem item) { if (item.SubItems[0].Text != aircraft.Registration) { item.SubItems[0].Text = aircraft.Registration; } if (item.SubItems[1].Text != aircraft.Icao24) { item.SubItems[1].Text = aircraft.Icao24; } if (item.SubItems[2].Text != aircraft.Type) { item.SubItems[2].Text = aircraft.Type; } if (item.SubItems[3].Text != aircraft.Operator) { item.SubItems[3].Text = aircraft.Operator; } item.Tag = aircraft; }
public void Notify(IAircraft sender, RequestType id) { if (id == RequestType.Landing) { foreach (var personel in GroundPersonnel) { personel.commDevice.receive(personel, id); } HandleRequestLanding(sender); } else if (id == RequestType.TakeOff) { foreach (var personel in GroundPersonnel) { personel.commDevice.receive(personel, id); } HandleRequestTakeoff(sender); } }
/// <summary> /// Creates a new model from an aircraft object passed across. The aircraft passed in is assumed to be a clone, i.e. /// the properties on the aircraft cannot change over the lifetime of the call. /// </summary> /// <param name="aircraft"></param> /// <param name="originLatitude">The latitude to measure distances from.</param> /// <param name="originLongitude">The longitude to measure distances from.</param> /// <returns></returns> public static ProximityGadgetClosestAircraftJson ToModel(IAircraft aircraft, double?originLatitude, double?originLongitude) { ProximityGadgetClosestAircraftJson result = null; if (aircraft != null) { double?distance = null; if (aircraft.Latitude != null && aircraft.Longitude != null) { distance = GreatCircleMaths.Distance(originLatitude, originLongitude, aircraft.Latitude, aircraft.Longitude); } result = new ProximityGadgetClosestAircraftJson() { Altitude = FormatNullable(aircraft.Altitude), BearingFromHere = FormatNullable(GreatCircleMaths.Bearing(originLatitude, originLongitude, aircraft.Latitude, aircraft.Longitude, null, false, false), null, 1), Callsign = aircraft.Callsign, Destination = aircraft.Destination, DistanceFromHere = FormatNullable(distance, null, 2), Emergency = aircraft.Emergency.GetValueOrDefault(), GroundSpeed = FormatNullable(aircraft.GroundSpeed), HasPicture = !String.IsNullOrEmpty(aircraft.PictureFileName), Icao24 = aircraft.Icao24 ?? "", Icao24Invalid = aircraft.Icao24Invalid, Latitude = FormatNullable(aircraft.Latitude), Longitude = FormatNullable(aircraft.Longitude), Manufacturer = aircraft.Manufacturer, Model = aircraft.Model, Operator = aircraft.Operator, OperatorIcao = aircraft.OperatorIcao, Origin = aircraft.Origin, Registration = aircraft.Registration, Squawk = aircraft.Squawk.GetValueOrDefault() == 0 ? null : String.Format("{0:0000}", aircraft.Squawk), Track = FormatNullable(aircraft.Track, null, 1), Type = aircraft.Type, VerticalRate = FormatNullable(aircraft.VerticalRate), }; } return(result); }
/// <summary> /// Add to Dictionary and return AirTarget ref of the adde missile /// </summary> /// <param name="missileScript"></param> /// <returns>Generated Target</returns> public ITarget CreateTarget4LaunchedMissile(IMissileScript missileScript) { //Register callback to handle missile explsion event missileScript.Exploded += OnMissleExploded; //Add AircraftScript to the missile var missileAircraftScript = (MonoBehaviour)((MonoBehaviour)missileScript).gameObject.AddComponent(AircraftScript.type); missileAircraftScript.enabled = false; IAircraft tempAircraft = NewAircraft; IPartScript partScript = (IPartScript)missileAircraftScript.GetComponent(PartScript.type); var firedByName = ((MonoBehaviour)partScript.Aircraft).name; //Rename Aircraft tempAircraft.Name = $"{missileAircraftScript.name} ({firedByName})"; //Set AircraftScript values AircraftScript.InvokeMethod("set_Aircraft", missileAircraftScript, new object[] { tempAircraft }); ((IAircraftScript)missileAircraftScript).MainCockpit = partScript; //Create the target presenting missile var target = (ITarget)AirTarget.type.GetConstructor(new Type[] { AircraftScript.type }).Invoke(new object[] { missileAircraftScript }); aircraftLaunchedMissiles.Add(target, new MissileInfo((IAircraftScript)missileAircraftScript, (IMissileScript)missileScript)); return(target); }
public string IsAirplaneInFinalRunway(IAircraft airplane, double direction = 0) { string name = String.Empty; double degreesAperture = 5; double finalOneDirection = MapMathHelper.GetAngle(this.PositionSideOne.Longitude, this.PositionSideTwo.Longitude, this.PositionSideOne.Latitude, this.PositionSideTwo.Latitude); double finalTwoDirection = MapMathHelper.GetAngle(this.PositionSideTwo.Longitude, this.PositionSideOne.Longitude, this.PositionSideTwo.Latitude, this.PositionSideOne.Latitude); double degreesOneFromPosition = MapMathHelper.GetAngle(this.PositionSideOne.Longitude, airplane.Position.Longitude, this.PositionSideOne.Latitude, airplane.Position.Latitude); double degreesTwoFromPosition = MapMathHelper.GetAngle(this.PositionSideTwo.Longitude, airplane.Position.Longitude, this.PositionSideTwo.Latitude, airplane.Position.Latitude); bool isTargetInAngleFromOne = finalOneDirection - degreesAperture <degreesOneFromPosition && finalOneDirection + degreesAperture> degreesOneFromPosition; bool isTargetInAngleFromTwo = finalTwoDirection - degreesAperture <degreesTwoFromPosition && finalTwoDirection + degreesAperture> degreesTwoFromPosition; if (isTargetInAngleFromOne && airplane.VerticalSpeed < 0 || isTargetInAngleFromTwo && airplane.VerticalSpeed > 0) { name = this.PositionSideTwo.Description; } else if (isTargetInAngleFromOne && airplane.VerticalSpeed > 0 || isTargetInAngleFromTwo && airplane.VerticalSpeed < 0) { name = this.PositionSideOne.Description; } return(name); }
/// <summary> /// Returns the English description of the engine type of the aircraft passed across. /// </summary> /// <param name="aircraft"></param> /// <returns></returns> private string EngineTypeDescription(IAircraft aircraft) { return(aircraft.EngineType == EngineType.None ? "" : aircraft.EngineType.ToString()); }
public Seabird_NEW(IAircraft aircraft) { this.aircraft = aircraft; }
public void TestInitialise() { _Aircraft = Factory.Singleton.Resolve<IAircraft>(); }
/// <summary> /// Builds the full or short coordinates list and attaches it to the aircraft JSON object. /// </summary> /// <param name="shortCoordinates"></param> /// <param name="firstTimeSeen"></param> /// <param name="aircraftJson"></param> /// <param name="aircraftSnapshot"></param> /// <param name="args"></param> /// <param name="sendAltitude"></param> /// <param name="sendSpeed"></param> private void BuildCoordinatesList(bool shortCoordinates, bool firstTimeSeen, AircraftJson aircraftJson, IAircraft aircraftSnapshot, AircraftListJsonBuilderArgs args, bool sendAltitude, bool sendSpeed) { aircraftJson.ResetTrail = firstTimeSeen || args.ResendTrails || aircraftSnapshot.FirstCoordinateChanged > args.PreviousDataVersion; List <double?> list = new List <double?>(); List <Coordinate> coordinates = shortCoordinates ? aircraftSnapshot.ShortCoordinates : aircraftSnapshot.FullCoordinates; Coordinate lastCoordinate = null; Coordinate nextCoordinate = null; for (var i = 0; i < coordinates.Count; ++i) { var coordinate = nextCoordinate ?? coordinates[i]; nextCoordinate = i + 1 == coordinates.Count ? null : coordinates[i + 1]; if (aircraftJson.ResetTrail || coordinate.DataVersion > args.PreviousDataVersion) { // If this is a full coordinate list then entries can be in here that only record a change in altitude or speed, and not a change in track. Those // entries are to be ignored. They can be identified by having a track that is the same as their immediate neighbours in the list. if (!shortCoordinates && lastCoordinate != null && nextCoordinate != null) { var dupeHeading = lastCoordinate.Heading == coordinate.Heading && coordinate.Heading == nextCoordinate.Heading; if (dupeHeading && !sendAltitude && !sendSpeed) { continue; } var dupeAltitude = lastCoordinate.Altitude == coordinate.Altitude && coordinate.Altitude == nextCoordinate.Altitude; if (sendAltitude && dupeHeading && dupeAltitude) { continue; } var dupeSpeed = lastCoordinate.GroundSpeed == coordinate.GroundSpeed && coordinate.GroundSpeed == nextCoordinate.GroundSpeed; if (sendSpeed && dupeHeading && dupeSpeed) { continue; } } list.Add(Round.Coordinate(coordinate.Latitude)); list.Add(Round.Coordinate(coordinate.Longitude)); if (shortCoordinates) { list.Add(JavascriptHelper.ToJavascriptTicks(coordinate.Tick)); } else { list.Add((int?)coordinate.Heading); } if (sendAltitude) { list.Add(coordinate.Altitude); } else if (sendSpeed) { list.Add(coordinate.GroundSpeed); } } lastCoordinate = coordinate; } if (aircraftSnapshot.Latitude != null && aircraftSnapshot.Longitude != null && (lastCoordinate.Latitude != aircraftSnapshot.Latitude || lastCoordinate.Longitude != aircraftSnapshot.Longitude) && aircraftSnapshot.PositionTimeChanged > args.PreviousDataVersion) { list.Add(Round.Coordinate(aircraftSnapshot.Latitude)); list.Add(Round.Coordinate(aircraftSnapshot.Longitude)); if (shortCoordinates) { list.Add(JavascriptHelper.ToJavascriptTicks(aircraftSnapshot.PositionTime.Value)); } else { list.Add((int?)Round.TrackHeading(aircraftSnapshot.Track)); } if (sendAltitude) { list.Add(Round.TrackAltitude(aircraftSnapshot.Altitude)); } else if (sendSpeed) { list.Add(Round.TrackGroundSpeed(aircraftSnapshot.GroundSpeed)); } } if (list.Count != 0) { if (shortCoordinates) { aircraftJson.ShortCoordinates = list; } else { aircraftJson.FullCoordinates = list; } } }
/// <summary> /// Returns the English description of the species of the aircraft passed across. /// </summary> /// <param name="aircraft"></param> /// <returns></returns> private string SpeciesDescription(IAircraft aircraft) { return aircraft.Species == Species.None ? "" : aircraft.Species.ToString(); }
public AircraftSelectionDataItem(IAircraft aircraft, DataGroup @group) : this(aircraft, @group, 15, 20) { }
/// <summary> /// See interface docs. /// </summary> /// <param name="aircraft"></param> public void RefreshPicture(IAircraft aircraft) { if(aircraft == null) throw new ArgumentNullException("aircraft"); IAircraft actualAircraft; lock(_AircraftMapLock) _AircraftMap.TryGetValue(aircraft.UniqueId, out actualAircraft); if(actualAircraft != null) _PictureLookupQueue.Enqueue(actualAircraft); }
private void SetProperties(IAircraft aircraft) { Version = aircraft.Version; Title = aircraft.AircraftType; }
/// <summary> /// Creates a new object /// </summary> /// <param name="aircraft">The aircraft to look up in the database.</param> /// <param name="queueForRefresh">True if another lookup should be scheduled if the aircraft is either missing from the database /// or the record on the database is incomplete.</param> /// <param name="alwaysRefreshPicture">Usually the aircraft picture is only refreshed if the aircraft has a registration added by /// the database lookup - this parameter can force a lookup even if the registration is missing or not found.</param> public DatabaseLookup(IAircraft aircraft, bool queueForRefresh, bool alwaysRefreshPicture) { Aircraft = aircraft; QueueForRefresh = queueForRefresh; AlwaysRefreshPicture = alwaysRefreshPicture; }
/// <summary> /// See interface docs. /// </summary> /// <param name="aircraft"></param> public void RefreshDatabaseDetails(IAircraft aircraft) { if(aircraft == null) throw new ArgumentNullException("aircraft"); IAircraft actualAircraft; lock(_AircraftMapLock) _AircraftMap.TryGetValue(aircraft.UniqueId, out actualAircraft); if(actualAircraft != null) _DatabaseLookupQueue.Enqueue(new DatabaseLookup(actualAircraft, false, false)); }
private void HandleRequestTakeoff(IAircraft sender) { sender.TakeoffGranted(); Console.WriteLine("Take off granted for {0}", sender); }
private void HandleRequestLanding(IAircraft sender) { sender.LandingGranted(); Console.WriteLine("Landing granted for {0}", sender); }
/// <summary> /// Builds the full or short coordinates list and attaches it to the aircraft JSON object. /// </summary> /// <param name="shortCoordinates"></param> /// <param name="firstTimeSeen"></param> /// <param name="aircraftJson"></param> /// <param name="aircraftSnapshot"></param> /// <param name="args"></param> private void BuildCoordinatesList(bool shortCoordinates, bool firstTimeSeen, AircraftJson aircraftJson, IAircraft aircraftSnapshot, AircraftListJsonBuilderArgs args) { aircraftJson.ResetTrail = firstTimeSeen || args.ResendTrails || aircraftSnapshot.FirstCoordinateChanged > args.PreviousDataVersion; List <double?> list = new List <double?>(); Coordinate lastCoordinate = null; foreach (var coordindate in shortCoordinates ? aircraftSnapshot.ShortCoordinates : aircraftSnapshot.FullCoordinates) { if (aircraftJson.ResetTrail || coordindate.DataVersion > args.PreviousDataVersion) { list.Add(Round.Coordinate(coordindate.Latitude)); list.Add(Round.Coordinate(coordindate.Longitude)); if (shortCoordinates) { list.Add(JavascriptHelper.ToJavascriptTicks(coordindate.Tick)); } else { list.Add(Round.Track(coordindate.Heading)); } } lastCoordinate = coordindate; } if (aircraftSnapshot.Latitude != null && aircraftSnapshot.Longitude != null && (lastCoordinate.Latitude != aircraftSnapshot.Latitude || lastCoordinate.Longitude != aircraftSnapshot.Longitude) && aircraftSnapshot.PositionTimeChanged > args.PreviousDataVersion) { list.Add(Round.Coordinate(aircraftSnapshot.Latitude)); list.Add(Round.Coordinate(aircraftSnapshot.Longitude)); if (shortCoordinates) { list.Add(JavascriptHelper.ToJavascriptTicks(aircraftSnapshot.PositionTime.Value)); } else { list.Add(Round.Track(aircraftSnapshot.Track)); } } if (list.Count != 0) { if (shortCoordinates) { aircraftJson.ShortCoordinates = list; } else { aircraftJson.FullCoordinates = list; } } }
public Key(IAircraft aircraft) { Icao24 = aircraft.Icao24; Callsign = aircraft.Callsign; OperatorIcao = aircraft.OperatorIcao; }
private static void ApplyAircraftType(IAircraft aircraft, AircraftType typeDetails) { if(typeDetails != null) { aircraft.NumberOfEngines = typeDetails.Engines; aircraft.EngineType = typeDetails.EngineType; aircraft.Species = typeDetails.Species; aircraft.WakeTurbulenceCategory = typeDetails.WakeTurbulenceCategory; } }
/// <summary> /// Returns the list view item for the aircraft passed across or null if there is no row for the aircraft. /// </summary> /// <param name="aircraft"></param> /// <returns></returns> private ListViewItem FindItem(IAircraft aircraft) { ListViewItem result = null; foreach(ListViewItem item in listView.Items) { var tag = (IAircraft)item.Tag; if(tag.UniqueId == aircraft.UniqueId) { result = item; break; } } return result; }
/// <summary> /// Applies the code block to the aircraft. /// </summary> /// <param name="aircraft"></param> /// <param name="codeBlock"></param> private static void ApplyCodeBlock(IAircraft aircraft, CodeBlock codeBlock) { if(codeBlock != null) { aircraft.Icao24Country = codeBlock.Country; aircraft.IsMilitary = codeBlock.IsMilitary; } }
/// <summary> /// Returns the distance from the browser to the aircraft. If the aircraft is in the <see cref="PrecalculatedDistances"/> map then /// the pre-calculated distance is returned. /// </summary> /// <param name="aircraft"></param> /// <returns></returns> private double? CalculateDistance(IAircraft aircraft) { double? result; if(!PrecalculatedDistances.TryGetValue(aircraft.UniqueId, out result)) { result = GreatCircleMaths.Distance(BrowserLocation.Latitude, BrowserLocation.Longitude, aircraft.Latitude, aircraft.Longitude); } return result; }
private void ApplyMessageToAircraft(BaseStationMessage message, IAircraft aircraft, bool isNewAircraft) { // We want to retrieve all of the lookups without writing anything to the aircraft. Then all of the values // that need changing on the aircraft will be set in one lock with one DataVersion so they're all consistent. CodeBlock codeBlock = null; Route route = null; if(isNewAircraft) codeBlock = StandingDataManager.FindCodeBlock(message.Icao24); bool callsignChanged; string operatorIcao; lock(aircraft) { // <-- nothing should be changing Callsign, we're the only thread that writes it, but just in case... callsignChanged = !String.IsNullOrEmpty(message.Callsign) && message.Callsign != aircraft.Callsign; operatorIcao = aircraft.OperatorIcao; } if(callsignChanged) route = LookupRoute(message.Callsign, operatorIcao); var track = CalculateTrack(message, aircraft); lock(aircraft) { var now = Provider.UtcNow; GenerateDataVersion(aircraft); aircraft.LastUpdate = now; ++aircraft.CountMessagesReceived; if(isNewAircraft) aircraft.FirstSeen = now; if(aircraft.Icao24 == null) aircraft.Icao24 = message.Icao24; if(!String.IsNullOrEmpty(message.Callsign)) aircraft.Callsign = message.Callsign; if(message.Altitude != null) aircraft.Altitude = message.Altitude; if(message.GroundSpeed != null) aircraft.GroundSpeed = message.GroundSpeed; if(track != null) aircraft.Track = track; if(message.Track != null && message.Track != 0.0) aircraft.IsTransmittingTrack = true; if(message.Latitude != null) aircraft.Latitude = message.Latitude; if(message.Longitude != null) aircraft.Longitude = message.Longitude; if(message.VerticalRate != null) aircraft.VerticalRate = message.VerticalRate; if(message.OnGround != null) aircraft.OnGround = message.OnGround; if(message.Squawk != null) { aircraft.Squawk = message.Squawk; aircraft.Emergency = message.Squawk == 7500 || message.Squawk == 7600 || message.Squawk == 7700; } var supplementaryMessage = message != null && message.Supplementary != null ? message.Supplementary : null; if(supplementaryMessage != null) { if(supplementaryMessage.SpeedType != null) aircraft.SpeedType = supplementaryMessage.SpeedType.Value; if(supplementaryMessage.CallsignIsSuspect != null) aircraft.CallsignIsSuspect = supplementaryMessage.CallsignIsSuspect.Value; } ApplyCodeBlock(aircraft, codeBlock); ApplyRoute(aircraft, route); if(message.Latitude != null && message.Longitude != null) aircraft.UpdateCoordinates(now, _ShortTrailLengthSeconds); } if(isNewAircraft) _DatabaseLookupQueue.Enqueue(new DatabaseLookup(aircraft, true, true)); }
/// <summary> /// Experiment 2: Classic usage of an adapter /// </summary> private static void ExecuteExperiment2(IAircraft seabird) { Console.WriteLine("\nExperiment 2: Use the engine in the Seabird"); seabird.TakeOff(); // And automatically increases speed Console.WriteLine("The Seabird took off"); }
/// <summary> /// Applies route data to the aircraft. /// </summary> /// <param name="aircraft"></param> /// <param name="route"></param> private void ApplyRoute(IAircraft aircraft, Route route) { if(route != null) { aircraft.Origin = Describe.Airport(route.From, _PreferIataAirportCodes); aircraft.Destination = Describe.Airport(route.To, _PreferIataAirportCodes); foreach(var stopover in route.Stopovers) { aircraft.Stopovers.Add(Describe.Airport(stopover, _PreferIataAirportCodes)); } } }
/// <summary> /// Creates an object that represents an aircraft in <see cref="ProximityGadgetAircraftJson"/>. /// </summary> /// <param name="aircraft"></param> /// <param name="distance"></param> /// <param name="latitude"></param> /// <param name="longitude"></param> /// <returns></returns> private ProximityGadgetClosestAircraftJson CreateProximityGadgetClosestAircraftJson(IAircraft aircraft, double? distance, double? latitude, double? longitude) { var result = new ProximityGadgetClosestAircraftJson() { Altitude = FormatNullable(aircraft.Altitude), BearingFromHere = FormatNullable(GreatCircleMaths.Bearing(latitude, longitude, aircraft.Latitude, aircraft.Longitude, null, false, false), null, 1), Callsign = aircraft.Callsign, Destination = aircraft.Destination, DistanceFromHere = FormatNullable(distance, null, 2), Emergency = aircraft.Emergency.GetValueOrDefault(), GroundSpeed = FormatNullable(aircraft.GroundSpeed), HasPicture = !String.IsNullOrEmpty(aircraft.PictureFileName), Icao24 = aircraft.Icao24 ?? "", Icao24Invalid = aircraft.Icao24Invalid, Latitude = FormatNullable(aircraft.Latitude), Longitude = FormatNullable(aircraft.Longitude), Manufacturer = aircraft.Manufacturer, Model = aircraft.Model, Operator = aircraft.Operator, OperatorIcao = aircraft.OperatorIcao, Origin = aircraft.Origin, Registration = aircraft.Registration, Squawk = aircraft.Squawk.GetValueOrDefault() == 0 ? null : String.Format("{0:0000}", aircraft.Squawk), Track = FormatNullable(aircraft.Track, null, 1), Type = aircraft.Type, VerticalRate = FormatNullable(aircraft.VerticalRate), }; result.Stopovers.AddRange(aircraft.Stopovers); return result; }
/// <summary> /// If the message contains a track then it is simply returned, otherwise if it's possible to calculate the track then /// it is calculated and returned. /// </summary> /// <param name="message"></param> /// <param name="aircraft"></param> /// <returns></returns> private float? CalculateTrack(BaseStationMessage message, IAircraft aircraft) { var result = message.Track; var onGround = message.OnGround.GetValueOrDefault(); var positionPresent = message.Latitude != null && message.Longitude != null; var trackNeverTransmitted = !aircraft.IsTransmittingTrack; if(result == 0.0 && trackNeverTransmitted) result = null; if(positionPresent && (onGround || trackNeverTransmitted)) { TrackCalculationParameters calcParameters; lock(_AircraftMapLock) { _CalculatedTrackCoordinates.TryGetValue(aircraft.UniqueId, out calcParameters); if(calcParameters != null && onGround && calcParameters.TrackFrozenAt.AddMinutes(30) <= Provider.UtcNow) { _CalculatedTrackCoordinates.Remove(aircraft.UniqueId); calcParameters = null; } } var trackSuspect = message.Track == null || message.Track == 0.0; var trackFrozen = onGround && (calcParameters == null || calcParameters.TrackFrozen); if(trackSuspect || trackFrozen) { var trackCalculated = false; if(calcParameters == null) { calcParameters = new TrackCalculationParameters() { LastLatitude = message.Latitude.Value, LastLongitude = message.Longitude.Value, LastTransmittedTrack = message.Track, TrackFrozen = true, TrackFrozenAt = Provider.UtcNow }; lock(_AircraftMapLock) _CalculatedTrackCoordinates.Add(aircraft.UniqueId, calcParameters); trackCalculated = true; } else if(message.Latitude != calcParameters.LastLatitude || message.Longitude != calcParameters.LastLongitude) { if(trackFrozen && onGround && calcParameters.LastTransmittedTrack != message.Track) { trackFrozen = calcParameters.TrackFrozen = false; } if(trackSuspect || trackFrozen) { var minimumDistanceKm = message.OnGround.GetValueOrDefault() ? 0.010 : 0.25; if(GreatCircleMaths.Distance(message.Latitude, message.Longitude, calcParameters.LastLatitude, calcParameters.LastLongitude).GetValueOrDefault() >= minimumDistanceKm) { result = (float?)GreatCircleMaths.Bearing(calcParameters.LastLatitude, calcParameters.LastLongitude, message.Latitude, message.Longitude, null, false, false); result = Round.Track(result); calcParameters.LastLatitude = message.Latitude.Value; calcParameters.LastLongitude = message.Longitude.Value; trackCalculated = true; } calcParameters.LastTransmittedTrack = message.Track; } } if(!trackCalculated && (trackSuspect || trackFrozen)) result = aircraft.Track; } } return result; }
static void Main(string[] args) { var planes = new IAircraft[] { //(planeNumber, maxFuel) new Plane("3HF543", 250), new Plane("3GJ234", 200), new Plane("3SD654", 350), new Plane("3KJ897", 150), //(planeNumber, numberOfSeats) new SailPlane("3HC943", 1), new SailPlane("3GLC34", 2), }; foreach (var x in planes) { Console.WriteLine($"{x.PlaneNumber} {x.NumberOfSeats} "); if (x is Plane) { Plane p = x as Plane; Console.WriteLine(p.ShowMaxFuelInfo()); } } var plan = new Plane("3KL654", 50); string s = JsonConvert.SerializeObject(plan); Console.WriteLine(); Console.WriteLine(s); var xx = JsonConvert.DeserializeObject<Plane>(s); var plan2 = new SailPlane("3QW344", 35); string s2 = JsonConvert.SerializeObject(plan2); Console.WriteLine(); Console.WriteLine(s2); var xx2 = JsonConvert.DeserializeObject<SailPlane>(s2); Console.WriteLine(); Console.WriteLine(); var setting = new JsonSerializerSettings() { Formatting = Formatting.Indented, TypeNameHandling = TypeNameHandling.Auto, }; Console.WriteLine(JsonConvert.SerializeObject(planes, setting)); Console.WriteLine(); Console.WriteLine(); var text = JsonConvert.SerializeObject(planes, setting); var desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); var filename = Path.Combine(desktop, "planes.json"); File.WriteAllText(filename, text); var textFromFile = File.ReadAllText(filename); var itemsFromFile = JsonConvert.DeserializeObject<IAircraft[]>(textFromFile, setting); foreach (var x in itemsFromFile) Console.WriteLine($"{x.PlaneNumber} {x.NumberOfSeats} "); Console.WriteLine(); Console.WriteLine(); var producer = new Subject<Plane>(); producer.Subscribe(plane => Console.WriteLine($"received value {plane}")); foreach (var x in planes) { System.Threading.Thread.Sleep(TimeSpan.FromSeconds(1)); if (x is Plane) { Plane p = x as Plane; producer.OnNext(p); // push value i to subscribers } } Console.ReadLine(); ///ALter Code TASK 1 & 2 //(ist ähnlich wie das malloc, nur naturlich besser :-D ) //var planes = new List<Plane>(); //erstelln von FLugzeugen(Daten) //var plane1 = new Plane("3HF543", 250); //var plane2 = new Plane("3GJ234", 200); //var plane3 = new Plane("3SD654", 350); //var plane4 = new Plane("3KJ897", 150); //hinzufügen zu Daten //planes.Add(plane1); //planes.Add(plane2); //planes.Add(plane3); //planes.Add(plane4); //Schleife zum ausgeben //foreach (var plane in planes) //{ // Console.WriteLine("Number of Seats:{0} Plane Number: {1}",plane.NumberOfSeats, plane.PlaneNumber); //Console.WriteLine("Max Fuel Info:{0}", plane.ShowMaxFuelInfo()); //} //Beispiel zum nutzen von "set;" //Änder der Anzahl der sitze von einem bestimmten Flugzeug //plane2.NumberOfSeats = 10; //sogrt für eine leerezeile so ähnlich "\n" //Schleife zum ausgeben, aber diesmal mit der änderung //foreach (var plane in planes) //{ // Console.WriteLine("Number of Seats:{0} Plane Number: {1}", plane.NumberOfSeats, plane.PlaneNumber); // Console.WriteLine("Max Fuel Info:{0}", plane.ShowMaxFuelInfo()); //} //Console.WriteLine(); //var sailPlanes = new List<SailPlane>(); //var sailplane1 = new SailPlane("3HC943", 1); //var sailplane2 = new SailPlane("3GLC34", 2); //sailPlanes.Add(sailplane1); //sailPlanes.Add(sailplane2); //foreach (var sailplane in sailPlanes) //{ // Console.WriteLine("Number of Seats:{0} Plane Number: {1}", sailplane.NumberOfSeats, sailplane.PlaneNumber); //} /// }
/// <summary> /// Sets a valid DataVersion. Always lock the aircraft map before calling this. /// </summary> /// <param name="aircraft"></param> /// <remarks> /// The tests call for this to be based on UtcNow, the idea being that if the webServer is quit and restarted while /// a browser is connected the chances are good that the browser data version will correspond with the data versions /// held by the new instance of the webServer. Not sure how useful that will be but it's not hard to do. However there /// are times when we cannot use UTC - if the clock gets reset or if two messages come in on the same tick. When that /// happens we just fallback to incrementing the dataversion. /// </remarks> private void GenerateDataVersion(IAircraft aircraft) { // This can be called on any of the threads that update the list. The _DataVersionLock value is really a property of // the aircraft map - it represents the highest possible DataVersion of any aircraft within the map. The caller should // have established a lock on the aircraft map before calling us to ensure that snapshots of the map are not taken until // all changes that involve a new DataVersion have been applied, but just in case they don't we get it again here. If // we don't, and if they forgot to acquire the lock, then we could get inconsistencies. lock(_AircraftMapLock) { lock(aircraft) { var dataVersion = Provider.UtcNow.Ticks; if(dataVersion <= _DataVersion) dataVersion = _DataVersion + 1; aircraft.DataVersion = _DataVersion = dataVersion; } } }
/// <summary> /// Returns true if the aircraft passes the filter criteria passed across. /// </summary> /// <param name="aircraft"></param> /// <param name="args"></param> /// <param name="distances"></param> /// <returns></returns> private bool PassesFilter(IAircraft aircraft, AircraftListJsonBuilderArgs args, Dictionary <int, double?> distances) { var filter = args.Filter; bool result = filter == null; var distance = args.IsFlightSimulatorList ? null : GreatCircleMaths.Distance(args.BrowserLatitude, args.BrowserLongitude, aircraft.Latitude, aircraft.Longitude); if (!result) { result = true; if (result && filter.Altitude != null) { result = filter.Altitude.Passes(aircraft.Altitude); } if (result && filter.Callsign != null) { result = filter.Callsign.Passes(aircraft.Callsign); } if (result && filter.EngineType != null) { result = filter.EngineType.Passes(aircraft.EngineType); } if (result && filter.Icao24 != null) { result = filter.Icao24.Passes(aircraft.Icao24); } if (result && filter.Icao24Country != null) { result = filter.Icao24Country.Passes(aircraft.Icao24Country); } if (result && filter.IsInteresting != null) { result = filter.IsInteresting.Passes(aircraft.IsInteresting); } if (result && filter.IsMilitary != null) { result = filter.IsMilitary.Passes(aircraft.IsMilitary); } if (result && filter.MustTransmitPosition != null) { result = filter.MustTransmitPosition.Passes(aircraft.Latitude != null && aircraft.Longitude != null); } if (result && filter.Operator != null) { result = filter.Operator.Passes(aircraft.Operator); } if (result && filter.OperatorIcao != null) { result = filter.OperatorIcao.Passes(aircraft.OperatorIcao); } if (result && filter.PositionWithin != null) { result = args.SelectedAircraftId == aircraft.UniqueId || IsWithinBounds(aircraft.Latitude, aircraft.Longitude, filter.PositionWithin); } if (result && filter.Registration != null) { result = filter.Registration.Passes(aircraft.Registration); } if (result && filter.Species != null) { result = filter.Species.Passes(aircraft.Species); } if (result && filter.Squawk != null) { result = filter.Squawk.Passes(aircraft.Squawk); } if (result && filter.Type != null) { result = filter.Type.Passes(aircraft.Type); } if (result && filter.UserTag != null) { result = filter.UserTag.Passes(aircraft.UserTag); } if (result && filter.WakeTurbulenceCategory != null) { result = filter.WakeTurbulenceCategory.Passes(aircraft.WakeTurbulenceCategory); } if (result && filter.Airport != null) { result = PassesAirportFilter(filter.Airport, aircraft); } if (result && filter.Distance != null) { if (distance == null && filter.Distance.IsValid) { result = false; } else { result = filter.Distance.Passes(distance); } } } if (result) { distances.Add(aircraft.UniqueId, distance); } return(result); }
/// <summary> /// Looks for the picture filename for the aircraft. /// </summary> /// <param name="aircraft"></param> private void SearchForPicture(IAircraft aircraft) { string icao24, registration, oldFileName; lock(aircraft) { icao24 = aircraft.Icao24; registration = aircraft.Registration; oldFileName = aircraft.PictureFileName; } var fileName = _PictureManager.FindPicture(_PictureDirectoryCache, icao24, registration); if(oldFileName != fileName) { // We need to make sure that any locks are applied in the same order as any other thread that is modifying DataVersion. lock(_AircraftMapLock) { lock(aircraft) { GenerateDataVersion(aircraft); aircraft.PictureFileName = fileName; } } } }
public static WindowsPilot Create( IAircraft aircraft, IGyroscope3 gyroscope, IAccelerometer3 accelerometer, IMagnetometer3 magnetometer, IFlightController controller, double thrustMax, double angularPositionPitchMax, double angularPositionRollMax, double angularVelocityYawMax) { var angularVelocityNoisy = new Subject <AngularVelocity3>(); var accelerationNoisy = new Subject <GForce3>(); var magnetismNoisy = new Subject <MagneticFluxDensity3>(); IObservable <AngularVelocity3> angularVelocityOptimal = angularVelocityNoisy .Filter( estimatedMeasurementNoiseCovariance: 0.0000025d, estimatedProcessNoiseCovariance: 0d, controlWeight: 0.5d * OutputFrequency / gyroscope.Frequency, initialEstimate: 0d, initialErrorCovariance: 1d) .Multiply(1.08d /*calibration*/); IObservable <GForce3> accelerationOptimal = accelerationNoisy .Filter( estimatedMeasurementNoiseCovariance: 0.025d, estimatedProcessNoiseCovariance: 0d, controlWeight: 0.5d * OutputFrequency / accelerometer.Frequency, initialEstimate: 0d, initialErrorCovariance: 1d); IObservable <MagneticFluxDensity3> magnetismOptimal = magnetismNoisy .Filter( estimatedMeasurementNoiseCovariance: 0.05d, estimatedProcessNoiseCovariance: 0d, controlWeight: 0.5d * OutputFrequency / magnetometer.Frequency, initialEstimate: 0d, initialErrorCovariance: 1d); var magnetismMinCalibration = new MagneticFluxDensity3( x: -0.273980716005263d, y: -0.245318477916743d, z: -0.237557110710227d); var magnetismMaxCalibration = new MagneticFluxDensity3( x: 0.148042531751317d, y: 0.177504483195312d, z: 0.155796981828076d); var ahrs = new Ahrs(angularVelocityOptimal, accelerationOptimal, magnetismOptimal, magnetismMinCalibration, magnetismMaxCalibration); var angularVelocityInterval = TimeSpan.FromTicks(Convert.ToInt64(TimeSpan.TicksPerSecond / gyroscope.Frequency)); var accelerationInterval = TimeSpan.FromTicks(Convert.ToInt64(TimeSpan.TicksPerSecond / accelerometer.Frequency)); var magnetismInterval = TimeSpan.FromTicks(Convert.ToInt64(TimeSpan.TicksPerSecond / magnetometer.Frequency)); var yawTimer = new Subject <object>(); var yawInterval = TimeSpan.FromTicks(Convert.ToInt64(TimeSpan.TicksPerSecond / YawFrequency)); var outputTimer = new Subject <object>(); var outputInterval = TimeSpan.FromTicks(Convert.ToInt64(TimeSpan.TicksPerSecond / OutputFrequency)); SyncLoop.ProduceAsync( angularVelocityInterval, a => gyroscope.Read(), angularVelocityNoisy, accelerationInterval, a => accelerometer.Read(), accelerationNoisy, magnetismInterval, a => magnetometer.Read(), magnetismNoisy, yawInterval, a => null, yawTimer, outputInterval, a => null, outputTimer, WorkItemPriority.High).AsTask(); IObservable <double> thrust = controller.Thrust.Select(value => value * thrustMax); IObservable <double> angularPositionPitchSetpoint = controller.Pitch.Select(value => value * angularPositionPitchMax); IObservable <double> angularPositionRollSetpoint = controller.Roll.Select(value => value * angularPositionRollMax); IObservable <double> angularPositionYawSetpoint = Extensions.ObservableExtensions .CombineLatest( controller.Yaw, yawTimer.TimeInterval(), (yaw, timer, yawChanged, timerChanged) => new { Yaw = yaw, YawChanged = yawChanged, TimerElapsed = timerChanged, TimerInterval = timer.Interval }) .Scan( default(double), (accu, t) => { double yaw = accu; if (t.TimerElapsed) { double dt = t.TimerInterval.TotalSeconds; yaw += t.Yaw * angularVelocityYawMax * dt; if (yaw > AngleConvert.ToRadians(180d)) { yaw -= AngleConvert.ToRadians(360d); } else if (yaw <= AngleConvert.ToRadians(-180d)) { yaw += AngleConvert.ToRadians(360d); } } return(yaw); }); IObservable <EulerAngles> angularPositionSetpoint = Observable.CombineLatest( angularPositionPitchSetpoint, angularPositionRollSetpoint, angularPositionYawSetpoint, (pitch, roll, yaw) => new EulerAngles(pitch, roll, yaw)); var pilot = new WindowsPilot( aircraft, thrust, angularPositionSetpoint, ahrs.AngularVelocityCalibrated, ahrs.AngularPosition); outputTimer.Subscribe(state => pilot.WriteOutput()); return(pilot); }
/// <summary> /// Sets up the filters, build arguments and aircraft for a test that confirms that combinations of filters behave correctly. /// </summary> /// <param name="filterProperty"></param> /// <param name="aircraft"></param> /// <param name="complies"></param> private void PrepareForCombinationTest(PropertyInfo filterProperty, IAircraft aircraft, bool complies) { switch(filterProperty.Name) { case "AltitudeLower": _AircraftListFilter.AltitudeLower = 10000; aircraft.Altitude = complies ? 15000 : 1000; break; case "AltitudeUpper": _AircraftListFilter.AltitudeUpper = 20000; aircraft.Altitude = complies ? 15000 : 30000; break; case "CallsignContains": _AircraftListFilter.CallsignContains = "ABC"; aircraft.Callsign = complies ? "ABC123" : "XYZ987"; break; case "DistanceLower": _AircraftListFilter.DistanceLower = 15; _AircraftListAddress.BrowserLatitude = _AircraftListAddress.BrowserLongitude = 0; aircraft.Latitude = aircraft.Longitude = complies ? 0.15F : 0.01F; break; case "DistanceUpper": _AircraftListFilter.DistanceUpper = 30; _AircraftListAddress.BrowserLatitude = _AircraftListAddress.BrowserLongitude = 0; aircraft.Latitude = aircraft.Longitude = complies ? 0.15F : 0.2F; break; case "EngineTypeEquals": _AircraftListFilter.EngineTypeEquals = EngineType.Piston; aircraft.EngineType = complies ? EngineType.Piston : EngineType.Jet; break; case "Icao24CountryContains": _AircraftListFilter.Icao24CountryContains = "UNITED"; aircraft.Icao24Country = complies ? "UNITED KINGDOM" : "BELGIUM"; break; case "IsInterestingEquals": _AircraftListFilter.IsInterestingEquals = true; aircraft.IsInteresting = complies ? true : false; break; case "IsMilitaryEquals": _AircraftListFilter.IsMilitaryEquals = true; aircraft.IsMilitary = complies ? true : false; break; case "MustTransmitPosition": _AircraftListFilter.MustTransmitPosition = true; aircraft.Latitude = aircraft.Longitude = complies ? 1F : (float?)null; break; case "OperatorContains": _AircraftListFilter.OperatorContains = "TRU"; aircraft.Operator = complies ? "ERMENUTRUDE AIRLINES" : "DOOGAL INTERNATIONAL"; break; case "PositionWithin": _AircraftListFilter.PositionWithin = new Pair<Coordinate>(new Coordinate(4F, 1F), new Coordinate(1F, 4F)); aircraft.Latitude = aircraft.Longitude = complies ? 3F : 6F; break; case "RegistrationContains": _AircraftListFilter.RegistrationContains = "GLU"; aircraft.Registration = complies ? "G-GLUE" : "G-LUUU"; break; case "SpeciesEquals": _AircraftListFilter.SpeciesEquals = Species.Helicopter; aircraft.Species = complies ? Species.Helicopter : Species.Landplane; break; case "SquawkLower": _AircraftListFilter.SquawkLower = 2000; aircraft.Squawk = complies ? 7654 : 1234; break; case "SquawkUpper": _AircraftListFilter.SquawkUpper = 4000; aircraft.Squawk = complies ? 2345 : 4567; break; case "TypeStartsWith": _AircraftListFilter.TypeStartsWith = "A38"; aircraft.Type = complies ? "A380" : "A340"; break; case "WakeTurbulenceCategoryEquals": _AircraftListFilter.WakeTurbulenceCategoryEquals = WakeTurbulenceCategory.Heavy; aircraft.WakeTurbulenceCategory = complies ? WakeTurbulenceCategory.Heavy : WakeTurbulenceCategory.Medium; break; default: Assert.Fail("Need to add code to prepare objects for {0} filter", filterProperty.Name); break; } }
/// <summary> /// Applies the fetched aircraft record to the aircraft detail, raising any events appropriate. /// </summary> /// <param name="detail"></param> /// <param name="databaseAircraft"></param> /// <param name="aircraft"></param> /// <param name="onlineAircraft"></param> /// <param name="isFirstFetch"></param> /// <param name="flightsCount"></param> private AircraftDetail ApplyDatabaseRecord(AircraftDetail detail, BaseStationAircraft databaseAircraft, AircraftOnlineLookupDetail onlineAircraft, IAircraft aircraft, bool isFirstFetch, int flightsCount = -1) { var databaseAircraftChanged = detail == null; if (!databaseAircraftChanged) { if (detail.Aircraft == null) { databaseAircraftChanged = databaseAircraft != null; } else { databaseAircraftChanged = !detail.Aircraft.Equals(databaseAircraft); if (!databaseAircraftChanged && flightsCount > -1 && flightsCount != detail.FlightsCount) { databaseAircraftChanged = true; } } } var onlineAircraftChanged = detail == null; if (!onlineAircraftChanged) { if (detail.OnlineAircraft == null) { onlineAircraftChanged = onlineAircraft != null; } else { onlineAircraftChanged = !detail.OnlineAircraft.ContentEquals(onlineAircraft); } } if (_ForceRefreshOfStandingData && detail != null) { detail.AircraftType = null; } var icaoTypeCode = databaseAircraft == null ? null : databaseAircraft.ICAOTypeCode; if (String.IsNullOrEmpty(icaoTypeCode) && onlineAircraft != null) { icaoTypeCode = onlineAircraft.ModelIcao; } var aircraftType = detail == null ? null : detail.AircraftType; var aircraftTypeChanged = detail == null; if (icaoTypeCode != null && (_ForceRefreshOfStandingData || detail == null || detail.Aircraft == null || detail.ModelIcao != icaoTypeCode)) { aircraftType = _StandingDataManager.FindAircraftType(icaoTypeCode); aircraftTypeChanged = true; } if (databaseAircraftChanged || onlineAircraftChanged || aircraftTypeChanged) { if (flightsCount == -1) { flightsCount = detail != null ? detail.FlightsCount : databaseAircraft == null ? 0 : _AutoConfigDatabase.Database.GetCountOfFlightsForAircraft(databaseAircraft, new SearchBaseStationCriteria() { Date = new FilterRange <DateTime>(DateTime.MinValue, DateTime.MaxValue), }); } detail = new AircraftDetail() { Aircraft = databaseAircraft, OnlineAircraft = onlineAircraft, AircraftType = aircraftType, FlightsCount = flightsCount, Icao24 = aircraft.Icao24, Picture = detail == null ? null : detail.Picture, }; OnFetched(new EventArgs <AircraftDetail>(detail)); } var registration = databaseAircraft != null ? databaseAircraft.Registration : aircraft.Registration; if (registration == null && onlineAircraft != null) { registration = onlineAircraft.Registration; } if (_PictureLookupThread != null) { _PictureLookupThread.Enqueue(new LookupPictureDetail() { Icao = aircraft.Icao24, Registration = registration, PictureDetail = detail == null ? null : detail.Picture, }); } return(detail); }
private void PrepareForSortTest(string sortColumn, IAircraft aircraft, bool setLow) { switch(sortColumn) { case AircraftComparerColumn.Altitude: aircraft.Altitude = setLow ? 1 : 2; break; case AircraftComparerColumn.Callsign: aircraft.Callsign = setLow ? "A" : "B"; break; case AircraftComparerColumn.Destination: aircraft.Destination = setLow ? "A" : "B"; break; case AircraftComparerColumn.DistanceFromHere: aircraft.Latitude = aircraft.Longitude = setLow ? 1 : 2; break; case AircraftComparerColumn.FirstSeen: aircraft.FirstSeen = setLow ? new DateTime(2001, 1, 1, 0, 0, 0) : new DateTime(2001, 1, 1, 0, 0, 1); break; case AircraftComparerColumn.FlightsCount: aircraft.FlightsCount = setLow ? 1 : 2; break; case AircraftComparerColumn.GroundSpeed: aircraft.GroundSpeed = setLow ? 1 : 2; break; case AircraftComparerColumn.Icao24: aircraft.Icao24 = setLow ? "A" : "B"; break; case AircraftComparerColumn.Icao24Country: aircraft.Icao24Country = setLow ? "A" : "B"; break; case AircraftComparerColumn.Model: aircraft.Model = setLow ? "A" : "B"; break; case AircraftComparerColumn.NumberOfEngines: aircraft.NumberOfEngines = setLow ? "1" : "2"; break; case AircraftComparerColumn.Operator: aircraft.Operator = setLow ? "A" : "B"; break; case AircraftComparerColumn.OperatorIcao: aircraft.OperatorIcao = setLow ? "A" : "B"; break; case AircraftComparerColumn.Origin: aircraft.Origin = setLow ? "A" : "B"; break; case AircraftComparerColumn.Registration: aircraft.Registration = setLow ? "A" : "B"; break; case AircraftComparerColumn.Species: aircraft.Species = setLow ? Species.Amphibian : Species.Helicopter; break; case AircraftComparerColumn.Squawk: aircraft.Squawk = setLow ? 1 : 2; break; case AircraftComparerColumn.Type: aircraft.Type = setLow ? "A" : "B"; break; case AircraftComparerColumn.VerticalRate: aircraft.VerticalRate = setLow ? 1 : 2; break; case AircraftComparerColumn.WakeTurbulenceCategory: aircraft.WakeTurbulenceCategory = setLow ? WakeTurbulenceCategory.Light : WakeTurbulenceCategory.Medium; break; default: throw new NotImplementedException(); } }
/// <summary> /// Adds the aircraft passed across to the list. /// </summary> /// <param name="aircraft"></param> private void AddAircraftToList(IAircraft aircraft) { if(aircraft.Latitude != null && aircraft.Longitude != null && (aircraft.Latitude != 0.0 || aircraft.Longitude != 0.0)) { ListViewItem item = new ListViewItem(new string[] { aircraft.Registration, aircraft.Icao24, aircraft.Type, aircraft.Operator }); item.Tag = aircraft; listView.Items.Add(item); } }
public override string GetDisplayerText(IAircraft iaircraft) { //TemplateAircraft aircraft = (TemplateAircraft) iaircraft; return(""); //tobo }
/// <summary> /// Updates an existing aircraft in the list. /// </summary> /// <param name="aircraft"></param> /// <param name="item"></param> private void UpdateAircraftInList(IAircraft aircraft, ListViewItem item) { if(item.SubItems[0].Text != aircraft.Registration) item.SubItems[0].Text = aircraft.Registration; if(item.SubItems[1].Text != aircraft.Icao24) item.SubItems[1].Text = aircraft.Icao24; if(item.SubItems[2].Text != aircraft.Type) item.SubItems[2].Text = aircraft.Type; if(item.SubItems[3].Text != aircraft.Operator) item.SubItems[3].Text = aircraft.Operator; item.Tag = aircraft; }
public override string GetText(IAircraft iaircraft) { return(""); //todo }
// Use this for initialization void Start() { controller = new Controller(); aircraft = GameObject.FindGameObjectWithTag("Drone") .GetComponent <Drone>(); }
public void Cleanup() { seabirdAir = null; seabirdSea = null; }
/// <summary> /// See base class. /// </summary> /// <param name="server"></param> /// <param name="args"></param> /// <returns></returns> protected override bool DoHandleRequest(Interface.WebServer.IWebServer server, Interface.WebServer.RequestReceivedEventArgs args) { bool result = false; if ((!args.IsInternetRequest || _InternetClientCanRequestClosestAircraft) && args.PathAndFile.Equals("/ClosestAircraft.json", StringComparison.OrdinalIgnoreCase)) { result = true; var latitude = QueryNDouble(args, "lat"); var longitude = QueryNDouble(args, "lng"); var json = new ProximityGadgetAircraftJson(); if (latitude == null || longitude == null) { json.WarningMessage = "Position not supplied"; } else { var receiver = _ReceiverManager.GetByUniqueId(_ReceiverId, ignoreInvisibleFeeds: true); if (receiver == null) { json.WarningMessage = "Receiver is offline"; } else { var baseStationAircraftList = receiver.AircraftList; long timeStamp, dataVersion; var aircraftList = baseStationAircraftList.TakeSnapshot(out timeStamp, out dataVersion); IAircraft closestAircraft = null; double? closestDistance = null; foreach (var aircraft in aircraftList) { double?distance = null; if (aircraft.Latitude != null && aircraft.Longitude != null) { distance = GreatCircleMaths.Distance(latitude, longitude, aircraft.Latitude, aircraft.Longitude); if (distance != null && closestAircraft == null || distance < closestDistance) { closestAircraft = aircraft; closestDistance = distance; } } if (aircraft.Emergency == true) { json.EmergencyAircraft.Add(CreateProximityGadgetClosestAircraftJson(aircraft, distance, latitude, longitude)); } } if (closestAircraft != null) { var closestJsonAircraft = CreateProximityGadgetClosestAircraftJson(closestAircraft, closestDistance, latitude, longitude); json.ClosestAircraft = closestJsonAircraft; } } } Responder.SendJson(args.Request, args.Response, json, null, MimeType.Text); // The proximity gagdet is expecting the text MIME type and will ignore JSON... args.Classification = ContentClassification.Json; } return(result); }
/// <summary> /// Returns the English description of the species of the aircraft passed across. /// </summary> /// <param name="aircraft"></param> /// <returns></returns> private string SpeciesDescription(IAircraft aircraft) { return(aircraft.Species == Species.None ? "" : aircraft.Species.ToString()); }
public AircraftController(IAircraft aircraftService) { _aircraftService = aircraftService; }
public void Register(IAircraft aircraft) { _aircraftList.Add(aircraft); }
public Application(ITransportFactory factory) { _aircraft = factory.CreateTransportAircraft(); _landvehicle = factory.CreateTransportVehicle(); }
public Key(IAircraft aircraft) { Icao24 = aircraft.Icao24?.ToUpper(); Callsign = aircraft.Callsign?.ToUpper(); OperatorIcao = aircraft.OperatorIcao?.ToUpper(); }
public AircraftSelectionDataItem(IAircraft aircraft, DataGroup @group, int rowSpan, int colSpan) : base(aircraft.UniqueId, aircraft.UniqueId, aircraft.ImagePath, @group, rowSpan, colSpan) { Version = aircraft.Version; }
/// <summary> /// Calculates an approximate bank angle based on the change in track of an aircraft since its last update. /// </summary> /// <param name="previousAircraft"></param> /// <param name="aircraft"></param> /// <returns></returns> private double ApproximateBank(IAircraft previousAircraft, IAircraft aircraft) { double result = 0.0; if(previousAircraft != null) { if(previousAircraft.UniqueId == aircraft.UniqueId) { if(previousAircraft.LastUpdate == aircraft.LastUpdate) result = _LastApproximatedBank; else { var delta = previousAircraft.Track - aircraft.Track; if(delta < 180F) delta += 360F; if(delta > 180F) delta -= 360F; result = ((double?)delta * 2.0).GetValueOrDefault(); result = Math.Max(-40.0, Math.Min(40.0, result)); } } } _LastApproximatedBank = result; return result; }
public void ReceiveMessage(IAircraft sender, string message) { Console.WriteLine($"{sender.Airline} @{sender.Altitude} => {Airline} @{Altitude}: {message}"); }
/// <summary> /// Repositions the FSX aircraft to match the location, speed and attitude of a real aircraft. /// </summary> private void MoveAircraft() { var selectedAircraft = _View.SelectedRealAircraft; if(_View.RidingAircraft && selectedAircraft != null) { long trash1, trash2; var aircraft = BaseStationAircraftList.TakeSnapshot(out trash1, out trash2).Where(a => a.UniqueId == selectedAircraft.UniqueId).FirstOrDefault(); if(aircraft != null) { var speedLimit = (float)_MaximumAirspeed - 30f; var writeAircraftInformation = new WriteAircraftInformation(); writeAircraftInformation.AirspeedIndicated = aircraft.GroundSpeed > speedLimit ? speedLimit : aircraft.GroundSpeed.GetValueOrDefault(); aircraft.GroundSpeed.GetValueOrDefault(); writeAircraftInformation.Altitude = aircraft.Altitude.GetValueOrDefault(); writeAircraftInformation.Operator = aircraft.Operator; writeAircraftInformation.Registration = aircraft.Registration; //writeAircraftInformation.Type = aircraft.Type; //writeAircraftInformation.Model = aircraft.Model; writeAircraftInformation.Latitude = aircraft.Latitude.GetValueOrDefault(); writeAircraftInformation.Longitude = aircraft.Longitude.GetValueOrDefault(); writeAircraftInformation.TrueHeading = aircraft.Track.GetValueOrDefault(); writeAircraftInformation.VerticalSpeed = aircraft.VerticalRate.GetValueOrDefault(); writeAircraftInformation.Bank = ApproximateBank(_MovedAircraft, aircraft); _MovedAircraft = aircraft; _FlightSimulatorX.MoveAircraft(writeAircraftInformation); } } }
public void TestInitialise() { _Aircraft = Factory.Singleton.Resolve <IAircraft>(); }
/// <summary> /// Returns true if the aircraft passes the filter criteria passed across. /// </summary> /// <param name="aircraft"></param> /// <param name="filter"></param> /// <returns></returns> private bool PassesFilter(IAircraft aircraft, AircraftListJsonBuilderFilter filter) { bool result = filter == null; if (!result) { result = true; if (filter.AltitudeLower != null) { result = aircraft.Altitude != null && aircraft.Altitude >= filter.AltitudeLower; } if (result && filter.AltitudeUpper != null) { result = aircraft.Altitude != null && aircraft.Altitude <= filter.AltitudeUpper; } if (result && !String.IsNullOrEmpty(filter.CallsignContains)) { result = aircraft.Callsign != null && aircraft.Callsign.Contains(filter.CallsignContains); } if (result && filter.EngineTypeEquals != null) { result = aircraft.EngineType == filter.EngineTypeEquals; } if (result && !String.IsNullOrEmpty(filter.Icao24CountryContains)) { result = aircraft.Icao24Country != null && aircraft.Icao24Country.ToUpperInvariant().Contains(filter.Icao24CountryContains); } if (result && filter.IsInterestingEquals != null) { result = aircraft.IsInteresting == filter.IsInterestingEquals; } if (result && filter.IsMilitaryEquals != null) { result = aircraft.IsMilitary == filter.IsMilitaryEquals; } if (result && filter.MustTransmitPosition) { result = aircraft.Latitude != null && aircraft.Longitude != null; } if (result && !String.IsNullOrEmpty(filter.OperatorContains)) { result = aircraft.Operator != null && aircraft.Operator.ToUpperInvariant().Contains(filter.OperatorContains); } if (result && filter.PositionWithin != null) { result = IsWithinBounds(aircraft.Latitude, aircraft.Longitude, filter.PositionWithin); } if (result && !String.IsNullOrEmpty(filter.RegistrationContains)) { result = aircraft.Registration != null && aircraft.Registration.Contains(filter.RegistrationContains); } if (result && filter.SpeciesEquals != null) { result = aircraft.Species == filter.SpeciesEquals; } if (result && filter.SquawkLower != null) { result = aircraft.Squawk != null && aircraft.Squawk >= filter.SquawkLower; } if (result && filter.SquawkUpper != null) { result = aircraft.Squawk != null && aircraft.Squawk <= filter.SquawkUpper; } if (result && !String.IsNullOrEmpty(filter.TypeStartsWith)) { result = aircraft.Type != null && aircraft.Type.StartsWith(filter.TypeStartsWith); } if (result && filter.WakeTurbulenceCategoryEquals != null) { result = aircraft.WakeTurbulenceCategory == filter.WakeTurbulenceCategoryEquals; } } return(result); }