/// <summary> /// Constructor, inicializa los valores por omisión de la configuración. /// </summary> public NetData() { pickNewIp(); IpUdpMulticast = "224.0.0.2"; TcpPort = 30001; UdpPort = 30002; SubnetMask = "255.255.0.0"; NetworkAdapter = SystemHandler.getWifiAdapter(); AdhocNetworkName = "HLMP-MANET"; OpSystem = OpSystemType.WINMOBILE5POCKETPC; WaitTimeWiFi = 5000; WaitTimeStart = 5000; WaitForStart = 10; WaitForWifi = 7; TimeOutWriteTCP = 2000; TimeIntervalTimer = 1000; WaitForTimerClose = 20; WaitForTCPConnection = 20; WaitForAck = 10; MaxMessagesProcess = 2500; QualityRiseNetUser = 5; QualityMaxNetUser = 25; QualityNormalNetUser = 15; QualityLowNetUser = 5; LolinessTimeOut = 15; SendFailsToDisconnect = 5; TcpConnectTimeOut = 2000; StateCritical = 20; StateOverloaded = 10; StatePathNN = 1; StatePathNL = 2; StatePathNC = 4; StatePathON = 10; StatePathOL = 20; StatePathOC = 40; StatePathCN = 100; StatePathCL = 200; StatePathCC = 400; StatePathNotFound = 1000000; }
/// <summary> /// Verifica que no exista Ip duplicada en el sistema operativo, si gatilla resetIpDelegate, asegura que el Thread se detendrá /// </summary> private void checkIp() { while (true) { System.Threading.Thread.Sleep(netData.WaitTimeStart); //Chequea Strong DAD if (state.Equals(IphandlerState.STARTEDSTRONG)) { int ipState = SystemHandler.getIpState(netData.NetworkAdapter, netData.IpTcpListener); switch (ipState) { case IpState.DUPLICATE: { resetIpDelegate(); return; } case IpState.NOTFOUND: { resetIpDelegate(); return; } } } else if (state.Equals(IphandlerState.STARTEDWEAK)) { //Chequea Weak DAD lock (queueLock) { while (queue.Count > 0) { IPAddress outterIp = queue.Dequeue(); if (outterIp.Equals(netData.IpTcpListener)) { resetIpDelegate(); return; } } } //chequea Strong DAD int ipState = SystemHandler.getIpState(netData.NetworkAdapter, netData.IpTcpListener); switch (ipState) { case IpState.DUPLICATE: { resetIpDelegate(); return; } case IpState.INVALID: { resetIpDelegate(); return; } case IpState.NOTFOUND: { resetIpDelegate(); return; } } //Chequea loneliness if (netData.OpSystem == OpSystemType.WIN7) { Int64 nBytes = SystemHandler.getAliveValue(netData.NetworkAdapter); if (nBytes == lastAliveValue) { lolinessTimeOut++; if (lolinessTimeOut >= netData.LolinessTimeOut) { resetIpDelegate(); return; } } else { lolinessTimeOut = 0; } lastAliveValue = nBytes; } //Chequea operatividad del adaptador if (netData.OpSystem == OpSystemType.WIN7) { if (!SystemHandler.isOperative(netData.NetworkAdapter)) { resetIpDelegate(); return; } } } //Detiene o duerme segun corresponda lock (stopLock) { if (state.Equals(IphandlerState.STOPPED)) { return; } } } }
/// <summary> /// Verifica la conexión de la red ad-hoc /// </summary> internal void checkWLanConnection() { try { //Revisa si hay un adaptador seleccionado en la configuración if (netData.NetworkAdapter == null) { throw new Exception("no hay un adaptador de red seleccionado"); } INetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (INetworkInterface networkInterface in networkInterfaces) { if (netData.NetworkAdapter.Name.Equals(networkInterface.Name)) { WirelessZeroConfigNetworkInterface adapter = (WirelessZeroConfigNetworkInterface)networkInterface; String ssid = adapter.AssociatedAccessPoint; if (ssid == null) { connectionState = WifiConnectionState.DISCONNECTED; wifiInformation("disconnected"); } else if (netData.AdhocNetworkName.Equals(ssid) && adapter.OperationalStatus == OperationalStatus.Up && SystemHandler.getIpState(netData.NetworkAdapter, netData.IpTcpListener) != IpState.NOTFOUND) { connectionState = WifiConnectionState.CONNECTED; wifiInformation("connected"); } else if (netData.AdhocNetworkName.Equals(ssid) && adapter.OperationalStatus != OperationalStatus.Up) { connectionState = WifiConnectionState.WAINTING; wifiInformation("waiting"); } else { connectionState = WifiConnectionState.DISCONNECTED; wifiInformation("disconnected"); } break; } } } catch (ThreadAbortException e) { throw e; } catch (Exception e) { wifiInformation("error " + e.Message); } }
/// <summary> /// Se gatilla para terminar los servicios /// Si ocurre algun error se informa en informationNetworkingHandler, no se detiene ejecución /// </summary> private void stop() { commHandler.informationNetworkingHandler("NETHANDLER: stop netHandler..."); netHandlerState = NetHandlerState.STOPPING; try { commHandler.informationNetworkingHandler("NETHANDLER: stop DAD..."); ipHandler.stop(); commHandler.informationNetworkingHandler("NETHANDLER: stop DAD... ok!"); } catch (Exception e) { commHandler.informationNetworkingHandler("NETHANDLER: stop DAD... failed! " + e.Message); } try { commHandler.informationNetworkingHandler("NETHANDLER: stop communication..."); commHandler.stopNetworkingHandler(); commHandler.informationNetworkingHandler("NETHANDLER: stop communication... ok!"); } catch (Exception e) { commHandler.informationNetworkingHandler("NETHANDLER: stop communication... failed! " + e.Message); } //Cerrado de threads y canales de red UDP try { commHandler.informationNetworkingHandler("NETHANDLER: drop multicast suscription..."); udpClient.DropMulticastGroup(udpMulticastAdress); commHandler.informationNetworkingHandler("NETHANDLER: drop multicast suscription... ok!"); } catch (Exception e) { commHandler.informationNetworkingHandler("NETHANDLER: drop multicast suscription... failed! " + e.Message); } try { commHandler.informationNetworkingHandler("NETHANDLER: shudown UDP client..."); udpClient.Client.Shutdown(SocketShutdown.Both); commHandler.informationNetworkingHandler("NETHANDLER: shudown UDP client... ok!"); } catch (Exception e) { commHandler.informationNetworkingHandler(e.Message); commHandler.informationNetworkingHandler("NETHANDLER: shudown UDP client... failed! " + e.Message); } try { commHandler.informationNetworkingHandler("NETHANDLER: close UDP socket..."); udpClient.Client.Close(); commHandler.informationNetworkingHandler("NETHANDLER: close UDP socket... ok!"); } catch (Exception e) { commHandler.informationNetworkingHandler("NETHANDLER: close UDP socket... failed! " + e.Message); } try { commHandler.informationNetworkingHandler("NETHANDLER: close UDP client..."); udpClient.Close(); commHandler.informationNetworkingHandler("NETHANDLER: close UDP client... ok!"); } catch (Exception e) { commHandler.informationNetworkingHandler("NETHANDLER: close UDP client... failed! " + e.Message); } try { commHandler.informationNetworkingHandler("NETHANDLER: stop UDP thread..."); udpClientThread.Abort(); udpClientThread.Join(); commHandler.informationNetworkingHandler("NETHANDLER: stop UDP thread... ok!"); } catch (Exception e) { commHandler.informationNetworkingHandler("NETHANDLER: stop UDP thread... failed! " + e.Message); } //Cerrado de threads y canales de red TCP try { commHandler.informationNetworkingHandler("NETHANDLER: stop TCP listener..."); tcpListener.Stop(); commHandler.informationNetworkingHandler("NETHANDLER: stop TCP listener... ok!"); } catch (Exception e) { commHandler.informationNetworkingHandler("NETHANDLER: stop TCP listener... failed! " + e.Message); } try { commHandler.informationNetworkingHandler("NETHANDLER: stop TCP thread..."); tcpListenerThread.Abort(); tcpListenerThread.Join(); commHandler.informationNetworkingHandler("NETHANDLER: stop TCP thread... ok!"); } catch (Exception e) { commHandler.informationNetworkingHandler("NETHANDLER: stop TCP thread... failed! " + e.Message); } //se deja la IP en el sistema operativo como por defecto (DHCP) try { commHandler.informationNetworkingHandler("NETHANDLER: dhcp on..."); SystemHandler.setDinamicIP(netData.NetworkAdapter); commHandler.informationNetworkingHandler("NETHANDLER: dhcp on... ok!"); } catch (Exception e) { commHandler.informationNetworkingHandler("NETHANDLER: dhcp on... failed!" + e.Message); } //detiene wifiHandler try { commHandler.informationNetworkingHandler("NETHANDLER: stop wifi..."); wifiHandler.disconnect(); commHandler.informationNetworkingHandler("NETHANDLER: stop wifi... ok!"); } catch (Exception e) { commHandler.informationNetworkingHandler("NETHANDLER: stop wifi... failed! " + e.Message); } //se cierran las conexiones aun existentes TCP try { commHandler.informationNetworkingHandler("NETHANDLER: kill TCP links..."); RemoteMachine[] serverRemoteMachines = tcpServerList.toObjectArray(); for (int i = 0; i < serverRemoteMachines.Length; i++) { try { commHandler.informationNetworkingHandler("NETHANDLER: kill TCP link... " + serverRemoteMachines[i].Ip); disconnectFrom(serverRemoteMachines[i]); commHandler.informationNetworkingHandler("NETHANDLER: kill TCP link... ok!"); } catch (Exception e) { commHandler.informationNetworkingHandler("NETHANDLER: kill TCP link... failed! " + e.Message); } } commHandler.informationNetworkingHandler("NETHANDLER: kill TCP links... ok!"); } catch (Exception e) { commHandler.informationNetworkingHandler("NETHANDLER: kill TCP links... failed! " + e.Message); } //reinicializacion de todos los objetos try { commHandler.informationNetworkingHandler("NETHANDLER: initialation of objects..."); init(); commHandler.informationNetworkingHandler("NETHANDLER: initialation of objects... ok!"); } catch (Exception e) { commHandler.informationNetworkingHandler("NETHANDLER: initialation of objects... failed! " + e.Message); } netHandlerState = NetHandlerState.STOPPED; commHandler.informationNetworkingHandler("NETHANDLER: stop netHandler... ok!"); commHandler.informationNetworkingHandler("NETHANDLER: bye bye!"); }
/// <summary> /// Se gatilla para levantar los servicios /// Si ocurre un error se arroja /// </summary> private void start() { try { if (netData.OpSystem == OpSystemType.WINXPSP3) { commHandler.informationNetworkingHandler("NETHANDLER: start netHandler..."); netHandlerState = NetHandlerState.STARTING; commHandler.informationNetworkingHandler("NETHANDLER: nerwork adapter is... " + netData.NetworkAdapter.Description); ////intenta poner la ip en modo estatico try { commHandler.informationNetworkingHandler("NETHANDLER: disable adapter..."); SystemHandler.disableIpAdapter(netData.NetworkAdapter); commHandler.informationNetworkingHandler("NETHANDLER: disable adapter... ok!"); } catch (ThreadAbortException e) { throw e; } catch (Exception e) { commHandler.informationNetworkingHandler("NETHANDLER: disable adapter... failed! " + e.Message); } try { commHandler.informationNetworkingHandler("NETHANDLER: set IP... " + netData.IpTcpListener); SystemHandler.setStaticIP(netData.NetworkAdapter, netData.IpTcpListener.ToString(), netData.SubnetMask); commHandler.informationNetworkingHandler("NETHANDLER: set IP... ok!"); } catch (ThreadAbortException e) { throw e; } catch (Exception e) { commHandler.informationNetworkingHandler("NETHANDLER: set IP... failed! " + e.Message); } try { commHandler.informationNetworkingHandler("NETHANDLER: enable adapter..."); SystemHandler.enableIpAdapter(netData.NetworkAdapter); commHandler.informationNetworkingHandler("NETHANDLER: enable adapter... ok!"); } catch (ThreadAbortException e) { throw e; } catch (Exception e) { commHandler.informationNetworkingHandler("NETHANDLER: enable adapter... failed! " + e.Message); } //hecha a andar wifiHandler commHandler.informationNetworkingHandler("NETHANDLER: start wifi..."); wifiHandler.connect(); //espera por primera conexión while (wifiHandler.ConnectionState == WifiConnectionState.DISCONNECTED) { commHandler.informationNetworkingHandler("NETHANDLER: waiting for other devices"); System.Threading.Thread.Sleep(netData.WaitTimeStart); } commHandler.informationNetworkingHandler("NETHANDLER: start wifi... ok!"); //Setea la IP en el sistema operativo Boolean ipChange = false; Int32 timeOutIpChange = 0; while (!ipChange) { try { commHandler.informationNetworkingHandler("NETHANDLER: set IP... " + netData.IpTcpListener); SystemHandler.setStaticIP(netData.NetworkAdapter, netData.IpTcpListener.ToString(), netData.SubnetMask); ipChange = true; commHandler.informationNetworkingHandler("NETHANDLER: set IP... ok!"); } catch (ThreadAbortException e) { throw e; } catch (Exception e) { commHandler.informationNetworkingHandler("NETHANDLER: set IP... failed! " + e.Message); timeOutIpChange++; if (timeOutIpChange > netData.WaitForStart) { throw new Exception("timeout, para configurar IP"); } System.Threading.Thread.Sleep(netData.WaitTimeStart); } } } else if (netData.OpSystem == OpSystemType.WIN7) { commHandler.informationNetworkingHandler("NETHANDLER: start netHandler..."); netHandlerState = NetHandlerState.STARTING; commHandler.informationNetworkingHandler("NETHANDLER: nerwork adapter is... " + netData.NetworkAdapter.Description); try { commHandler.informationNetworkingHandler("NETHANDLER: enable adapter..."); SystemHandler.enableIpAdapter(netData.NetworkAdapter); commHandler.informationNetworkingHandler("NETHANDLER: enable adapter... ok!"); } catch (ThreadAbortException e) { throw e; } catch (Exception e) { commHandler.informationNetworkingHandler("NETHANDLER: enable adapter... failed! " + e.Message); } //hecha a andar wifiHandler commHandler.informationNetworkingHandler("NETHANDLER: start wifi..."); wifiHandler.connect(); //espera por primera conexión while (wifiHandler.ConnectionState == WifiConnectionState.DISCONNECTED) { commHandler.informationNetworkingHandler("NETHANDLER: waiting for other devices"); System.Threading.Thread.Sleep(netData.WaitTimeStart); } commHandler.informationNetworkingHandler("NETHANDLER: start wifi... ok!"); //Setea la IP en el sistema operativo Boolean ipChange = false; Int32 timeOutIpChange = 0; while (!ipChange) { try { commHandler.informationNetworkingHandler("NETHANDLER: set IP... " + netData.IpTcpListener); SystemHandler.setStaticIP2(netData.NetworkAdapter, netData.IpTcpListener.ToString(), netData.SubnetMask); ipChange = true; commHandler.informationNetworkingHandler("NETHANDLER: set IP... ok!"); } catch (ThreadAbortException e) { throw e; } catch (Exception e) { commHandler.informationNetworkingHandler("NETHANDLER: set IP... failed! " + e.Message); timeOutIpChange++; if (timeOutIpChange > netData.WaitForStart) { throw new Exception("timeout, para configurar IP"); } System.Threading.Thread.Sleep(netData.WaitTimeStart); } } } //chequeo de ip commHandler.informationNetworkingHandler("NETHANDLER: start strong DAD"); ipHandler.startStrongDAD(); //Servicios TCP commHandler.informationNetworkingHandler("NETHANDLER: start TCP..."); tcpListener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1); Boolean tcpChange = false; Int32 timeOutTcpChange = 0; while (!tcpChange) { try { commHandler.informationNetworkingHandler("NETHANDLER: start TCP listener... " + netData.IpTcpListener + ":" + netData.TcpPort); tcpListener.Start(); tcpChange = true; commHandler.informationNetworkingHandler("NETHANDLER: start TCP listener... ok!"); } catch (ThreadAbortException e) { throw e; } catch (Exception e) { commHandler.informationNetworkingHandler("NETHANDLER: start TCP listener... failed! " + e.Message); timeOutTcpChange++; if (timeOutTcpChange > netData.WaitForStart) { throw new Exception("timeout, para levantar servicio TCP"); } else { System.Threading.Thread.Sleep(netData.WaitTimeStart); } } } tcpListenerThread.Start(); commHandler.informationNetworkingHandler("NETHANDLER: start TCP... ok!"); //conecta a UDP commHandler.informationNetworkingHandler("NETHANDLER: start UDP... " + netData.IpUdpMulticast + ":" + netData.UdpPort); udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1); //udpClient.Client.Bind(new IPEndPoint(IPAddress.Any, netData.UdpPort)); udpClient.Client.Bind(new IPEndPoint(tcpAddress, netData.UdpPort)); udpClient.JoinMulticastGroup(udpMulticastAdress, tcpAddress); udpIpEndPoint = new IPEndPoint(udpMulticastAdress, netData.UdpPort); udpClientThread.Start(); commHandler.informationNetworkingHandler("NETHANDLER: start UDP... ok!"); //cambio a cheque de ip debil commHandler.informationNetworkingHandler("NETHANDLER: start weak DAD"); ipHandler.chageToWeakDAD(); //Avisa que empiece la comunicacion commHandler.startNetworkingHandler(); netHandlerState = NetHandlerState.STARTED; commHandler.informationNetworkingHandler("NETHANDLER: start netHandler... ok!"); commHandler.informationNetworkingHandler("NETHANDLER: we are so connected!!! welcome to HLMP"); } catch (ThreadAbortException e) { commHandler.informationNetworkingHandler("NETHANDLER: start netHandler... failed! " + e.Message); } catch (Exception e) { //disconnect(); commHandler.informationNetworkingHandler("NETHANDLER: start netHandler... failed! " + e.Message); commHandler.errorNetworkingHandler(e); } }
/// <summary> /// Verifica que no exista Ip duplicada en el sistema operativo, si gatilla resetIpDelegate, asegura que el Thread se detendrá /// </summary> private void checkIp() { while (true) { System.Threading.Thread.Sleep(netData.WaitTimeStart); //Chequea Strong DAD if (state.Equals(IphandlerState.STARTEDSTRONG)) { try { int ipState = SystemHandler.getIpState(netData.NetworkAdapter, netData.IpTcpListener); switch (ipState) { case IpState.DUPLICATE: { resetIpDelegate(); return; } case IpState.NOTFOUND: { resetIpDelegate(); return; } } } catch (ThreadAbortException e) { throw e; } catch (Exception) { } } else if (state.Equals(IphandlerState.STARTEDWEAK)) { //Chequea Weak DAD lock (queueLock) { while (queue.Count > 0) { IPAddress outterIp = queue.Dequeue(); if (outterIp.Equals(netData.IpTcpListener)) { resetIpDelegate(); return; } } } //chequea Strong DAD try { int ipState = SystemHandler.getIpState(netData.NetworkAdapter, netData.IpTcpListener); switch (ipState) { case IpState.DUPLICATE: { resetIpDelegate(); return; } case IpState.INVALID: { resetIpDelegate(); return; } case IpState.NOTFOUND: { resetIpDelegate(); return; } } } catch (ThreadAbortException e) { throw e; } catch (Exception) { } //Chequea loneliness if (aliveValue > preAliveValue) { lolinessTimeOut = 0; } else { lolinessTimeOut++; if (lolinessTimeOut >= netData.LolinessTimeOut) { resetIpDelegate(); return; } } preAliveValue = aliveValue; } //Detiene o duerme segun corresponda lock (stopLock) { if (state.Equals(IphandlerState.STOPPED)) { return; } } } }
/// <summary> /// Es ejecutado por un thread para verificar el estado de la conexión con la red inalambrica /// </summary> private void wakeUpDaemon() { int sleepingPill = 0; while (true) { lock (syncPoint) { switch (connectionState) { case WifiConnectionState.CONNECTED: { sleepingPill = 0; break; } case WifiConnectionState.DISCONNECTED: { sleepingPill++; if (sleepingPill > netData.WaitForWifi) { sleepingPill = 0; try { wifiInformation("WIFI: disable adapter..."); SystemHandler.disableIpAdapter(netData.NetworkAdapter); wifiInformation("WIFI: disable adapter... ok!"); } catch (ThreadAbortException e) { throw e; } catch (Exception e) { wifiInformation("WIFI: disable adapter... failed! " + e.Message); } try { wifiInformation("WIFI: enable adapter..."); SystemHandler.enableIpAdapter(netData.NetworkAdapter); wifiInformation("WIFI: enable adapter... ok!"); } catch (ThreadAbortException e) { throw e; } catch (Exception e) { wifiInformation("WIFI: enable adapter... failed! " + e.Message); } } else { openWLanConnection(); } break; } case WifiConnectionState.WAINTING: { break; } } } if (connectionState == WifiConnectionState.STOP) { return; } else { Thread.Sleep(netData.WaitTimeWiFi); } } }