示例#1
0
        public WorkerDestination()
        {
            try
            {
                WorkerLogger.Debug("Start Initializing ZMQ Consumer.");
                ZMQSubscriber = new ZMQSubscriber();

                Dictionary <string, List <string> > DicZMQTopic = new Dictionary <string, List <string> >();

                foreach (ZMQPublisherList item in IOHelper.AgentConfig.PublisherList)
                {
                    DicZMQTopic.Add(item.ZMQAddress, item.TopicList);
                    // WorkerLogger.Control(CommonMessages.ZMQTopicList(item.ZMQAddress, string.Join(",", item.TopicList.ToArray())));
                }
                string strError = string.Empty;
                ZMQSubscriber.InitialiseMultipleSubscriber(DicZMQTopic, out strError, 100, 1000, IOHelper.AgentConfig.ZMQSecurity);

                if (!string.IsNullOrEmpty(strError))
                {
                    WorkerLogger.Error(CommonMessages.InitializeZMQConnectionFailed(strError));
                }
                else
                {
                    WorkerLogger.Control(CommonMessages.InitializeZMQConnectionSucc);
                }

                //     LoadMappingConfig();
            }
            catch (Exception Ex0)
            {
                //WorkerLogger.Exception(Ex0);
                WorkerLogger.TraceLog(MessageType.Error, Ex0.Message);
            }
        }
示例#2
0
        public static async Task PingTcpPort(Tag tag)
        {
            try
            {
                var client = new TcpClient();
                await client.ConnectAsync(tag.Ip_Address, tag.Port);

                tag.is_open = true;
            }
            catch (SocketException ex)
            {
                switch (ex.ErrorCode)
                {
                case 10054:
                    WorkerLogger.TraceLog(MessageType.Debug, tag.PortDescription);
                    tag.PortDescription = tag.Ip_Address + ":" + tag.Port + ":: " + "is closed or connection blocked by firewall";
                    break;

                case 10048:
                    tag.PortDescription = "Port " + tag.Port + ":: " + "Address already in use";
                    WorkerLogger.TraceLog(MessageType.Debug, tag.PortDescription);
                    break;

                case 10051:
                    tag.PortDescription = "Port " + tag.Port + "::" + "Network is unreachable";
                    WorkerLogger.TraceLog(MessageType.Debug, tag.PortDescription);
                    break;

                case 10050:
                    tag.PortDescription = tag.Ip_Address + ":" + tag.Port + "::" + "Network is down";
                    WorkerLogger.TraceLog(MessageType.Debug, tag.PortDescription);
                    break;

                case 10056:
                    tag.PortDescription = tag.Ip_Address + ":" + tag.Port + "::" + "Socket is already connected";
                    WorkerLogger.TraceLog(MessageType.Debug, tag.PortDescription);
                    break;

                case 10060:
                    tag.PortDescription = tag.Ip_Address + ":" + tag.Port + "::" + "Connection timed out, the connection is maybe blocked by the firewall";
                    WorkerLogger.TraceLog(MessageType.Debug, tag.PortDescription);
                    break;

                case 10061:
                    tag.PortDescription = tag.Ip_Address + ":" + tag.Port + ":" + "Connection refused::No server application is running";
                    WorkerLogger.TraceLog(MessageType.Debug, tag.PortDescription);
                    break;

                case 10064:
                    tag.PortDescription = tag.Ip_Address + ":" + tag.Port + "::" + "Host is down";
                    WorkerLogger.TraceLog(MessageType.Debug, tag.PortDescription);
                    break;

                default:
                    tag.PortDescription = tag.Ip_Address + ":" + tag.Port + "::" + "CodeError: " + ex.ErrorCode + ":: " + ex.Message;
                    WorkerLogger.TraceLog(MessageType.Debug, tag.PortDescription);
                    break;
                }
            }
        }
