Exemplo n.º 1
0
        public void Run()
        {
            try
            {
                _Stop     = false;
                _Handlers = new ReceivedHandler[4] {
                    SetLongNames, SetAgenda, SetDependences, SetDependences
                };

                foreach (string str in Settings.Default.LongNames)
                {
                    string[] shortLong = str.Split('=');
                    _LongNames[shortLong[0].Trim()] = shortLong[1].Trim();
                }
                foreach (string str in Settings.Default.Alias)
                {
                    string[] nameAlias = str.Split('=');
                    _Alias[nameAlias[0].Trim()] = nameAlias[1].Trim();
                }

                if (Settings.Default.ListenPort != 0)
                {
                    _Comm = new UdpSocket(Settings.Default.ListenPort);
                    _Comm.MaxReceiveThreads = 1;
                    _Comm.NewDataEvent     += OnNewData;

                    _Comm.BeginReceive();
                }
            }
            catch (Exception) {}
        }
Exemplo n.º 2
0
        public void TestingMcastSendingAndReceive()
        {
            var Listener = new UdpSocket("192.168.90.50", 9000);

            //Listener.Base.MulticastLoopback = false;
            Listener.Base.JoinMulticastGroup(IPAddress.Parse("225.12.101.1"), IPAddress.Parse("192.168.90.50"));
            Listener.Base.JoinMulticastGroup(IPAddress.Parse("225.212.101.1"), IPAddress.Parse("192.168.90.50"));
            Listener.NewDataEvent += (s, d) =>
            {
                var from = d.Client.Address;
            };
            Listener.BeginReceive();

            var Sender = new UdpSocket(9001);

            Sender.Base.JoinMulticastGroup(IPAddress.Parse("225.12.101.1"), IPAddress.Parse("192.168.90.50"));
            IPEndPoint to1 = new IPEndPoint(IPAddress.Parse("225.12.101.1"), 9000);
            IPEndPoint to2 = new IPEndPoint(IPAddress.Parse("225.212.101.1"), 9000);

            Task.Delay(1000).Wait();
            Sender.Send(to1, new byte[] { 1, 2, 3 });
            Task.Delay(1000).Wait();
            Sender.Send(to2, new byte[] { 1, 2, 3 });

            Task.Delay(1000).Wait();
        }
Exemplo n.º 3
0
 void ToStart(object sender, ElapsedEventArgs e)
 {
     WorkingThread.Enqueue("Cluster Starting Timer", () =>
     {
         // 20170925. No arranca hasta que no consigue que se active la LAN Interna.
         // Se considera que hay red si se completa favorablemente toda la inicializacion ...
         // 20171019. Este parte del timer se ejecutará periodicamente hasta que se inicie la red interna...
         Logger.Info <Cluster>("Starting... (ToStart TICK)");
         try
         {
             _Comm = new UdpSocket(_Settings.Ip, _Settings.Port);
             _Comm.NewDataEvent += OnNewData;
             _Comm.BeginReceive();
             Logger.Info <Cluster>("Internal Network Available.");
         }
         catch (Exception x)
         {
             Logger.Exception <Cluster>(x);
             // Rearranco este timer...
             _ToStart.Enabled = true;
         }
         try
         {
             // 20171019. Esta parte del timer solo se ejecuta la primera vez...Si no hay errores internos...
             if (_State.LocalNode.State == NodeState.NoValid)
             {
                 // 20171019. Fuerzo el borrado de la IP virtual...
                 DeleteVirtualAddresses(true);
                 /////////////////////////////////////////////////
                 _State.LocalNode.ValidAdaptersMask = GetAdaptersState();
                 if (_State.LocalNode.ValidAdaptersMask > 0)
                 {
                     if (!ExistClusterAddresses())
                     {
                         //_State.LocalNode.SetState(NodeState.Activating, Resources.LocalActivateAsk);
                         _State.LocalNode.SetState(NodeState.NoActive, "Initial Status" /*Resources.LocalActivateAsk*/);
                     }
                     else
                     {
                         _State.LocalNode.SetState(NodeState.NoActive, Resources.FoundClusterIps);
                     }
                 }
                 else
                 {
                     _State.LocalNode.SetState(NodeState.NoActive, Resources.DeactivateByNotAdapters);
                 }
                 _PeriodicTasks.Enabled = true;
             }
         }
         catch (Exception x)
         {
             Logger.Exception <Cluster>(x);
             // Rearranco este timer...
             _ToStart.Enabled = true;
         }
     });
 }
