Plane.FormationCreator/Plane.FormationCreator/App.xaml.cs

305 lines
12 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Plane.Communication;
using Plane.Copters;
using Plane.FormationCreator.Formation;
using Plane.Logging;
using Plane.Windows;
using Plane.Windows.Messages;
using GalaSoft.MvvmLight.Ioc;
using Microsoft.Practices.ServiceLocation;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using Plane.CommunicationManagement;
using Plane.FormationCreator.Util;
namespace Plane.FormationCreator
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
public App()
{
VersionControl.GetSettingFromIni();
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US");
ServiceLocatorConfigurer.Instance.Configure();
_logger = ServiceLocator.Current.GetInstance<ILogger>();
_copterManager = ServiceLocator.Current.GetInstance<CopterManager>();
_formationController = ServiceLocator.Current.GetInstance<FormationController>();
_mapManager = ServiceLocator.Current.GetInstance<MapManager>();
AppDomain.CurrentDomain.AssemblyResolve += (s, e) =>
{
var simpleName = new AssemblyName(e.Name).Name;
if (simpleName.EndsWith(".resources"))
{
return null;
}
return LoadAssembly(simpleName);
};
this.DispatcherUnhandledException += (s, e) =>
{
_logger.Log(e.Exception);
// await _formationController.AllStop();
TcpServerConnectionManager.Instance.StopListening();
UdpServerConnectionManager.Instance.StopReceiving();
};
this.Exit += (s, e) =>
{
try
{
// TcpServerConnectionManager.Instance.StopListening();
UdpServerConnectionManager.Instance.StopReceiving();
}
catch (Exception ex)
{
// RaiseExceptionThrown(ex);
}
};
//new Test().Prepare().Run();
}
private ILogger _logger;
private CopterManager _copterManager;
private FormationController _formationController;
private MapManager _mapManager;
private Assembly LoadAssembly(string simpleName)
{
String resourceName = this.GetType().Namespace + ".AssemblyLoadingAndReflection." + simpleName + ".dll";
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
{
Byte[] assemblyData = new Byte[stream.Length];
stream.Read(assemblyData, 0, assemblyData.Length);
return Assembly.Load(assemblyData);
}
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var md = Resources.MergedDictionaries;
// md.Add(new ResourceDictionary { Source = new Uri("pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml") });
md.Add(new ResourceDictionary { Source = new Uri("pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml") });
md.Add(new ResourceDictionary { Source = new Uri("pack://application:,,,/MahApps.Metro;component/Styles/Colors.xaml") });
md.Add(new ResourceDictionary { Source = new Uri("pack://application:,,,/MahApps.Metro;component/Styles/VS/Colors.xaml") });
md.Add(new ResourceDictionary { Source = new Uri("pack://application:,,,/MahApps.Metro;component/Styles/VS/Styles.xaml") });
md.Add(new ResourceDictionary { Source = new Uri("pack://application:,,,/Plane.Windows.Messages;component/Styles.xaml") });
md.Add(new ResourceDictionary { Source = new Uri("pack://application:,,,/Styles/Colors.xaml") });
md.Add(new ResourceDictionary { Source = new Uri("pack://application:,,,/Styles.xaml") });
/*
new UpdateChecker("http://dl.Plane.com/tools/ver.php?app=FormationCreator", _logger)
.CheckAsync(ver =>
{
var currentVersion = this.GetType().Assembly.GetName().Version;
if (currentVersion < ver
&& Alert.Show("检测到新版本,请下载。", "更新提示", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
{
Process.Start("http://dl.Plane.com/tools/FormationCreatorSetup.exe");
this.Shutdown();
}
});
*/
System.Windows.FrameworkCompatibilityPreferences.KeepTextBoxDisplaySynchronizedWithTextProperty = false;
MainWindow = new MainWindow();
MainWindow.Show();
try
{
/* by panxu tcp 不使用了 --使用TCP监听在自动获取IP的情况下刚开始会导致界面无响应过一会就好
TcpServerConnectionManager.Instance.ConnectionEstablished += ConnectionManager_ConnectionEstablished;
if (!TcpServerConnectionManager.Instance.StartListening())
{
Alert.Show("网络连接不正常,无法连接飞机。");
return;
}
*/
if (VersionControl.ConType == 1)
{
CommModuleManager.Instance.UseTransModule = false;
UdpServerConnectionManager.Instance.ExceptionThrown += (sender, e1) =>
{
_logger.Log(e1.Exception);
};
UdpServerConnectionManager.Instance.ConnectionEstablished += ConnectionManager_ConnectionEstablished;
UdpServerConnectionManager.Instance.StartReceiving();
}
else
{
CommModuleManager.Instance.UseTransModule = true;
//初始化地面站连接
CommModuleManager.Instance.CommunicationReceived += CommtionReceivedCopterInfo;
CommModuleManager.Instance.CommunicationCopterDisconnect += CommCopterDisconnect;
CommModuleManager.Instance.CommunicationConnected += CommCopterconnected;
CommModuleManager.Instance.Connect();
}
}
catch (Exception ex)
{
Alert.Show("网络连接不正常,无法连接飞机。");
return;
}
}
protected override void OnExit(ExitEventArgs e)
{
CommModuleManager.Instance.CloseConnection();
base.OnExit(e);
}
private void Copter_TextReceived(object sender, MessageCreatedEventArgs e)
{
_logger.Log(e.Message );
}
//wifi模式添加飞机
private async Task AddOrUpdateCopter(string ip, IConnection Connection)
{
var copters = _copterManager.Copters;
var copterStatus = _copterManager.CopterStatus;
string[] iparr = ip.Split('.');
string vIPID = String.Format("{0:D3}", int.Parse(iparr[2])) + String.Format("{0:D3}", int.Parse(iparr[3]));
var copter = copters.FirstOrDefault(c => c.Id == vIPID);
if (copter == null)
{
if (!_copterManager.EnAddCopter_Real())
{
UdpServerConnectionManager.Instance.DeleteConnections(ip);
}
else
{
await Dispatcher.BeginInvoke(new Action(() =>
{
copter = new Copter(Connection, SynchronizationContext.Current, _mapManager.Center.Lat, _mapManager.Center.Lng)
{
Id = vIPID,
Name = vIPID // ip.Substring(ip.LastIndexOf('.') + 1)
};
int _index;
_index = copters.AddCopter(copter);
copterStatus.Insert(_index, false);
copter.TextReceived += Copter_TextReceived;
}));
}
}
else
{
copter.Connection = Connection;
}
if (copter!=null)
await copter.ConnectAsync().ConfigureAwait(false);
}
private async void ConnectionManager_ConnectionEstablished(object sender, ConnectionEstablishedEventArgs e)
{
await AddOrUpdateCopter(e.RemoteAddress, e.Connection);
}
private async void CommtionReceivedCopterInfo(object sender, CommunicationReceiveCopterInfoEventArgs e)
{
await UpdateCommCopterInfo(e.Id, e.Package, e.CommModuleVersion);
//await TaskUtils.CompletedTask;
}
private async void CommCopterDisconnect(object sender, CommunicationCopterDisconnectEventArgs e)
{
await DisconnectCopter(e.Id);
}
private async void CommCopterconnected(object sender, CommunicationConnectEventArgs e)
{
await AddCommCopter(e.Id);
}
private async Task DisconnectCopter(int id)
{
var copters = _copterManager.Copters;
var copter = copters.FirstOrDefault(c => c.Id == id.ToString());
if (copter != null)
{
if (copter is PLCopter)
{
PLCopter plcopter = (PLCopter)copter;
plcopter.CommModuleConnected = false;
}
}
await TaskUtils.CompletedTask;
}
private static readonly object locker = new object();
private async Task AddCommCopter(int id)
{
await Dispatcher.BeginInvoke(new Action(() =>
{
lock(locker)
{
var copter = _copterManager.Copters.FirstOrDefault(c => c.Id == id.ToString());
if (copter == null)
{
if (_copterManager.EnAddCopter_Real())
{
var copterStatus = _copterManager.CopterStatus;
var connection = new CommConnection();
copter = new Copter(connection, SynchronizationContext.Current, _mapManager.Center.Lat, _mapManager.Center.Lng)
{
Id = id.ToString(),
Name = id.ToString(),
};
int _index;
_index = _copterManager.Copters.AddCopter(copter);
copterStatus.Insert(_index, false);
copter.TextReceived += Copter_TextReceived;
}
}
}
}));
}
private async Task UpdateCommCopterInfo(int id, byte[] package, byte CommModuleVersion)
{
await AddCommCopter(id);
lock (locker)
{
var copter = _copterManager.Copters.FirstOrDefault(c => c.Id == id.ToString());
if (copter!= null && copter is PLCopter)
{
PLCopter plcopter = (PLCopter)copter;
if (!plcopter.CommModuleConnected) plcopter.CommModuleConnected = true;
plcopter.InternalCopter.AnalyzeCommMouldePositionIntPacket(package, CommModuleVersion);
plcopter.CommModuleConnected = true;
}
}
}
}
}