示例#3
0
        private void ScheduledTask_OnException(ScheduledTask task, Exception exception)
        {
            string message = $"An error occurred while executing {task.Name}";

            WorkerLogger.Error(message, exception);
            Store($"{message}, Exception = {exception.Message}");

            OnTaskException?.Invoke(this, new TaskExceptionEventArgs(task, exception));
        }
 public Worker(ILogger <Worker> logger, ServiceSettings serviceSettings,
               FileReader fileReader, Repository repository, FileHandler fileHandler, WorkerLogger workerLogger)
 {
     _logger          = logger;
     _serviceSettings = serviceSettings;
     _fileReader      = fileReader;
     _repository      = repository;
     _fileHandler     = fileHandler;
     _workerLogger    = workerLogger;
 }
示例#5
0
 /// <summary>
 /// Create new IMAPConnection object specifying the IMAPConfig to use
 /// </summary>
 public IMAPConnection(IMAPConfig config, WorkerLogger logger)
 {
     _config     = config;
     _useSSL     = _config.UseSSL;
     _serverHost = _config.Host;
     _serverPort = _useSSL ? IMAP_DEFAULT_SSL_PORT : IMAP_DEFAULT_PORT;
     _username   = _config.UserName;
     _password   = _config.Password;
     _logger     = logger;
 }
示例#6
0
 /// <summary>
 ///
 /// </summary>
 public IMAPConnectionWorker(IMAPAsyncClient client, int id)
 {
     _client            = client;
     _workerID          = id;
     _logger            = new WorkerLogger(id);
     _config            = _client.Config;
     _conn              = new IMAPConnection(_config, _logger);
     _shuttingDown      = false;
     _loggedIn          = false;
     _processingRequest = false;
 }
示例#7
0
        //Check Host and/or port status
        public void Connection()
        {
            try
            {
                //Check tcp ports sync
                Thread ConnectPortsTcpSyncThread = new Thread(ConnectPortTcpSync);
                ConnectPortsTcpSyncThread.Name         = "Thread To Connect To Tcp port Synchronously";
                ConnectPortsTcpSyncThread.IsBackground = true;
                ConnectPortsTcpSyncThread.Start();

                //Check tcp ports async
                Thread ConnectPortsTcpASyncThread = new Thread(ConnectPortTcpASync);
                ConnectPortsTcpASyncThread.Name         = "Thread To Connect To Synchronously";
                ConnectPortsTcpASyncThread.IsBackground = true;
                ConnectPortsTcpASyncThread.Start();
                //check udp ports async
                Thread ConnectPortsUdpSyncThread = new Thread(ConnectPortUdpSync);
                ConnectPortsUdpSyncThread.Name         = "Thread To Connect To Device";
                ConnectPortsUdpSyncThread.IsBackground = true;
                ConnectPortsUdpSyncThread.Start();

                //check udp ports async
                Thread ConnectPortsUdpASyncThread = new Thread(ConnectPortUdpASync);
                ConnectPortsUdpASyncThread.Name         = "Thread To Connect To Device";
                ConnectPortsUdpASyncThread.IsBackground = true;
                ConnectPortsUdpASyncThread.Start();

                //To Check Device Status
                Thread SynchroneHostStatusThread = new Thread(CheckSyncHostStatus);
                SynchroneHostStatusThread.Name         = "Thread To Check Host Status Synchronously";
                SynchroneHostStatusThread.IsBackground = true;
                SynchroneHostStatusThread.Priority     = ThreadPriority.BelowNormal;
                SynchroneHostStatusThread.Start();
                //To Check Device Status
                Thread ASynchroneHostStatusThread = new Thread(CheckASyncHostStatus);
                ASynchroneHostStatusThread.Name         = "Thread To Check Host Status ASynchronously";
                ASynchroneHostStatusThread.IsBackground = true;
                ASynchroneHostStatusThread.Priority     = ThreadPriority.BelowNormal;
                ASynchroneHostStatusThread.Start();



                //  <<<=======================================  Start publishing Data To SIOTH  =======================================>>>
                Thread PublisherThread = new Thread(PublishDADataToSIOTHBUS);
                PublisherThread.Name         = "Thread To publish data to SIOTH";
                PublisherThread.IsBackground = true;
                PublisherThread.Priority     = ThreadPriority.BelowNormal;
                PublisherThread.Start();
            }
            catch (Exception Ex)
            {
                WorkerLogger.TraceLog(MessageType.Error, Ex.Message);
            }
        }