Exemplo n.º 4
0
        public void Run()
        {
            ClusterConfigManager.Get((cfg) =>
            {
                Cfg    = cfg;
                Worker = new EventQueue();
                Worker.Start();

                Listener = new UdpSocket(cfg.IpInterna, cfg.PuertoInterno);
                Listener.NewDataEvent += OnNewData;
                Listener.BeginReceive();

                StartWebService();
            });
        }
Exemplo n.º 5
0
        public override void Start()
        {
            Logger.Info <PsiManager>($"Starting PsiManager...");
            try
            {
                Listener1 = new UdpSocket(Lan1Listen);
                /** Para seleccionar correctamente la Interfaz de salida de las tramas MCAST */
                //Listener1.Base.MulticastLoopback = false;
                Listener1.Base.JoinMulticastGroup(IPAddress.Parse(Cfg.Comm.If1.McastGroup),
                                                  IPAddress.Parse(Cfg.Comm.If1.Ip));
                Listener1.Base.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 16);
                Listener1.NewDataEvent += OnDataReceived;
                Listener1.BeginReceive();

                Listener2 = new UdpSocket(Lan2Listen);
                /** Para seleccionar correctamente la Interfaz de salida de las tramas MCAST */
                //Listener2.Base.MulticastLoopback = false;
                Listener2.Base.JoinMulticastGroup(IPAddress.Parse(Cfg.Comm.If2.McastGroup),
                                                  IPAddress.Parse(Cfg.Comm.If2.Ip));
                Listener2.Base.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 16);
                Listener2.NewDataEvent += OnDataReceived;
                Listener2.BeginReceive();

                TickTimer           = new Timer(TimeSpan.FromSeconds(1).TotalMilliseconds);
                TickTimer.AutoReset = false;
                TickTimer.Elapsed  += OnTick;
                TickTimer.Enabled   = true;

                SendInitMsg();
                Logger.Info <PsiManager>($"PsiManager. Waiting for SCV Activity on {Cfg.Comm.If1.Ip}:{Cfg.Comm.ListenPort} / {Cfg.Comm.If2.Ip}:{Cfg.Comm.ListenPort}");
                Logger.Info <PsiManager>($"PsiManager. Sectores {Cfg.Sectorization.Sectors} Posiciones {Cfg.Sectorization.Positions}");
                PS.Set(ProcessStates.Running);
            }
            catch (Exception x)
            {
                Logger.Exception <PsiManager>(x, $"On PSI");
                Dispose();
                PS.SignalFatal <PsiManager>($"Excepcion en el Arranque => {x}", History());
            }
        }
Exemplo n.º 6
0
        public void RoutingMcastTest()
        {
            // Programar el LISTEN de LAN1 en el simulador.
            var Listener1 = new UdpSocket("10.12.90.1", 19205);

            Listener1.Base.JoinMulticastGroup(IPAddress.Parse("225.12.101.1"), IPAddress.Parse("10.12.90.1"));
            Listener1.NewDataEvent += (s, d) =>
            {
                Debug.WriteLine("Trama Recibida en LISTENER 1");
            };
            Listener1.BeginReceive();
            // Programar el LISTEN de LAN2 en el simulador.
            var Listener2 = new UdpSocket("10.20.91.1", 19205);

            Listener2.Base.JoinMulticastGroup(IPAddress.Parse("225.212.101.1"), IPAddress.Parse("10.20.91.1"));
            Listener2.NewDataEvent += (s, d) =>
            {
                Debug.WriteLine("Trama Recibida en LISTENER 2");
            };
            Listener2.BeginReceive();

            // Envio de la trama por el código del SCV.
            var ScvSender = new UdpSocket("10.12.90.1", 15001);

            ScvSender.Base.MulticastLoopback = false;
            ScvSender.Base.JoinMulticastGroup(IPAddress.Parse("225.12.101.1"), IPAddress.Parse("10.12.90.1"));
            ScvSender.Base.JoinMulticastGroup(IPAddress.Parse("225.212.101.1"), IPAddress.Parse("10.12.90.1"));
            IPEndPoint to1 = new IPEndPoint(IPAddress.Parse("225.12.101.1"), 19205);
            IPEndPoint to2 = new IPEndPoint(IPAddress.Parse("225.212.101.1"), 19205);

            Task.Delay(1000).Wait();
            ScvSender.Send(to1, new byte[] { 1, 2, 3 });
            Task.Delay(1000).Wait();
            ScvSender.Send(to2, new byte[] { 1, 2, 3 });

            Task.Delay(1000).Wait();
        }
