private void OnNewUser_Click(object sender, EventArgs e) { int num = GetNumNouveau(); string Profil = "Nouveau"; if (num > 0) { Profil += " " + num; } ListUsers.SelectedNode = ListUsers.Nodes[0]; PirepUser User = new PirepUser(); User.Profil = Profil; User.Login = "******"; User.Password = Outils.Encrypt(""); User.URL = "ffs2play.fr"; Users.Add(User); ListUsers.SelectedNode = ListUsers.SelectedNode.Nodes.Add(Profil); tbProfil.Text = User.Profil; tbLogin.Text = User.Login; tbPassword.Text = ""; tbURL.Text = User.URL; ListUsers.ExpandAll(); btnSupprimer.Enabled = true; btnSupprimer.BackColor = Color.LightGray; btnSupprimer.ForeColor = Color.Black; SaveUsers(); }
/// <summary> /// Event sur récéption des données de l'AI sur le simulateur /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnSCReceiveAIUpdate(object sender, SCManagerEventAIUpdate e) { if (m_ObjectID != e.ObjectID) { return; } m_LastAIUpdate = e.Time; m_AISimData = e.Data; m_Ecart = Outils.distance(m_Data.Latitude, m_Data.Longitude, m_AISimData.Latitude, m_AISimData.Longitude, 'N'); }
private void CheckVersionCallBack(HttpWebResponse Reponse) { sVersion Actual = Outils.GetVersion(); XmlDocument xmlDoc = new XmlDocument(); xmlDoc = pm.GetResultXml(ref Reponse); XmlNode Version = pm.GetFirstElement(ref xmlDoc, "version"); if (Version != null) { int SiteMajor = Convert.ToInt32(Version.Attributes["major"].Value); int SiteMinor = Convert.ToInt32(Version.Attributes["minor"].Value); int SiteBuild = Convert.ToInt32(Version.Attributes["build"].Value); Byte Beta = Convert.ToByte(Version.Attributes["beta"].Value); bool maj = false; bool compat = true; string Message = ""; if (Beta == 1) { Message = "!!! Attention, Nouvelle Version Bêta disponible !!!" + Environment.NewLine + Environment.NewLine; } if (SiteMajor > Actual.Major) { Message += "Cette version de FFS2Play n'est pas supportée par le site. souhaitez vous procéder à la mise à jour ?"; maj = true; compat = false; } else if ((SiteMinor > Actual.Minor) || ((SiteMinor == Actual.Minor) && (SiteBuild > Actual.Build))) { Message += "Cette version de FFS2Play n'est plus a jour. souhaitez vous procéder à la mise à jour ?"; maj = true; } if (maj) { DialogResult dialogResult = MessageBox.Show(Message, "Mise à jour de FFS2Play", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { XmlNode Url = pm.GetFirstElement(ref xmlDoc, "url"); if (Url != null) { Process.Start(Url.InnerText); } pm.AutoExit = true; Invoke(new Action(() => { Close(); })); return; } if (!compat) { return; } } } }
/// <summary> /// Méthode cyclique du timer /// Gestion des tâches périodiques /// Pour les demandes de données sur le simulateur /// </summary> /// <param name="source"></param> /// <param name="evt"></param> private void OnATCUpdate(object source, ElapsedEventArgs evt) { if (IsConnected() && SCM.IsConnected()) { int Transponder = Outils.ConvertToBinaryCodedDecimal(Analyse.GetLastState().Squawk); if ((Transponder == 1200) || (Transponder == 7000)) { return; } XmlBuild(ref SendAtc, XmlCode.atc); XmlNodeList Nodes = SendAtc.GetElementsByTagName("atc"); foreach (XmlNode node in Nodes) { foreach (XmlNode child in node.ChildNodes) { switch (child.Name) { case "latitude": child.InnerText = string.Format("{0:0.00000}", Analyse.GetLastState().Latitude); break; case "longitude": child.InnerText = string.Format("{0:0.00000}", Analyse.GetLastState().Longitude); break; case "heading": child.InnerText = string.Format("{0:0.}", Analyse.GetLastState().Heading); break; case "altitude": child.InnerText = string.Format("{0:0.}", Analyse.GetLastState().Altitude); break; case "groundSpeed": child.InnerText = string.Format("{0:0.}", Analyse.GetLastState().GSpeed); break; case "iaspeed": child.InnerText = string.Format("{0:0.}", Analyse.GetLastState().IASSpeed); break; case "squawk": child.InnerText = string.Format("{0:0.}", Outils.ConvertToBinaryCodedDecimal(Analyse.GetLastState().Squawk)); break; } } } #if DEBUG Log.LogMessage("PManager: ATCUpdate =\n " + Beautify(SendAtc), Color.DarkRed, 2); #endif HTTPRequestThread Requete = new HTTPRequestThread(SendAtc, m_sURL, ATCCB); Requete.Start(); } }
private void tbPassword_TextChanged(object sender, EventArgs e) { if (position < 0) { return; } if (tbLogin.Text != Outils.Decrypt(Users[position].Password)) { btnAppliquer.Enabled = true; btnAppliquer.BackColor = Color.DodgerBlue; btnAppliquer.ForeColor = Color.White; } }
/// <summary> /// Callback Requete de mise à jour /// </summary> /// <param name="asyncResult"></param> private void SyncAICB(HttpWebResponse Response) { if (!m_bConnected) { return; } Dictionary <string, string> Fichiers = new Dictionary <string, string>(); XmlDocument xmlDoc = null; if (Response != null) { xmlDoc = GetResultXml(ref Response); Response.Close(); } if (xmlDoc != null) { CheckError(xmlDoc); XmlNode Node = GetFirstElement(ref xmlDoc, "no_found"); if (Node != null) { List <string> Manquants = Outils.PhpDeSerialize(Node.InnerText); foreach (string item in Manquants) { #if DEBUG Log.LogMessage("PManager: Fichier manquant :" + item + " Fichier :" + Mapping.GetPath(item), Color.DarkBlue, 1); #endif Fichiers.Add(item, Mapping.GetFichierData(item)); break; } if (Fichiers.Count == 0) { return; } XmlBuild(ref SendAI, XmlCode.sendai); XmlNode DNode = GetFirstElement(ref SendAI, "sendai"); foreach (KeyValuePair <string, string> item in Fichiers) { XmlNode Fichier = SendAI.CreateElement(string.Empty, "MD5_" + item.Key, string.Empty); Fichier.InnerText = item.Value; DNode.AppendChild(Fichier); } HTTPRequestThread Requete = new HTTPRequestThread(SendAI, m_sURL, SyncAICB); Requete.Start(); #if DEBUG Log.LogMessage("PManager: Envois des AI : \n" + Beautify(SendAI), Color.DarkRed, 2); #endif } } m_SyncAIDone = true; }
private void ListUsers_AfterSelect(object sender, TreeViewEventArgs e) { if (e.Node.Parent != null) { string Profil = e.Node.Text; position = e.Node.Index; tbProfil.Text = Users[position].Profil; tbLogin.Text = Users[position].Login; tbPassword.Text = Outils.Decrypt(Users[position].Password); tbURL.Text = Users[position].URL; btnConnexion.Enabled = true; btnConnexion.BackColor = Color.DodgerBlue; btnConnexion.ForeColor = Color.White; btnAppliquer.Enabled = false; btnAppliquer.BackColor = Color.LightGray; btnAppliquer.ForeColor = Color.Black; btnSupprimer.Enabled = true; btnSupprimer.BackColor = Color.DodgerBlue; btnSupprimer.ForeColor = Color.White; tbProfil.Enabled = true; tbLogin.Enabled = true; tbPassword.Enabled = true; tbURL.Enabled = true; } else { position = -1; btnConnexion.Enabled = false; btnConnexion.BackColor = Color.LightGray; btnConnexion.ForeColor = Color.Black; btnAppliquer.Enabled = false; btnAppliquer.BackColor = Color.LightGray; btnAppliquer.ForeColor = Color.Black; btnSupprimer.Enabled = false; btnSupprimer.BackColor = Color.LightGray; btnSupprimer.ForeColor = Color.Black; tbProfil.Enabled = false; tbLogin.Enabled = false; tbProfil.Text = ""; tbLogin.Text = ""; tbPassword.Text = ""; tbPassword.Enabled = false; tbURL.Text = ""; tbURL.Enabled = false; } btnAppliquer.Enabled = false; btnAppliquer.BackColor = Color.LightGray; btnAppliquer.ForeColor = Color.Black; }
private void UpdateUser() { if (position < 0) { return; } PirepUser User = Users[position]; User.Profil = tbProfil.Text; User.Login = tbLogin.Text; User.Password = Outils.Encrypt(tbPassword.Text); tbURL.Text = tbURL.Text.ToLower(); if (tbURL.Text.StartsWith("http://")) { tbURL.Text = tbURL.Text.Substring(7); } User.URL = tbURL.Text; ListUsers.SelectedNode.Text = User.Profil; Users[position] = User; }
private void ProcessIncomingData(object obj) { try { lock (m_ClientLock) { TCPReceiveEvent Packet = (TCPReceiveEvent)obj; FireReceiveMessage(ref Packet); #if DEBUG Log.LogMessage("TCPServer : Requête entrante de " + (Packet.Client.Address.ToString() + " : " + Outils.HexToString(Packet.Data, Packet.Data.Length)), Color.Blue, 2); #endif } } catch (SocketException Ex) { Log.LogMessage("TCPServer : Problème Socket : " + Ex.Message, Color.DarkBlue, 0); } }
/// <summary> /// Construit le patron /// </summary> /// <param name="Doc"></param> /// <param name="Code"></param> private void XmlBuild(ref XmlDocument Doc, XmlCode Code) { if (Doc == null) { Doc = new XmlDocument(); } else { Doc.RemoveAll(); } sVersion Actual = Outils.GetVersion(); //Déclaration de la norme utilisée XmlDeclaration xmlDeclaration = Doc.CreateXmlDeclaration("1.0", "UTF-8", null); XmlElement root = Doc.DocumentElement; Doc.InsertBefore(xmlDeclaration, root); //Création de la racine XmlElement xmlffs2play = Doc.CreateElement(string.Empty, "ffs2play", string.Empty); Doc.AppendChild(xmlffs2play); //Création de la version XmlElement xmlVersion = Doc.CreateElement(string.Empty, "version", string.Empty); xmlVersion.InnerText = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + "_" + Actual.Major.ToString() + "_" + Actual.Minor.ToString() + "_" + Actual.Build.ToString(); xmlffs2play.AppendChild(xmlVersion); //Activation du P2P; XmlElement xmlP2P = Doc.CreateElement(string.Empty, "P2P", string.Empty); xmlP2P.InnerText = Properties.Settings.Default.P2PEnable.ToString(); xmlffs2play.AppendChild(xmlP2P); //Création du switch XmlElement xmlSwitch = Doc.CreateElement(string.Empty, "switch", string.Empty); xmlffs2play.AppendChild(xmlSwitch); //Création du data XmlElement xmlData = Doc.CreateElement(string.Empty, "data", string.Empty); xmlData.InnerText = Code.ToString(); xmlSwitch.AppendChild(xmlData); //Création du key XmlElement xmlKey = Doc.CreateElement(string.Empty, "key", string.Empty); xmlKey.InnerText = Key; xmlSwitch.AppendChild(xmlKey); switch (Code) { case XmlCode.hello: XmlElement xmlHello = Doc.CreateElement(string.Empty, "hello", string.Empty); xmlffs2play.AppendChild(xmlHello); //Création de la balise pilotID XmlElement xmlLogin = Doc.CreateElement(string.Empty, "pilotID", string.Empty); xmlLogin.InnerText = User.Login; xmlHello.AppendChild(xmlLogin); break; case XmlCode.verify: //Création de la balise verify XmlElement xmlVerify = Doc.CreateElement(string.Empty, "verify", string.Empty); xmlffs2play.AppendChild(xmlVerify); //Création de la balise AES XmlElement xmlAES = Doc.CreateElement(string.Empty, "AES", string.Empty); xmlAES.InnerText = Crypted_AESKey; xmlVerify.AppendChild(xmlAES); //Création de la balise pilotID XmlElement xmlPilotID = Doc.CreateElement(string.Empty, "pilotID", string.Empty); xmlPilotID.InnerText = User.Login; xmlVerify.AppendChild(xmlPilotID); //Création de la balise password XmlElement xmlPassword = Doc.CreateElement(string.Empty, "password", string.Empty); xmlPassword.InnerText = Outils.EncryptMessage(Outils.Decrypt(User.Password), m_sAESKey); xmlVerify.AppendChild(xmlPassword); //Envoi du port en écoute XmlElement xmlPort = Doc.CreateElement(string.Empty, "port", string.Empty); xmlPort.InnerText = P2P.Port.ToString(); xmlVerify.AppendChild(xmlPort); //Envoi du port en écoute XmlElement xmlLocalIP = Doc.CreateElement(string.Empty, "local_ip", string.Empty); xmlLocalIP.InnerText = P2P.LocalIPSerialized; xmlVerify.AppendChild(xmlLocalIP); break; case XmlCode.liveupdate: //Création de la balise liveupdate XmlElement xmlLiveUpdate2 = Doc.CreateElement(string.Empty, "liveupdate", string.Empty); xmlffs2play.AppendChild(xmlLiveUpdate2); xmlLiveUpdate2.AppendChild(Doc.CreateElement(string.Empty, "registration", string.Empty)); //Création de la balise registration xmlLiveUpdate2.AppendChild(Doc.CreateElement(string.Empty, "latitude", string.Empty)); //Création de la balise latitude xmlLiveUpdate2.AppendChild(Doc.CreateElement(string.Empty, "longitude", string.Empty)); //Création de la balise longitude xmlLiveUpdate2.AppendChild(Doc.CreateElement(string.Empty, "heading", string.Empty)); //Création de la balise heading xmlLiveUpdate2.AppendChild(Doc.CreateElement(string.Empty, "altitude", string.Empty)); //Création de la balise altitude xmlLiveUpdate2.AppendChild(Doc.CreateElement(string.Empty, "groundSpeed", string.Empty)); //Création de la balise groundSpeed xmlLiveUpdate2.AppendChild(Doc.CreateElement(string.Empty, "iaspeed", string.Empty)); //Création de la balise iaspeed xmlLiveUpdate2.AppendChild(Doc.CreateElement(string.Empty, "squawk", string.Empty)); //Création de la balise squawk xmlLiveUpdate2.AppendChild(Doc.CreateElement(string.Empty, "onground", string.Empty)); //Création de la balise onground xmlLiveUpdate2.AppendChild(Doc.CreateElement(string.Empty, "sim", string.Empty)); //Création de la balise simulateur break; case XmlCode.atc: //Création de la balise liveupdate XmlElement xmlAtc = Doc.CreateElement(string.Empty, "atc", string.Empty); xmlffs2play.AppendChild(xmlAtc); xmlAtc.AppendChild(Doc.CreateElement(string.Empty, "latitude", string.Empty)); //Création de la balise latitude xmlAtc.AppendChild(Doc.CreateElement(string.Empty, "longitude", string.Empty)); //Création de la balise longitude xmlAtc.AppendChild(Doc.CreateElement(string.Empty, "heading", string.Empty)); //Création de la balise heading xmlAtc.AppendChild(Doc.CreateElement(string.Empty, "altitude", string.Empty)); //Création de la balise altitude xmlAtc.AppendChild(Doc.CreateElement(string.Empty, "groundSpeed", string.Empty)); //Création de la balise groundSpeed xmlAtc.AppendChild(Doc.CreateElement(string.Empty, "iaspeed", string.Empty)); //Création de la balise iaspeed xmlAtc.AppendChild(Doc.CreateElement(string.Empty, "squawk", string.Empty)); //Création de la balise squawk break; case XmlCode.syncai: XmlElement xmlSyncAI = Doc.CreateElement(string.Empty, "syncai", string.Empty); xmlffs2play.AppendChild(xmlSyncAI); xmlSyncAI.AppendChild(Doc.CreateElement(string.Empty, "md5list", string.Empty)); break; case XmlCode.sendai: XmlElement xmlSendAI = Doc.CreateElement(string.Empty, "sendai", string.Empty); xmlffs2play.AppendChild(xmlSendAI); break; } }
/// <summary> /// Méthode cyclique du timer /// Gestion des tâches périodiques /// Pour les demandes de données sur le simulateur /// </summary> /// <param name="source"></param> /// <param name="evt"></param> private void OnLiveUpdate(object source, ElapsedEventArgs evt) { if (IsConnected() && SCM.IsConnected()) { XmlBuild(ref SendUpdate, XmlCode.liveupdate); XmlNodeList Nodes = SendUpdate.GetElementsByTagName("liveupdate"); foreach (XmlNode node in Nodes) { foreach (XmlNode child in node.ChildNodes) { switch (child.Name) { case "pilotID": child.InnerText = User.Login; break; case "registration": child.InnerText = Analyse.GetLastState().Title; break; case "latitude": child.InnerText = string.Format("{0:0.00000}", Analyse.GetLastState().Latitude); break; case "longitude": child.InnerText = string.Format("{0:0.00000}", Analyse.GetLastState().Longitude); break; case "heading": child.InnerText = string.Format("{0:0.}", Analyse.GetLastState().Heading); break; case "altitude": child.InnerText = string.Format("{0:0.}", Analyse.GetLastState().Altitude); break; case "groundSpeed": child.InnerText = string.Format("{0:0.}", Analyse.GetLastState().GSpeed); break; case "iaspeed": child.InnerText = string.Format("{0:0.}", Analyse.GetLastState().IASSpeed); break; case "squawk": child.InnerText = string.Format("{0:0.}", Outils.ConvertToBinaryCodedDecimal(Analyse.GetLastState().Squawk)); break; case "onground": child.InnerText = string.Format("{0:0.}", Convert.ToInt32(Analyse.GetLastState().OnGround)); break; case "sim": child.InnerText = SCM.GetVersion().ToString(); break; } } } #if DEBUG Log.LogMessage("PManager: Mise à jour de la position =\n " + Beautify(SendUpdate), Color.DarkRed, 2); #endif HTTPRequestThread Requete = new HTTPRequestThread(SendUpdate, m_sURL, LiveUpdateCB); Requete.Start(); } }
private void RempliTableau() { if (m_lvDonneesFS.InvokeRequired) { RempliTableauCallback d = new RempliTableauCallback(RempliTableau); m_lvDonneesFS.Invoke(d); } else { // On rempli la ligne correspondante dans la listview foreach (ListViewItem Item in m_lvDonneesFS.Items) { if (Item.SubItems.Count < 1) { continue; } ListViewItem.ListViewSubItem Sub = Item.SubItems[1]; switch (Item.Text) { case "Titre Avion": Sub.Text = GetLastState().Title; break; case "Type Avion": Sub.Text = GetLastState().Type; break; case "Model Avion": Sub.Text = GetLastState().Model; break; case "Catégorie": Sub.Text = GetLastState().Category; break; case "Altitude Avion": Sub.Text = string.Format("{0:0.} ft", GetLastState().Altitude); break; case "Altitude Sol": Sub.Text = string.Format("{0:0.} ft", GetLastState().Altitude - GetLastState().AltitudeSol); break; case "Vario": Sub.Text = string.Format("{0:0.} ft/min", GetLastState().Vario); break; case "Direction": Sub.Text = string.Format("{0:0.} °", GetLastState().Heading); break; case "Delta Altitude": Sub.Text = string.Format("{0:0.} ft", GetLastState().AltitudeSol); break; case "Facteur Temps": Sub.Text = string.Format("{0:0}X", GetLastState().TimeFactor); break; case "Longitude": Sub.Text = string.Format("{0:0.000}°", GetLastState().Longitude); break; case "Latitude": Sub.Text = string.Format("{0:0.000}°", GetLastState().Latitude); break; case "Vitesse Sol": Sub.Text = string.Format("{0:0.}Kts", GetLastState().GSpeed); break; case "Vitesse TAS": Sub.Text = string.Format("{0:0.}Kts", GetLastState().TASSpeed); break; case "Carburant": Sub.Text = string.Format("{0:0.}Lbs", GetLastState().Fuel); break; case "Cabrage Avion": Sub.Text = string.Format("{0:0.0}°", GetLastState().Pitch); break; case "Roulis Avion": Sub.Text = string.Format("{0:0.0}°", GetLastState().Bank); break; case "G Force": Sub.Text = string.Format("{0:0.0} G", GetLastState().GForce); break; case "Poids Avion": Sub.Text = string.Format("{0:0.}Lbs", GetLastState().PoidsAvion); break; case "Total Fuel Capacity": Sub.Text = string.Format("{0:0} Lbs", GetLastState().TotalFuelCapacity); break; case "Vitesse du vent": Sub.Text = string.Format("{0:0} Kts", GetLastState().AmbiantWindVelocity); break; case "Direction du vent": Sub.Text = string.Format("{0:0} °", GetLastState().AmbiantWindDirection); break; case "Précipitation": Sub.Text = string.Format("{0:0}", GetLastState().AmbiantPrecipState); break; case "Pression Atm": Sub.Text = string.Format("{0:0} mBar", GetLastState().AltimeterSetting); break; case "Pression MSL": Sub.Text = string.Format("{0:0} mBar", GetLastState().SeaLevelPressure); break; case "Profondeur": Sub.Text = string.Format("{0:0.000}", GetLastState().ElevatorPos); break; case "Ailerons": Sub.Text = string.Format("{0:0.000}", GetLastState().AileronPos); break; case "Derive": Sub.Text = string.Format("{0:0.000}", GetLastState().RudderPos); break; case "Aerofreins": Sub.Text = string.Format("{0:0.000}", GetLastState().SpoilerPos); break; case "Frein de parking": Sub.Text = string.Format("{0:0.000}", GetLastState().ParkingBrakePos); break; case "Squawk": Sub.Text = string.Format("{0:0}", Outils.ConvertToBinaryCodedDecimal(GetLastState().Squawk)); break; default: break; } } } }
/// <summary> /// Callback Requete de mise à jour /// </summary> /// <param name="asyncResult"></param> private void LiveUpdateCB(HttpWebResponse Response) { // Si pas connecté au serveur on ignore le CB if (!m_bConnected) { return; } XmlDocument xmlDoc = null; // On récupère le contenu XML if (Response != null) { xmlDoc = GetResultXml(ref Response); Response.Close(); } // Si le contenu est vide on ignore le CB if (xmlDoc == null) { return; } LastGoodUpdate = DateTimeEx.UtcNowMilli; //On vérifie les erreurs retournées par le serveur if (CheckError(xmlDoc)) { Disconnect(); return; } // On charge la liste des joueurs depuis le wazzup XmlNode Wazzup = GetFirstElement(ref xmlDoc, "whazzup"); if (Wazzup != null) { P2P.Wazzup_Update(Wazzup, m_sAESKey); } //On synchronise le serveur avec les AI disponibles if ((!m_SyncAIDone) && m_AIManagement) { if (!Mapping.IsInit) { return; } XmlBuild(ref SendSyncAI, XmlCode.syncai); XmlNodeList Nodes = SendSyncAI.GetElementsByTagName("syncai"); foreach (XmlNode node in Nodes) { foreach (XmlNode child in node.ChildNodes) { switch (child.Name) { case "md5list": child.InnerText = Outils.PhpSerialize(Mapping.GetList.Keys); break; } } } HTTPRequestThread Requete = new HTTPRequestThread(SendSyncAI, m_sURL, SyncAICB); Requete.Start(); #if DEBUG Log.LogMessage("PManager: Synchronisation des AI : \n" + Beautify(SendSyncAI), Color.DarkRed, 2); #endif } // On check la méteo XmlNode Metar = GetFirstElement(ref xmlDoc, "metar"); if (Metar != null) { MetarUpdate(ref Metar); } }
/// <summary> /// Envoi un datagramme /// </summary> /// <param name="remoteEP"></param> /// <param name="buffer"></param> public void Send(ref IPEndPoint remoteEP, byte[] buffer) { if ((m_listener != null) && (buffer != null)) { try { m_listener.SendTo(buffer, remoteEP); #if DEBUG Log.LogMessage("TCPServer : Données sortante vers " + remoteEP.Address.ToString() + " sur le Port = " + remoteEP.Port.ToString() + ": " + Outils.HexToString(buffer, buffer.Length), Color.Blue, 2); #endif } catch (SocketException ex) { #if DEBUG Log.LogMessage("Exception écriture socket : " + ex.ErrorCode.ToString(), Color.Violet); #endif } catch (Exception ex) { #if DEBUG Log.LogMessage("Exception écriture socket : " + ex.Message.ToString(), Color.Violet); #endif } } }
/// <summary> /// Réception d'un datagramme entrant sur le socket udp /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnReceiveMessage(object sender, UDPReceiveEvent evt) { // Si l'adresse du peer est nulle cela signifie que le wazzhup update a détecté un PEER local if (m_EP == null) { // Si le peer à une addresse locale qui correspond // Il s'agit d'un client sur le même réseau local // On prend alors cette IP locale comme référence if (m_InternalIP.Contains(evt.Client.Address)) { m_EP = new IPEndPoint(evt.Client.Address, m_Port); } else { return; } } else if ((!evt.Client.Address.Equals(m_EP.Address)) || (evt.Client.Port != m_Port)) { return; } BinaryReader reader = new BinaryReader(new MemoryStream(evt.Data)); try { switch ((Protocol)reader.ReadByte()) { case Protocol.PING: { SendPong(evt.Time); break; } case Protocol.PONG: { m_Latence = (evt.Time - m_LastPing) / 2; m_Counter = 0; long TimePong = reader.ReadInt64(); if (m_MiniPing > m_Latence) { m_Decalage = evt.Time - m_Latence - TimePong; m_MiniPing = m_Latence; } if (!m_OnLine) { #if DEBUG Log.LogMessage("Peer [" + CallSign + "] Passage en état OnLine", Color.DarkBlue, 1); #endif m_OnLine = true; m_Distance = -1; m_Counter_In = 0; m_Counter_Out = 0; } if (m_Version == 0) { RequestVersion(); } P2P.UpdateListItem(m_CallSign); break; } case Protocol.CHAT: { string Message = reader.ReadString(); P2P.AddLineChat(CallSign, Message); m_SC.SendScrollingText(CallSign + " : " + Message); break; } case Protocol.DATA: { if (m_Version == PROTO_VERSION) { if (m_bBlockData) { return; } m_Mutex.WaitOne(); try { byte CounterIn = reader.ReadByte(); // Si le compteur reçu est supérieur nous avons une donnée récente if (((CounterIn - m_Counter_In) > 0) || (m_Counter_In == 255)) { m_OldData.Clone(m_Data); int Len = reader.ReadInt32(); reader.BaseStream.Seek(2, 0); m_Data = (AirData)Serializer.Deserialize <AirData>(reader.BaseStream); m_Data.TimeStamp += m_Decalage; if (m_Data.TimeStamp <= m_OldData.TimeStamp) { #if DEBUG Log.LogMessage("Peer[" + CallSign + "] Donées en retard ignorées", Color.DarkBlue, 1); #endif return; } if ((m_Spawned >= 4) && (m_Spawned < 5)) { m_Spawned++; } m_RefreshRate = evt.Time - m_LastData; m_LastData = evt.Time; m_RemoteRefreshRate = m_Data.TimeStamp - m_OldData.TimeStamp; m_Distance = Outils.distance(m_Data.Latitude, m_Data.Longitude, m_SendData.Latitude, m_SendData.Longitude, 'N'); #if DEBUG if ((CounterIn - m_Counter_In) > 1) { Log.LogMessage("Peer [" + CallSign + "] Paquets Udp Manquants =" + (CounterIn - m_Counter_In - 1).ToString(), Color.DarkViolet, 1); } #endif if (m_Spawned >= 5) { RefreshData(); } } #if DEBUG else { Log.LogMessage("Peer [" + CallSign + "] Paquets Udp ignoré en retard de " + (m_Counter_In - CounterIn).ToString(), Color.DarkViolet, 1); } #endif m_Counter_In = CounterIn; } finally { m_Mutex.ReleaseMutex(); } } break; } case Protocol.VERSION: { m_Version = reader.ReadByte(); if (m_Version == PROTO_VERSION) { m_Data.Title = reader.ReadString(); if (m_Spawned >= 3) { Spawn_AI(false); } m_Data.Type = reader.ReadString(); m_Data.Model = reader.ReadString(); m_Data.Category = reader.ReadString(); } P2P.UpdateListItem(m_CallSign); #if DEBUG Log.LogMessage("Peer [" + CallSign + "] reçu numéro de version = " + m_Version.ToString(), Color.DarkBlue, 1); #endif break; } case Protocol.REQ_VERSION: { SendVersion(); break; } } } catch (Exception e) { Log.LogMessage("Peer [" + CallSign + "] Erreur d'analyse du datagramme : " + e.Message, Color.DarkViolet, 0); } }
public void UpdatePeerDetail() { if (m_lvUsers.SelectedItems.Count == 0) { ClearPeerDetail(); return; } ListViewItem User = m_lvUsers.SelectedItems[0]; Peer Pair = Peers.Find(x => x.CallSign == User.Text); if (Pair != null) { // On rempli la ligne correspondante dans la listview foreach (ListViewItem Item in m_lvPeerDetail.Items) { if (Item.SubItems.Count < 1) { continue; } ListViewItem.ListViewSubItem Sub = Item.SubItems[1]; switch (Item.Text) { case "Statut": if (Pair.IsOnline) { Sub.Text = "Connecté"; } else { Sub.Text = "Déconnecté"; } break; case "Refresh": Sub.Text = string.Format("{0:0000} mSec", Pair.RefreshRate); break; case "Latence": Sub.Text = string.Format("{0:0.} mSec", Pair.Latence); break; case "Distance": Sub.Text = string.Format("{0:0.0} Nm", Pair.Distance); break; case "Altitude": Sub.Text = string.Format("{0:0.} ft", Pair.Altitude); break; case "Longitude": Sub.Text = string.Format("{0:0.000}°", Pair.Longitude); break; case "Latitude": Sub.Text = string.Format("{0:0.000}°", Pair.Latitude); break; case "Bank Angle": Sub.Text = string.Format("{0:0.000}°", Pair.BankAngle); break; case "Pitch Angle": Sub.Text = string.Format("{0:0.000}°", Pair.PitchAngle); break; case "Vitesse": Sub.Text = string.Format("{0:0.} KIAS", Pair.Vitesse); break; case "Direction": Sub.Text = string.Format("{0:0.} °", Pair.Direction); break; case "OnGround": Sub.Text = string.Format("{0:0.}", Pair.OnGround); break; case "Version": Sub.Text = string.Format("{0:0.}", Pair.Version); break; case "Squawk": Sub.Text = string.Format("{0:0.}", Outils.ConvertToBinaryCodedDecimal(Pair.Squawk)); break; case "Titre": Sub.Text = Pair.Titre; break; case "Model": Sub.Text = Pair.Model; break; case "Type": Sub.Text = Pair.Type; break; case "Refresh Distant": Sub.Text = string.Format("{0:0000} mSec", Pair.RemoteRefreshRate); break; case "Décalage": Sub.Text = string.Format("{0:000000} mSec", Pair.Decalage); break; case "Spawned": Sub.Text = Pair.Spawned.ToString(); break; case "Object_ID": Sub.Text = Pair.ObjectId.ToString(); break; case "Ecart": Sub.Text = string.Format("{0:0.0} Nm", Pair.Ecart); break; case "Last Update": Sub.Text = string.Format(DateTimeEx.TimeFromUnixTimestamp(Pair.LastAIUpdate).ToLongTimeString()); break; } } } else { ClearPeerDetail(); } }
/// <summary> /// Mise à jour de l'annuaire des peers connecté sur le serveur web /// </summary> /// <param name="Liste"></param> public void Wazzup_Update(XmlNode Liste, string pAESKey) { //Détection Shadow string UserName = PirepManager.Instance.Get_UserName(); UserName = UserName.Replace('[', '_'); UserName = UserName.Replace(']', '_'); UserName = UserName.ToLower(); foreach (XmlNode Child in Liste.ChildNodes) { bool Shadow = false; bool Disabled = IsDisabled(Child.Name); //Détection Shadow if (UserName == Child.Name.ToLower()) { #if DEBUG if (Properties.Settings.Default.ShadowEnable) { Shadow = true; } else #endif continue; } IPAddress IP = IPAddress.Parse("0.0.0.0"); int Port = 0; List <IPAddress> Local_IP = new List <IPAddress>(); //Le partenaire est il déjà présent dans la liste? Peer test = Peers.Find(x => x.CallSign == Child.Name); //Si non, on le crée if (test == null) { foreach (XmlAttribute Item in Child.Attributes) { switch (Item.Name) { case ("ip"): { if (Shadow) { IP = IPAddress.Parse("127.0.0.1"); } else { string sIP = Outils.DecryptMessage(Item.Value, pAESKey); if (!IPAddress.TryParse(sIP, out IP)) { Log.LogMessage("P2P Manager : Adresse IP invalide", Color.DarkViolet); IP = IPAddress.Parse("0.0.0.0"); } } break; } case ("port"): { Port = int.Parse(Item.Value); break; } case ("local_ip"): { try { if (Item.Value != "na") { MemoryStream Data = new MemoryStream(Convert.FromBase64String(Item.Value)); List <string> sLocal_IP = Serializer.Deserialize <List <string> >(Data); foreach (string item in sLocal_IP) { IPAddress ip; if (IPAddress.TryParse(item, out ip)) { Local_IP.Add(ip); } } } } catch (Exception e) { Log.LogMessage("P2P Manager : Erreur Whazzup Update = " + e.Message, Color.DarkViolet); } break; } } } if ((!IP.Equals(IPAddress.Parse("0.0.0.0"))) && (Port > 0)) { Peers.Add(new Peer(ref Server, IP, Port, Child.Name, Disabled, m_ExternalIP.Equals(IP), Local_IP)); UpdateList(); #if DEBUG Log.LogMessage("P2PManager: Ajout d'un utilisateur P2P Nom = " + Child.Name + ", IP=" + IP + ", Port=" + Port.ToString(), Color.Blue, 1); if (Local_IP != null) { foreach (IPAddress sip in Local_IP) { Log.LogMessage("P2PManager: Liste ip locale = " + sip.ToString(), Color.Blue, 1); } } #endif } else { Log.LogMessage("P2PManager: Utilisateur " + Child.Name + " ignoré", Color.Violet); } } //Si oui , on le met à jour else { foreach (XmlAttribute Item in Child.Attributes) { switch (Item.Name) { case ("ip"): { if (Shadow) { IP = IPAddress.Parse("127.0.0.1"); } else { string sIP = Outils.DecryptMessage(Item.Value, pAESKey); if (!IPAddress.TryParse(sIP, out IP)) { Log.LogMessage("P2P Manager : Adresse IP invalide", Color.DarkViolet); IP = IPAddress.Parse("0.0.0.0"); } } if (!test.ExternalIP.Equals(IP)) { #if DEBUG Log.LogMessage("P2PManager: Modification IP de = " + test.CallSign + ", IP=" + test.ExternalIP.ToString(), Color.Blue, 1); #endif DeleteUser(test.CallSign); } break; } case ("port"): { if (test.Port != int.Parse(Item.Value)) { #if DEBUG Log.LogMessage("P2PManager: Modification Port de = " + test.CallSign + ", Port=" + test.Port.ToString(), Color.Blue, 1); #endif DeleteUser(test.CallSign); } break; } } } } } // Recherche Inverse pour détecter un joueur déconnecté for (int i = Peers.Count - 1; i >= 0; i--) { bool find = false; foreach (XmlNode Child in Liste.ChildNodes) { if (Peers[i].CallSign == Child.Name) { if ((!Properties.Settings.Default.ShadowEnable) && (Child.Name == UserName)) { find = false; } else { find = true; } } } if (!find) { #if DEBUG Log.LogMessage("P2PManager: Supression du joueur " + Peers[i].CallSign, Color.Blue, 1); #endif Peers[i].Dispose(); Peers.RemoveAt(i); } } UpdateList(); }