示例#8
0
 public WorkerSource()
 {
     try
     {
         string strError = string.Empty;
         zmqPublisher = new ZMQPublisher();
         zmqPublisher.InitialisePublisher(IOHelper.AgentConfig.ZMQAddress, out strError, 1000, IOHelper.AgentConfig.ZMQSecurity);
     }
     catch (Exception ex)
     {
         WorkerLogger.TraceLog(MessageType.Error, ex.Message);
     }
 }
示例#9
0
 public void CheckASyncHostStatus()
 {
     try
     {
         Parallel.ForEach(ASynchroneHost.Keys, item =>
         {
             PingAsyncHosts(ASynchroneHost[item], item.ToString(), Convert.ToInt32(item)).Wait();
         });
     }
     catch (Exception ex)
     {
         WorkerLogger.TraceLog(MessageType.Error, ex.Message);
     }
 }
示例#10
0
        public virtual bool Stop()
        {
            try
            {
                ScheduledTask.StopSchedule();

                OnStopped?.Invoke(this, new WorkerStoppedEventArgs());

                Store($"{Name} has stopped at {DateTime.Now}");

                return(true);
            }
            catch (Exception exception)
            {
                WorkerLogger.Error("", exception);
                return(false);
            }
        }
        private void DoSomething()
        {
            string message = string.Format("{0} Hello {1}", Name, DateTime.Now);

            for (int i = 0; i < 1000000; i++)
            {
                var tmp = i / 100000;

                if (i % 100000 == 0)
                {
                    Progress(new ProgressMessage {
                        Message = message, Percent = 10m * tmp
                    });
                    WorkerLogger.Info(message);
                }
            }

            Console.WriteLine(message);
        }
 private void Worker_Started(object sender, WorkerStartedEventArgs e)
 {
     try
     {
         IPubSubResult result = PubSubClient.Publish(new PubSubMessage
         {
             Event   = "task:onstarted",
             Channel = "panteon",
             Payload = new
             {
                 TaskName = Name
             }
         });
         Console.WriteLine(result.Body);
     }
     catch (Exception exception)
     {
         WorkerLogger.Error($"An error occurred while informing about [{Name}] starting operation.", exception);
     }
 }
示例#13
0
        public void PublishDADataToSIOTHBUS(object obj)
        {
            WorkerLogger.TraceLog(MessageType.Control, "Starting to publish data .......");
            PublisherClass PItem;
            string         strError = string.Empty;

            while (true)
            {
                while (Publisherqueue.TryTake(out PItem))
                {
                    zmqPublisher.PublishData(JsonConvert.SerializeObject(PItem), IOHelper.AgentConfig.Topic, out strError);

                    if (!string.IsNullOrEmpty(strError))
                    {
                        WorkerLogger.TraceLog(MessageType.Error, "Error when publishing data: " + strError);
                    }
                }
                Thread.Sleep(IOHelper.AgentConfig.PublishRate);
            }
        }
示例#14
0
        public static void PingSynchHost(Tag tag, PublisherClass itemList)
        {
            Ping        pingSender = new Ping();
            PingOptions options    = new PingOptions();

            // Use the default Ttl value which is 128,
            // but change the fragmentation behavior.
            options.DontFragment = tag.DontFragment;

            // Create a buffer of 32 bytes of data to be transmitted.

            byte[] buffer = Encoding.ASCII.GetBytes(tag.Data);
            try
            {
                Item     element   = new Item();
                DateTime localDate = DateTime.Now;
                element.TimeStamp = localDate;
                element.TagName   = tag.TagKey;
                PingReply reply = pingSender.Send(tag.Ip_Address, tag.Connection_Timeout, buffer, options);
                if (reply.Status == IPStatus.Success)
                {
                    WorkerLogger.TraceLog(MessageType.Debug, tag.Ip_Address + " is connected");
                    element.is_open     = true;
                    tag.is_open         = true;
                    element.Description = "Host with ip: " + tag.Ip_Address + "is open";
                }
                else
                {
                    WorkerLogger.TraceLog(MessageType.Debug, tag.Ip_Address + " is not connected");
                    element.is_open     = false;
                    tag.is_open         = false;
                    element.Description = "Host with ip: " + tag.Ip_Address + "is down or cannot be reachable";
                }
                itemList.Payload.Add(element);
            }
            catch (Exception ex)
            {
                WorkerLogger.TraceLog(MessageType.Error, ex.Message);
            }
        }
