public void SetUp() { AutoResetEvent resetEvent = new AutoResetEvent(false); _fsConnect = new FsConnect(); _fsConnect.ConnectionChanged += (sender, b) => { if (b) { resetEvent.Set(); } }; _fsConnect.FsError += (sender, args) => { Assert.Fail($"MSFS Error: {args.ExceptionDescription}"); }; _fsConnect.Connect("AutopilotManagerIntegrationTest", 0); bool res = resetEvent.WaitOne(2000); if (!res) { Assert.Fail("Not connected to MSFS within timeout"); } _manager = new AutopilotManager(_fsConnect); _manager.Initialize(); }
static void Main(string[] args) { run = true; fs = new FsConnect(); fs.Connect("FlightEconOnline"); fs.ConnectionChanged += Fs_ConnectionChanged; fs.FsDataReceived += Fs_FsDataReceived; List <SimProperty> definition = new List <SimProperty>(); // Consult the SDK for valid sim variable names, units and whether they can be written to. definition.Add(new SimProperty("Title", null, SIMCONNECT_DATATYPE.STRING256)); definition.Add(new SimProperty("Plane Latitude", "degrees", SIMCONNECT_DATATYPE.FLOAT64)); definition.Add(new SimProperty("Plane Longitude", "degrees", SIMCONNECT_DATATYPE.FLOAT64)); // Can also use predefined enums for sim variables and units (incomplete) definition.Add(new SimProperty(FsSimVar.PlaneAltitude, FsUnit.Feet, SIMCONNECT_DATATYPE.FLOAT64)); definition.Add(new SimProperty(FsSimVar.PlaneHeadingDegreesTrue, FsUnit.Degrees, SIMCONNECT_DATATYPE.FLOAT64)); definition.Add(new SimProperty(FsSimVar.AirspeedIndicated, FsUnit.Knots, SIMCONNECT_DATATYPE.FLOAT64)); definition.Add(new SimProperty(FsSimVar.GpsGroundSpeed, FsUnit.Knots, SIMCONNECT_DATATYPE.FLOAT64)); fs.RegisterDataDefinition <PlaneInfoResponse>(Requests.PlaneInfo, definition); while (run) { // Request data fs.RequestData(Requests.PlaneInfo); // Sleep for a sec Thread.Sleep(1000); } }
public void clearRecord(FsConnect _fsConnect, uint ID) { for (int i = ghostPlanes.Count - 1; i >= 0; i--) { if (ID == ghostPlanes[i].ID) { _fsConnect.RemoveObject(ghostPlanes[i].ID, Requests.TowPlane); ghostPlanes.RemoveAt(i); } } }
public void clearRecords(FsConnect _fsConnect) { foreach (GhostPlane ghostPlane in ghostPlanes) { if (ghostPlane.ID != TARGETMAX) { _fsConnect.RemoveObject(ghostPlane.ID, Requests.TowPlane); } } ghostPlanes = new List <GhostPlane>(); }
private static void InitializeDataDefinitions(FsConnect fsConnect) { List <SimProperty> definition = new List <SimProperty>(); definition.Add(new SimProperty(FsSimVar.Title, FsUnit.None, SIMCONNECT_DATATYPE.STRING256)); definition.Add(new SimProperty(FsSimVar.PlaneLatitude, FsUnit.Radians, SIMCONNECT_DATATYPE.FLOAT64)); definition.Add(new SimProperty(FsSimVar.PlaneLongitude, FsUnit.Radians, SIMCONNECT_DATATYPE.FLOAT64)); definition.Add(new SimProperty(FsSimVar.PlaneAltitudeAboveGround, FsUnit.Feet, SIMCONNECT_DATATYPE.FLOAT64)); definition.Add(new SimProperty(FsSimVar.PlaneAltitude, FsUnit.Feet, SIMCONNECT_DATATYPE.FLOAT64)); fsConnect.RegisterDataDefinition <PlaneInfoResponse>(Definitions.PlaneInfo, definition); }
private static void InitializeDataDefinitions(FsConnect fsConnect) { List <SimProperty> definition = new List <SimProperty>(); definition.Add(new SimProperty(FsSimVar.Title, FsUnit.None, SIMCONNECT_DATATYPE.STRING256)); definition.Add(new SimProperty(FsSimVar.PlaneLatitude, FsUnit.Radians, SIMCONNECT_DATATYPE.FLOAT64)); definition.Add(new SimProperty(FsSimVar.PlaneLongitude, FsUnit.Radians, SIMCONNECT_DATATYPE.FLOAT64)); definition.Add(new SimProperty(FsSimVar.PlaneAltitudeAboveGround, FsUnit.Feet, SIMCONNECT_DATATYPE.FLOAT64)); definition.Add(new SimProperty("PLANE ALTITUDE", "Feet", SIMCONNECT_DATATYPE.FLOAT64)); // Example using known/new values definition.Add(new SimProperty(FsSimVar.PlaneHeadingDegreesTrue, FsUnit.Radians, SIMCONNECT_DATATYPE.FLOAT64)); definition.Add(new SimProperty(FsSimVar.AirspeedTrue, FsUnit.Knot, SIMCONNECT_DATATYPE.FLOAT64)); fsConnect.RegisterDataDefinition <PlaneInfoResponse>(Definitions.PlaneInfo, definition); }
public void SetTime_SetsTimeInMSFS() { // Arrange AutoResetEvent resetEvent = new AutoResetEvent(false); int errorCount = 0; FsConnect fsConnect = new FsConnect(); fsConnect.ConnectionChanged += (sender, b) => { if (b) { resetEvent.Set(); } }; fsConnect.FsError += (sender, args) => { errorCount++; Console.WriteLine($"Error: {args.ExceptionDescription}"); }; fsConnect.Connect("WorldManagerIntegrationTests", 0); bool res = resetEvent.WaitOne(2000); if (!res) { Assert.Fail("Not connected to MSFS within timeout"); } WorldManager worldManager = new WorldManager(fsConnect); // Act DateTime now = new DateTime(); DateTime night = new DateTime(now.Year, now.Month, now.Day, 3, 0, 0); fsConnect.SetText("Setting time to night", 1000); worldManager.SetTime(night); Thread.Sleep(3000); fsConnect.SetText("Setting time to morning", 1000); DateTime morning = new DateTime(now.Year, now.Month, now.Day, 9, 0, 0); worldManager.SetTime(morning); // Assert Assert.That(errorCount, Is.Zero); }
public FlightSimMonitor() { // Initialize the data definition _dataDefinition = InitializeDataDefinition(); // Initialize a new FsConnect object _fsConn = new FsConnect(); _fsConn.ConnectionChanged += _fsConn_ConnectionChanged; _fsConn.FsDataReceived += _fsConn_FsDataReceived; // Initialize the last connected & disconnected times to the minimum DateTime value, since DateTimes are wonky about nulls _lastConnectedTime = DateTime.MinValue; _lastDisconnecedTime = DateTime.MinValue; // Note that we have yet to receive any data _firstDataRecvd = false; }
public static void Main(string[] args) { string hostName = "localhost"; uint port = 500; // Also supports "somehostname 1234" if (args.Length == 2) { hostName = args[0]; port = uint.Parse(args[1]); } FsConnect fsConnect = new FsConnect(); // Specify where the SimConnect.cfg should be written to fsConnect.SimConnectFileLocation = SimConnectFileLocation.Local; // Creates a SimConnect.cfg and connect to Flight Simulator using this configuration. fsConnect.Connect("TestApp", hostName, port, SimConnectProtocol.Ipv4); // Other alternatives, use existing SimConfig.cfg and specify config index: // fsConnect.Connect(1); // or // fsConnect.Connect(); fsConnect.FsDataReceived += HandleReceivedFsData; List <SimProperty> definition = new List <SimProperty>(); // Consult the SDK for valid sim variable names, units and whether they can be written to. definition.Add(new SimProperty("Title", null, SIMCONNECT_DATATYPE.STRING256)); definition.Add(new SimProperty("Plane Latitude", "degrees", SIMCONNECT_DATATYPE.FLOAT64)); definition.Add(new SimProperty("Plane Longitude", "degrees", SIMCONNECT_DATATYPE.FLOAT64)); // Can also use predefined enums for sim variables and units (incomplete) definition.Add(new SimProperty(FsSimVar.PlaneAltitude, FsUnit.Feet, SIMCONNECT_DATATYPE.FLOAT64)); definition.Add(new SimProperty(FsSimVar.PlaneHeadingDegreesTrue, FsUnit.Degrees, SIMCONNECT_DATATYPE.FLOAT64)); definition.Add(new SimProperty(FsSimVar.AirspeedTrue, FsUnit.MeterPerSecond, SIMCONNECT_DATATYPE.FLOAT64)); definition.Add(new SimProperty(FsSimVar.AirspeedTrue, FsUnit.Knot, SIMCONNECT_DATATYPE.FLOAT64)); fsConnect.RegisterDataDefinition <PlaneInfoResponse>(Requests.PlaneInfo, definition); fsConnect.RequestData(Requests.PlaneInfo); Console.ReadKey(); fsConnect.Disconnect(); }
public void GetAircraftData() { // Arrange AutoResetEvent resetEvent = new AutoResetEvent(false); int errorCount = 0; FsConnect fsConnect = new FsConnect(); fsConnect.ConnectionChanged += (sender, b) => { if (b) { resetEvent.Set(); } }; fsConnect.FsError += (sender, args) => { errorCount++; Console.WriteLine($"Error: {args.ExceptionDescription}"); }; fsConnect.Connect("AircraftManagersIntegrationTests", 0); bool res = resetEvent.WaitOne(2000); if (!res) { Assert.Fail("Not connected to MSFS within timeout"); } var defId = fsConnect.RegisterDataDefinition <AircraftInfo>(); AircraftManager <AircraftInfo> aircraftManager = new AircraftManager <AircraftInfo>(fsConnect, defId); // Act var info = aircraftManager.Get(); // Assert Assert.That(errorCount, Is.Zero); Assert.That(info.Title, Is.Not.Empty); Assert.That(info.Latitude, Is.Not.EqualTo(0)); Assert.That(info.Longitude, Is.Not.EqualTo(0)); }
public static void Main(string[] args) { string hostName = "localhost"; uint port = 500; // Also supports "somehostname 1234" if (args.Length == 2) { hostName = args[0]; port = uint.Parse(args[1]); } FsConnect fsConnect = new FsConnect(); // Specify where the SimConnect.cfg should be written to fsConnect.SimConnectFileLocation = SimConnectFileLocation.Local; // Creates a SimConnect.cfg and connect to Flight Simulator using this configuration. fsConnect.Connect("TestApp", hostName, port, SimConnectProtocol.Ipv4); // Other alternatives, use existing SimConfig.cfg and specify config index: // fsConnect.Connect(1); // or // fsConnect.Connect(); fsConnect.FsDataReceived += HandleReceivedFsData; int planeInfoDefinitionId = fsConnect.RegisterDataDefinition <PlaneInfoResponse>(); ConsoleKeyInfo cki; do { fsConnect.RequestData((int)Requests.PlaneInfoRequest, planeInfoDefinitionId); cki = Console.ReadKey(); } while (cki.Key != ConsoleKey.Escape); fsConnect.Disconnect(); }
private static void Run(Options commandLineOptions) { _levelSwitch.MinimumLevel = commandLineOptions.LogLevel; try { _fsConnect = new FsConnect(); try { if (string.IsNullOrEmpty(commandLineOptions.Hostname)) { Console.WriteLine($"Connecting to Flight Simulator using index {commandLineOptions.ConfigIndex}"); _fsConnect.Connect("FsConnectTestConsole", commandLineOptions.ConfigIndex); } else { Console.WriteLine($"Connecting to Flight Simulator on {commandLineOptions.Hostname}:{commandLineOptions.Port}"); _fsConnect.Connect("FsConnectTestConsole", commandLineOptions.Hostname, commandLineOptions.Port, SimConnectProtocol.Ipv4); } } catch (Exception e) { Console.WriteLine("An error occurred while connection to Microsoft Flight Simulator: " + e.Message); return; } // // Register event handlers // _fsConnect.ConnectionChanged += OnFsConnectOnConnectionChanged; // // Wait for connection to Flight Simulator before using API // bool receivedEvent = _connectedResetEvent.WaitOne(2000); if (receivedEvent == false) { Console.WriteLine("Could not connect to Flight Simulator. Timed out waiting for connection"); return; } // // Post connection initialization // Console.WriteLine("Initializing data definitions"); InitializeDataDefinitions(_fsConnect); _fsConnect.SetText("Test Console connected", 2); // // Show menu // MainMenu mainMenu = new MainMenu(_fsConnect); mainMenu.Run(); // // Tear down // if (_fsConnect.Connected) { _fsConnect.Disconnect(); } _fsConnect.Dispose(); _fsConnect = null; Console.WriteLine("Done"); } catch (Exception e) { Console.WriteLine("An error occurred: " + e); } }
private static void Run(Options commandLineOptions) { try { _fsConnect = new FsConnect(); try { if (string.IsNullOrEmpty(commandLineOptions.Hostname)) { Console.WriteLine($"Connecting to Flight Simulator using index {commandLineOptions.ConfigIndex}"); _fsConnect.Connect("FsConnectTestConsole", commandLineOptions.ConfigIndex); } else { Console.WriteLine($"Connecting to Flight Simulator on {commandLineOptions.Hostname}:{commandLineOptions.Port}"); _fsConnect.Connect("FsConnectTestConsole", commandLineOptions.Hostname, commandLineOptions.Port, SimConnectProtocol.Ipv4); } } catch (Exception e) { Console.WriteLine(e.Message); return; } _fsConnect.FsDataReceived += HandleReceivedFsData; Console.WriteLine("Initializing data definitions"); InitializeDataDefinitions(_fsConnect); _keyHandlers.Add(ConsoleKey.P, PollFlightSimulator); _keyHandlers.Add(ConsoleKey.W, MoveForward); _keyHandlers.Add(ConsoleKey.S, MoveBackward); _keyHandlers.Add(ConsoleKey.A, MoveLeft); _keyHandlers.Add(ConsoleKey.D, MoveRight); _keyHandlers.Add(ConsoleKey.Q, RotateLeft); _keyHandlers.Add(ConsoleKey.E, RotateRight); _keyHandlers.Add(ConsoleKey.R, IncreaseAltitude); _keyHandlers.Add(ConsoleKey.F, DecreaseAltitude); Console.WriteLine("Press any key to request data from Flight Simulator or ESC to quit."); Console.WriteLine("Press WASD keys to move, Q and E to rotate, R and F to change altitude."); ConsoleKeyInfo cki = Console.ReadKey(true); _fsConnect.SetText("Test Console connected", 2); _fsConnect.RequestData(Requests.PlaneInfo); while (cki.Key != ConsoleKey.Escape) { if (_keyHandlers.ContainsKey(cki.Key)) { _keyHandlers[cki.Key].Invoke(); } else { PollFlightSimulator(); } cki = Console.ReadKey(true); } Console.ReadKey(true); Console.WriteLine("Disconnecting from Flight Simulator"); _fsConnect.SetText("Test Console disconnecting", 1); _fsConnect.Disconnect(); _fsConnect.Dispose(); _fsConnect = null; Console.WriteLine("Done"); } catch (Exception e) { Console.WriteLine("An error occurred: " + e); } }
public void TransmitClientEvent_HeadingBugDirectionSet_SetsHeadingBugDirection() { // Arrange AutoResetEvent resetEvent = new AutoResetEvent(false); int errorCount = 0; FsConnect fsConnect = new FsConnect(); fsConnect.ConnectionChanged += (sender, b) => { if (b) { resetEvent.Set(); } }; fsConnect.FsError += (sender, args) => { errorCount++; Console.WriteLine($"Error: {args.ExceptionDescription}"); }; fsConnect.Connect("FsConnectIntegrationTest", 0); bool res = resetEvent.WaitOne(2000); if (!res) { Assert.Fail("Not connected to MSFS within timeout"); } var hbDef = fsConnect.RegisterDataDefinition <HeadingBugTest>(); HeadingBugTest headingBugData = default; // Act fsConnect.MapClientEventToSimEvent(TestEnums.GroupId, TestEnums.EventId, FsEventNameId.HeadingBugSet); fsConnect.SetNotificationGroupPriority(TestEnums.GroupId); uint headingValue = (uint)DateTime.Now.Second * 6; fsConnect.TransmitClientEvent(TestEnums.EventId, (uint)headingValue, TestEnums.GroupId); // Assert Assert.That(errorCount, Is.Zero, "MSFS returned errors. Check console output."); fsConnect.FsDataReceived += (sender, args) => { var data = args.Data.FirstOrDefault(); headingBugData = data is HeadingBugTest ? (HeadingBugTest)data : default; resetEvent.Set(); }; fsConnect.RequestData((int)TestEnums.RequestId, hbDef); res = resetEvent.WaitOne(2000); if (!res) { Assert.Fail("Data not returned from MSFS within timeout"); } Assert.That(headingBugData, Is.Not.Null); Assert.That(headingBugData.HeadingBug, Is.EqualTo(headingValue)); // Teardown fsConnect?.Disconnect(); }
private static void InitializeDataDefinitions(FsConnect fsConnect) { fsConnect.RegisterDataDefinition <PlaneInfoResponse>(Definitions.PlaneInfo); fsConnect.RegisterDataDefinition <PlanePosition>(Definitions.PlanePosition); }
public GhostCommit updateGhostPlayer(uint ID, NearbyInfoResponse response, GhostCommit towCommit, FsConnect _fsConnect, MathClass _mathClass, double absoluteTime) { int index = 0; double deltaTime = 0; foreach (GhostPlane ghostPlane in ghostPlanes) { if (ghostPlane.ID == ID && ghostPlane.Progress > 0 && ghostPlane.TrackPoints.Count > 0) { deltaTime = absoluteTime - ghostPlane.LastTrackPlayed; TrackPoint prev = new TrackPoint(); TrackPoint curr = new TrackPoint(); TrackPoint next = new TrackPoint(); bool found = false; foreach (var point in ghostPlane.TrackPoints) { if (!found) { curr = point; } else { next = point; break; } if (prev.Timer < (ghostPlane.Progress + deltaTime) && point.Timer >= (ghostPlane.Progress + deltaTime)) { found = true; if (!string.IsNullOrEmpty(curr.Message) && lastMessage != curr.Message) { message = new KeyValuePair <uint, string>(ghostPlane.ID, point.Message); lastMessage = point.Message; } } else { prev = point; } } if (found && prev.Location != null && curr.Location != null && next.Location != null) { try { double progress = ((ghostPlane.Progress + deltaTime) - prev.Timer) / (curr.Timer - prev.Timer); double timeLeft = curr.Timer - (ghostPlane.Progress + deltaTime); double distancePrev = _mathClass.findDistanceBetweenPoints(response.Latitude, response.Longitude, prev.Location.Latitude, prev.Location.Longitude); double distanceCurr = _mathClass.findDistanceBetweenPoints(response.Latitude, response.Longitude, curr.Location.Latitude, curr.Location.Longitude); double distanceNext = _mathClass.findDistanceBetweenPoints(response.Latitude, response.Longitude, next.Location.Latitude, next.Location.Longitude); double bearing = normalizeRadAngle(_mathClass.findBearingToPoint(response.Latitude, response.Longitude, next.Location.Latitude, next.Location.Longitude)); response.Heading = normalizeRadAngle(response.Heading); bearing = zeroeRadAngle(bearing - response.Heading); double newHeading = zeroeRadAngle(response.Heading + (absoluteTime - ghostPlane.LastTrackPlayed) * bearing); towCommit.RotationVelocityBodyY = Math.Sin(newHeading - response.Heading); //Console.WriteLine($"Tracking heading: {response.Heading:F4} bearing: {bearing:F4} newHeading: {newHeading:F4}"); double requiredBank = ((1 - progress) * (prev.Roll * Math.PI / 180 - response.Bank) + progress * (curr.Roll * Math.PI / 180 - response.Bank)) / 2; towCommit.RotationVelocityBodyZ = Math.Sin(requiredBank - response.Bank); double requiredPitch = ((1 - progress) * (prev.Pitch * Math.PI / 180 - response.Pitch) + progress * (prev.Pitch * Math.PI / 180 - response.Pitch)) / 2; towCommit.RotationVelocityBodyX = Math.Sin(requiredPitch - response.Pitch); //Console.WriteLine($"RotationVelocityBodyX: {towCommit.RotationVelocityBodyX:F4} RotationVelocityBodyY: {towCommit.RotationVelocityBodyY:F4} RotationVelocityBodyZ: {towCommit.RotationVelocityBodyZ:F4}"); //towCommit.Heading = newHeading; towCommit.VelocityBodyX = 0; towCommit.VelocityBodyY = ((1 - progress) * (prev.Elevation - response.Altitude) + progress * (curr.Elevation - response.Altitude)) / 2; towCommit.VelocityBodyZ = (0.8 * curr.Velocity + 0.1 * distanceCurr / Math.Max(1, timeLeft)) * (Math.Abs(distanceCurr) < 10 ? Math.Abs(distanceCurr) / 10 : 1); // TAXIING if (towCommit.VelocityBodyZ < 1 && towCommit.VelocityBodyZ > -1) { towCommit.VelocityBodyZ = Math.Sign(towCommit.VelocityBodyZ) * Math.Pow(Math.Abs(towCommit.VelocityBodyZ), 4); } if (towCommit.VelocityBodyY > 10) { TowInfoResponse towInfo = new TowInfoResponse(); towInfo.Altitude = response.Altitude + towCommit.VelocityBodyY; towInfo.Latitude = response.Latitude; towInfo.Longitude = response.Longitude; towInfo.Heading = response.Heading; towInfo.Bank = response.Bank; if (!double.IsNaN(towInfo.Altitude) && !double.IsNaN(towInfo.Latitude) && !double.IsNaN(towInfo.Longitude) && !double.IsNaN(towInfo.Heading) && !double.IsNaN(towInfo.Bank)) { try { Console.WriteLine("Sinking, TELEPORT!"); _fsConnect.UpdateData(Definitions.TowPlane, towInfo, ID); } catch (Exception ex) { } } } //Console.WriteLine("Tracking animation " + (ghostPlane.Progress + deltaTime) + " h" + towCommit.VelocityBodyZ + " v" + towCommit.VelocityBodyY + " d" + distanceCurr); } catch { } } else if (curr.Location != null && next.Location == null) { message = new KeyValuePair <uint, string>(ghostPlane.ID, "REMOVE"); } break; } index++; } if (index < ghostPlanes.Count) { GhostPlane gp = ghostPlanes[index]; gp.LastTrackPlayed = absoluteTime; gp.Progress += deltaTime; ghostPlanes[index] = gp; } return(towCommit); }