Exemplo n.º 7
0
        public override void Start()
        {
            Logger.Info <ScvManager>($"Starting ScvManager for {Id}...");
            try
            {
                Listener1 = new UdpSocket(Lan1Listen);
                /** Para seleccionar correctamente la Interfaz de salida de las tramas MCAST */
                Listener1.Base.MulticastLoopback = false;
                Listener1.Base.JoinMulticastGroup(IPAddress.Parse(Cfg.Comm.If1.McastGroup),
                                                  IPAddress.Parse(Cfg.Comm.If1.Ip));
                /** 20180731. Para poder pasar por una red de ROUTERS */
                Listener1.Base.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 16);
                Listener1.NewDataEvent += OnDataReceived;
                if (Version == 0)
                {
                    Listener2 = new UdpSocket(Lan2Listen);
                    /** Para seleccionar correctamente la Interfaz de salida de las tramas MCAST */
                    Listener2.Base.MulticastLoopback = false;
                    Listener2.Base.JoinMulticastGroup(IPAddress.Parse(Cfg.Comm.If2.McastGroup),
                                                      IPAddress.Parse(Cfg.Comm.If2.Ip));
                    /** 20180731. Para poder pasar por una red de ROUTERS */
                    Listener2.Base.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 16);
                    Listener2.NewDataEvent += OnDataReceived;
                }
                else
                {
                    Listener2 = null;
                    Listener1.Base.JoinMulticastGroup(IPAddress.Parse(Cfg.Comm.If2.McastGroup),
                                                      IPAddress.Parse(Cfg.Comm.If1.Ip));
                }

                Listener1.BeginReceive();
                if (Version == 0)
                {
                    Listener2.BeginReceive();
                }

                TickTimer           = new Timer(TimeSpan.FromSeconds(1).TotalMilliseconds);
                TickTimer.AutoReset = false;
                TickTimer.Elapsed  += OnTick;
                TickTimer.Enabled   = true;

                GlobalState = SactaState.WaitingSactaActivity;

                if (Version == 0)
                {
                    Logger.Info <ScvManager>($"ScvManager for {Id}. Waiting for Sacta Activity on {Cfg.Comm.If1.Ip}:{Cfg.Comm.ListenPort}, {Cfg.Comm.If2.Ip}:{Cfg.Comm.ListenPort} ...");
                }
                else
                {
                    Logger.Info <ScvManager>($"ScvManager for {Id}. Waiting for Sacta Activity on {Cfg.Comm.If1.Ip}:{Cfg.Comm.ListenPort} ...");
                }
                Logger.Info <PsiManager>($"ScvManager for {Id}. Sectores {Cfg.Sectorization.Sectors} Posiciones {Cfg.Sectorization.Positions}");
                PS.Set(ProcessStates.Running);
            }
            catch (Exception x)
            {
                Logger.Exception <ScvManager>(x, $"On {Cfg.Id}");
                Dispose();
                PS.SignalFatal <ScvManager>($"Excepcion en el Arranque {x}", History());
            }
        }