示例#15
0
        /// <summary>This method load the devices configuration from the config file into a dictionary that contains all the information needed to read and write data


        /// <summary> this method Check whether the Hosts are connected or not///<example>
        /// For example:///<code>/// ConnectToBACnetDevices();///results///Device BasicServer is not connected, Device RoomSimulator is connected
        /// ConnectToBACnetDevices():Check the connectivity for the first time
        ///this method check periodicaly the connectivity of multiple hosts
        public void CheckSyncHostStatus()
        {
            try
            {
                Parallel.ForEach(SynchroneHost.Keys, item =>
                {
                    while (true)
                    {
                        PublisherClass itemList = new PublisherClass();
                        foreach (Tag tag in SynchroneHost[item])
                        {
                            WorkerManager.PingSynchHost(tag, itemList);
                        }
                        itemList.SchemaId = IOHelper.AgentConfig.Agent_SchemaID;
                        Publisherqueue.Add(itemList);
                        Thread.Sleep(item);
                    }
                });
            }
            catch (Exception ex)
            {
                WorkerLogger.TraceLog(MessageType.Error, ex.Message);
            }
        }
示例#16
0
        public virtual bool Run(Action <ScheduledTask, DateTimeOffset> actionToRun, bool autoRun = true)
        {
            try
            {
                string message = $"{Name} is started.";
                WorkerLogger.Info(message);
                Store(message);

                ScheduledTask = _schtick.AddAsyncTask(Name, WorkerSettings.SchedulePattern,
                                                      TaskWrapper.WrapAsync(async(task, timeIntendedToRun) =>
                                                                            await Task.Run(() =>
                {
                    Store($"{Name} - execution has started at {DateTime.Now}");
                    OnTaskEnter?.Invoke(this, new WorkerEventArgs());

                    actionToRun?.Invoke(task, timeIntendedToRun);

                    OnTaskExit?.Invoke(this, new WorkerEventArgs());
                    Store($"{Name} - execution has completed at {DateTime.Now}");
                }).ConfigureAwait(false))
                                                      , autoRun);

                ScheduledTask.OnException += ScheduledTask_OnException;

                OnStarted?.Invoke(this, new WorkerStartedEventArgs());

                return(true);
            }
            catch (Exception exception)
            {
                string details = $"An error occurrred while executing {Name}";
                WorkerLogger.Error(details, exception);
                Store($"{details}, Exception = {exception.Message}");
                return(false);
            }
        }
示例#17
0
 private static bool InitilizeLog(out string error)
 {
     WorkerFilesManager.InitializeIniFiles();
     return(WorkerLogger.InitializeLogger(AgentCommonMessages.serviceProcessName, out error, Process.GetCurrentProcess().ProcessName));
 }
示例#18
0
        public static async Task PingUdpPort(Tag tag, Byte[] sendBytes)
        {
            try
            {
                UdpClient udpClient = new UdpClient(tag.Port);
                Socket    uSocket   = udpClient.Client;
                uSocket.ReceiveTimeout = 5000;
                udpClient.Connect(tag.Ip_Address, tag.Port);
                udpClient.Send(sendBytes, sendBytes.Length);
                IPEndPoint RemoteIpEndPoint = tag.RemoteIpEndPoint;
                Byte[]     receiveBytes     = udpClient.Receive(ref RemoteIpEndPoint);
                tag.is_open         = true;
                tag.PortDescription = tag.Ip_Address + ":" + tag.Port + " is open";
                udpClient.Close();
            }
            catch (SocketException ex)
            {
                tag.is_open = false;

                switch (ex.ErrorCode)
                {
                case 10054:
                    WorkerLogger.TraceLog(MessageType.Debug, tag.PortDescription);
                    tag.PortDescription = tag.Ip_Address + ":" + tag.Port + ":: " + "is closed or connection blocked by firewall";
                    break;

                case 10048:
                    tag.PortDescription = "Port " + tag.Port + ":: " + "Address already in use";
                    WorkerLogger.TraceLog(MessageType.Debug, tag.PortDescription);
                    break;

                case 10051:
                    tag.PortDescription = "Port " + tag.Port + "::" + "Network is unreachable";
                    WorkerLogger.TraceLog(MessageType.Debug, tag.PortDescription);
                    break;

                case 10050:
                    tag.PortDescription = tag.Ip_Address + ":" + tag.Port + "::" + "Network is down";
                    WorkerLogger.TraceLog(MessageType.Debug, tag.PortDescription);
                    break;

                case 10056:
                    tag.PortDescription = tag.Ip_Address + ":" + tag.Port + "::" + "Socket is already connected";
                    WorkerLogger.TraceLog(MessageType.Debug, tag.PortDescription);
                    break;

                case 10060:
                    tag.PortDescription = tag.Ip_Address + ":" + tag.Port + "::" + "Connection timed out, the connection is maybe blocked by the firewall";
                    WorkerLogger.TraceLog(MessageType.Debug, tag.PortDescription);
                    break;

                case 10061:
                    tag.PortDescription = tag.Ip_Address + ":" + tag.Port + ":" + "Connection refused::No server application is running";
                    WorkerLogger.TraceLog(MessageType.Debug, tag.PortDescription);
                    break;

                case 10064:
                    tag.PortDescription = tag.Ip_Address + ":" + tag.Port + "::" + "Host is down";
                    WorkerLogger.TraceLog(MessageType.Debug, tag.PortDescription);
                    break;

                default:
                    tag.PortDescription = tag.Ip_Address + ":" + tag.Port + "::" + "CodeError: " + ex.ErrorCode + ":: " + ex.Message;
                    WorkerLogger.TraceLog(MessageType.Debug, tag.PortDescription);
                    break;
                }
            }
        }
示例#19
0
        private void WriteDataToDestination(object obj)
        {
            ////To Check Device Status
            //  Thread StatusThread = new Thread(CheckSyncHostStatus);
            //  StatusThread.Name = "Thread To Check Device Status";
            //  StatusThread.IsBackground = true;
            //  StatusThread.Start();

            try
            {
                string ConsumeErrorMsg = string.Empty;
                string error;
                string transformerSchemaId = "{\"SchemaId\" : \"#valueof($.SchemaId)\"}";
                //string item;
                Dictionary <string, string> SchemaToUse = new Dictionary <string, string>();



                while (true)
                {
                    string result = ZMQSubscriber.ReceiveDataFromSubscriberList(out error);
                    Console.WriteLine(result);
                    if (!string.IsNullOrEmpty(result) && string.IsNullOrEmpty(error))
                    {
                        string resSchemaId     = JsonTransformer.Transform(transformerSchemaId, result);
                        var    payloadSchemaId = Newtonsoft.Json.JsonConvert.DeserializeObject <Payload>(resSchemaId);
                        if (IOHelper.AgentConfig.Mapping.FieldsMappings.ContainsKey(payloadSchemaId.SchemaId))
                        {
                            IOHelper.AgentConfig.Mapping.FieldsMappings.TryGetValue(payloadSchemaId.SchemaId, out SchemaToUse);
                            string transformer = "{\"Iterator\": {    \"#loop($.Payload)\": {    \"TagName\":\"#currentvalueatpath($." + SchemaToUse["TagName"] + ")\",\"Value\":\"#currentvalueatpath($." + SchemaToUse["Value"] + ")\"}}}";

                            string res     = JsonTransformer.Transform(transformer, result);
                            var    payload = Newtonsoft.Json.JsonConvert.DeserializeObject <Payload>(res);

                            var valuesfromPalyload = payload.Iterator.ToList().Select(x =>
                            {
                                var values = x.Values.ToList();
                                return(values);
                            });
                            int PaylodLength = valuesfromPalyload.ToList().Count;


                            valuesfromPalyload.ToList().ForEach(m =>
                            {
                                if (m[0] != null)
                                {
                                    if (IOHelper.AgentConfig.Mapping.TagsMapping.ContainsKey(m[0].ToString()))
                                    {
                                        WriteItem(IOHelper.AgentConfig.Mapping.TagsMapping[m[0].ToString()].ToString(), m[1]);
                                    }
                                }
                            });
                        }
                    }



                    Thread.Sleep(IOHelper.AgentConfig.ConsumerRate);
                }
            }
            catch (Exception Ex0)
            {
                WorkerLogger.TraceLog(MessageType.Error, Ex0.Message);
            }
        }