Exemplo n.º 8
0
        public void TestMethod1()
        {
            var Listener = new UdpSocket("127.0.0.1", 9000);

            Listener.NewDataEvent += (s, dg) =>
            {
                try
                {
                    if (dg.Data[0] == '{')
                    {
                        Debug.WriteLine("Llega un JSON...");
                    }
                    else
                    {
                        BinaryFormatter bf  = new BinaryFormatter();
                        MemoryStream    ms  = new MemoryStream(dg.Data);
                        object          msg = bf.Deserialize(ms);

                        if (msg is MsgType type)
                        {
                            switch (type)
                            {
                            case MsgType.Activate:
                                Debug.WriteLine("Activate(true)");
                                break;

                            case MsgType.Deactivate:
                                Debug.WriteLine("Deactivate()");
                                break;

                            case MsgType.GetState:
                                Debug.WriteLine("SendState()");
                                break;

                            default:
                                Debug.WriteLine("Error 1");
                                break;
                            }
                        }
                        else if (msg is NodeInfo)
                        {
                            Debug.WriteLine("NodeInfo...");
                        }
                        else
                        {
                            throw new Exception("Mensaje Desconocido");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"Excepcion: {ex.Message}");
                }
            };
            Listener.BeginReceive();

            var Sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            var EndpTo = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9000);

            using (MemoryStream ms = new MemoryStream())
                using (MemoryStream ms1 = new MemoryStream())
                {
                    var             _State = new ClusterState();
                    BinaryFormatter bf     = new BinaryFormatter();

                    try
                    {
                        bf.Serialize(ms, _State.LocalNode);
                        Sender.SendTo(ms.ToArray(), EndpTo);
                        Task.Delay(1000).Wait();

                        bf.Serialize(ms1, MsgType.Activate);
                        Sender.SendTo(ms1.ToArray(), EndpTo);
                    }
                    catch (Exception ex)
                    {
                    }
                }

            Task.Delay(1000).Wait();

            var data1 = System.Text.Encoding.ASCII.GetBytes("{ \"res\": \"ok\"}");

            Sender.SendTo(data1, EndpTo);

            Task.Delay(1000).Wait();
        }
Exemplo n.º 9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ToStart(object sender, ElapsedEventArgs e)
        {
#if _VERSION_00_
            try
            {
                _Comm = new UdpSocket(_Settings.Ip, _Settings.Port);
                _Comm.NewDataEvent += OnNewData;
            }
            catch (System.Net.Sockets.SocketException ex)
            {
                _Logger.DebugException(ex.Message, ex);
            }

            _State.LocalNode.ValidAdapters = GetAdaptersState();
            if (_State.LocalNode.ValidAdapters > 0)
            {
                if (!ExistClusterAddresses(false))
                {
                    _State.LocalNode.SetState(NodeState.Activating, Resources.LocalActivateAsk);
                }
                else
                {
                    _State.LocalNode.SetState(NodeState.NoActive, Resources.FoundClusterIps);
                }
            }
            else
            {
                _State.LocalNode.SetState(NodeState.NoActive, Resources.DeactivateByNotAdapters);
            }

            if (_Comm != null)
            {
                _Comm.BeginReceive();
            }

            _PeriodicTasks.Enabled = true;
#else
            // 20170925. No arranca hasta que no consigue que se active la LAN Interna.
            // Se considera que hay red si se completa favorablemente toda la inicializacion ...

            // 20171019. Este parte del timer se ejecutará periodicamente hasta que se inicie la red interna...
            LogHelper.Log(LogLevel.Info, "ToStart TICK");
            try
            {
                _Comm = new UdpSocket(_Settings.Ip, _Settings.Port);
                _Comm.NewDataEvent += OnNewData;
                _Comm.BeginReceive();
                LogHelper.Log(LogLevel.Info, "Red Interna Disponible...");
            }
            catch (Exception x)
            {
                LogHelper.Log(LogLevel.Error, x.Message);
                // Rearranco este timer...
                _ToStart.Enabled = true;
            }

            try
            {
                // 20171019. Esta parte del timer solo se ejecuta la primera vez...Si no hay errores internos...
                if (_State.LocalNode.State == NodeState.NoValid)
                {
                    // 20171019. Fuerzo el borrado de la IP virtual...
                    ForceDeleteVirtualAddress();
                    /////////////////////////////////////////////////
                    _State.LocalNode.ValidAdapters = GetAdaptersState();
                    if (_State.LocalNode.ValidAdapters > 0)
                    {
                        if (!ExistClusterAddresses(false))
                        {
                            _State.LocalNode.SetState(NodeState.Activating, Resources.LocalActivateAsk);
                        }
                        else
                        {
                            _State.LocalNode.SetState(NodeState.NoActive, Resources.FoundClusterIps);
                        }
                    }
                    else
                    {
                        _State.LocalNode.SetState(NodeState.NoActive, Resources.DeactivateByNotAdapters);
                    }

                    _PeriodicTasks.Enabled = true;
                }
            }
            catch (Exception x)
            {
                LogHelper.Log(LogLevel.Error, x.Message);

                // Rearranco este timer...
                _ToStart.Enabled = true;
            }
#endif
        }