示例#20
0
        //Ping Hosts asynchronously
        public static async Task PingAsyncHosts(ASynchroneHost addresses, string updateRate, int update)
        {
            while (true)
            {
                //Date before Ping Hosts
                DateTime       DateD    = DateTime.Now;
                PublisherClass itemList = new PublisherClass();
                //
                var pingTasks = addresses.Ip_Address.Select(address =>
                {
                    return(new Ping().SendPingAsync(address.ToString()));
                });

                await Task.WhenAll(pingTasks);


                StringBuilder pingResultBuilder = new StringBuilder();

                foreach (var pingReply in pingTasks)
                {
                    pingResultBuilder.Append(pingReply.Result.Address);
                    Temp_Test_Connection_Async_Host[pingReply.Result.Address.ToString()] = true;
                }

                foreach (var item in addresses.TagList)
                {
                    Item element = new Item();
                    element.Address = item.Ip_Address;
                    element.TagName = item.TagKey;
                    DateTime localDate = DateTime.Now;
                    element.TimeStamp = localDate;


                    if (Temp_Test_Connection_Async_Host[item.Ip_Address] == true)
                    {
                        WorkerLogger.TraceLog(MessageType.Debug, " Host with address: " + item + " is connected");
                        element.is_open     = true;
                        item.is_open        = true;
                        element.Description = "Host with ip: " + item.Ip_Address + "is open";
                    }
                    else
                    {
                        WorkerLogger.TraceLog(MessageType.Debug, " Host with address: " + item + " is not connected");
                        element.is_open     = false;
                        item.is_open        = false;
                        element.Description = "Host with ip: " + item.Ip_Address + "is down or cannot be reachable";
                    }
                    itemList.Payload.Add(element);
                }
                Publisherqueue.Add(itemList);



                Clear_Test_Connection();
                //Date after test connection
                DateTime DateF = DateTime.Now;
                //We have to subtract the time of traitement from the updateRate
                //If the traitement time was higher than the updateRate we had to excute the next ping without waiting
                if (update - (DateD.Second - DateF.Second) > 0)
                {
                    await Task.Delay(TimeSpan.FromSeconds(update - (DateD.Second - DateF.Second)));
                }
                //we have to set the test_connection values to false
                Clear_Test_Connection();
            }
        }
示例#21
0
 public static void LoadConfig()
 {
     try
     {
         foreach (Tag tag in IOHelper.AgentConfig.dataExtractionProperties.DataConfig.DataConfiguration.Tags)
         {
             if (tag.OnlyHostPing == true && tag.Synchronous == true)
             {
                 tag.TagKey = tag.TagName + "/" + tag.Ip_Address;
                 if (SynchroneHost.ContainsKey(tag.UpdateRate) == false)
                 {
                     SynchroneHost.Add(tag.UpdateRate, new List <Tag>());
                     SynchroneHost[tag.UpdateRate].Add(tag);
                 }
                 else
                 {
                     SynchroneHost[tag.UpdateRate].Add(tag);
                 }
             }
             else if (tag.OnlyHostPing == false && tag.Synchronous == true && tag.PortType == "TCP")
             {
                 tag.TagKey = tag.TagKey = tag.TagName + "/" + tag.Ip_Address + ":" + tag.Port;
                 if (SynchronePortTcp.ContainsKey(tag.UpdateRate) == false)
                 {
                     SynchronePortTcp.Add(tag.UpdateRate, new List <Tag>());
                     SynchronePortTcp[tag.UpdateRate].Add(tag);
                 }
                 else
                 {
                     SynchronePortTcp[tag.UpdateRate].Add(tag);
                 }
             }
             else if (tag.OnlyHostPing == false && tag.Synchronous == false && tag.PortType == "TCP")
             {
                 tag.TagKey = tag.TagKey = tag.TagName + "/" + tag.Ip_Address + ":" + tag.Port;
                 if (ASynchronePortTcp.ContainsKey(tag.UpdateRate) == false)
                 {
                     ASynchronePortTcp.Add(tag.UpdateRate, new List <Tag>());
                     ASynchronePortTcp[tag.UpdateRate].Add(tag);
                 }
                 else
                 {
                     ASynchronePortTcp[tag.UpdateRate].Add(tag);
                 }
             }
             else if (tag.OnlyHostPing == false && tag.Synchronous == true && tag.PortType == "UDP")
             {
                 tag.TagKey = tag.TagKey = tag.TagName + "/" + tag.Ip_Address + ":" + tag.Port;
                 IPAddress address = IPAddress.Parse(tag.Ip_Address);
                 tag.RemoteIpEndPoint = new IPEndPoint(address, tag.Port);
                 if (SynchronePortUdp.ContainsKey(tag.UpdateRate) == false)
                 {
                     SynchronePortUdp.Add(tag.UpdateRate, new List <Tag>());
                     SynchronePortUdp[tag.UpdateRate].Add(tag);
                 }
                 else
                 {
                     SynchronePortUdp[tag.UpdateRate].Add(tag);
                 }
             }
             else if (tag.OnlyHostPing == false && tag.Synchronous == false && tag.PortType == "UDP")
             {
                 tag.TagKey = tag.TagName + "/" + tag.Ip_Address + ":" + tag.Port;
                 IPAddress address = IPAddress.Parse(tag.Ip_Address);
                 tag.RemoteIpEndPoint = new IPEndPoint(address, tag.Port);
                 if (ASynchronePortUdp.ContainsKey(tag.UpdateRate) == false)
                 {
                     ASynchronePortUdp.Add(tag.UpdateRate, new List <Tag>());
                     ASynchronePortUdp[tag.UpdateRate].Add(tag);
                 }
                 else
                 {
                     ASynchronePortUdp[tag.UpdateRate].Add(tag);
                 }
             }
             else if (tag.OnlyHostPing == true && tag.Synchronous == false)
             {
                 tag.TagKey = tag.TagName + "/" + tag.Ip_Address;
                 if (ASynchroneHost.ContainsKey(tag.UpdateRate) == false)
                 {
                     List <Tag>    TagList    = new List <Tag>();
                     List <string> Ip_Address = new List <string>();
                     ASynchroneHost.Add(tag.UpdateRate, new ASynchroneHost(TagList, Ip_Address));
                     ASynchroneHost[tag.UpdateRate].Ip_Address.Add(tag.Ip_Address);
                     ASynchroneHost[tag.UpdateRate].TagList.Add(tag);
                 }
                 else
                 {
                     ASynchroneHost[tag.UpdateRate].Ip_Address.Add(tag.Ip_Address);
                     ASynchroneHost[tag.UpdateRate].TagList.Add(tag);
                 }
             }
         }
         Initialiaze_Test_Connection();
         WorkerLogger.TraceLog(MessageType.Control, "Load  dictionnary configuration succeeded");
     }
     catch (Exception ex)
     {
         WorkerLogger.TraceLog(MessageType.Error, ex.Message);
     }
 }
示例#22
0
        public override Task StartAsync(CancellationToken cancellationToken)
        {
            //  <<<=======================================  Initialize Logger  =======================================>>>

            try
            {
                string strError = string.Empty;
                bool   initLog  = InitilizeLog(out string error);
                if (initLog && String.IsNullOrEmpty(strError))
                {
                    WorkerLogger.TraceLog(MessageType.Control, "Initializing INI configuration was successful");
                }
                else
                {
                    WorkerLogger.TraceLog(MessageType.Error, "Initializing INI configuration failed");
                }
                //if (initLog && String.IsNullOrEmpty(error))
                //{
                //    WorkerLogger.Control(AgentCommonMessages.InitializingIniConfigurationSuccessful);
                //}
                //else
                //{
                //    StopAsync(cancellationToken);
                //}
            }
            catch (Exception)
            {
                //Ignored
            }

            //  <<<=======================================  Load Config And Start The Worker  =======================================>>>
            #region <-------------------------------------------Load Configuration----------------------------------->
            // Load Configuration
            string LoadconfigError;
            string strPathFile = $"AgentConfig\\" + Process.GetCurrentProcess().ProcessName + ".json";

            string mappingFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPathFile);

            IOHelper.AgentConfig = IOHelper.LoadConfiguration(mappingFilePath, out LoadconfigError);



            if (!string.IsNullOrEmpty(LoadconfigError))
            {
                WorkerLogger.Error($"{CommonMessages.LoadConfigFileFailed} ,[File Name : {Process.GetCurrentProcess().ProcessName + ".json"}], Reason = [{LoadconfigError}]");
                //StopService
                //StopAsync(cancellationToken);
            }
            else
            {
                WorkerLogger.Control(CommonMessages.LoadConfigFileSucceeded);
            }
            //  <<<=======================================  Loading Config And Start The Worker  =======================================>>>
            WorkerLogger.Control(CommonMessages.LoadInifileConfig);
            IOHelper.LoadIniFileConfiguration();
            //Initialize Publisher
            if (!string.IsNullOrEmpty(IOHelper.AgentConfig.SIOTHLogZMQAddress))
            {
                WorkerLogger.InitializeSIOTHLoggingPublisher(IOHelper.AgentConfig.SIOTHLogZMQAddress, IOHelper.AgentConfig.ZMQSecurity);
            }
            else
            {
                WorkerLogger.Control("SIOTH Log ZMQ Address is Null or Empty, No Message Log will be Published to the SIOTH");
            }
            #endregion


            //Initialize ConfigDictionnary
            WorkerManager.LoadConfig();

            //Initialize ZmqResponse
            try
            {
                String StrError;
                zmqresp.InitialiseZMQResponse(IOHelper.AgentConfig.ZMQListeningOnRequest, out StrError, IOHelper.AgentConfig.ZMQSecurity);
                if (!string.IsNullOrEmpty(StrError))
                {
                    WorkerLogger.TraceLog(MessageType.Error, "Error occurred while Initializing ZMQ response: " + StrError);
                }
            }
            catch (Exception ex)
            {
                WorkerLogger.TraceLog(MessageType.Error, ex.Message);
            }

            WorkerManager.ListenOnRequest(zmqresp);
            try
            {
                if (IOHelper.AgentConfig.Agent_Type.Equals("Source"))
                {
                    WorkerLogger.Control(CommonMessages.IsPublisherWorker);
                    WorkerSource = new WorkerSource();
                    WorkerSource.Connection();
                }
                else if (IOHelper.AgentConfig.Agent_Type.Equals("Destination"))
                {
                    WorkerLogger.Control(CommonMessages.IsConsumerWorker, true);

                    WorkerDestination = new WorkerDestination();

                    Thread WorkerDestinationThread = new Thread(WorkerDestination.StartWritingData)
                    {
                        Name         = "Worker Destination Thread",
                        IsBackground = true
                    };
                    WorkerDestinationThread.Start();
                }
            }
            catch (Exception Ex0)
            {
                // ignore
            }

            // <<<========================================= Load and build address space ==============================>>>
            try
            {
                //WorkerLogger.TraceLog(MessageType.Control, CommonMessages.LoadInifileConfig);
                workerManager = new WorkerManager();
                //workerManager.StartlistingToIncomingRequest();
            }
            catch (Exception Ex0)
            {
                WorkerLogger.Exception(Ex0);
            }

            return(base.StartAsync(cancellationToken));
        }