public void HandleResult(IPublishableMessage message)
 {
     if (message is SingleAnalogValueSCADAMessage singleAnalog)
     {
         Dictionary <long, AnalogModbusData> data = new Dictionary <long, AnalogModbusData>(1)
         {
             { singleAnalog.AnalogModbusData.MeasurementGid, singleAnalog.AnalogModbusData },
         };
         Provider.Instance.MeasurementProvider.UpdateAnalogMeasurement(data);
     }
     else if (message is MultipleAnalogValueSCADAMessage multipleAnalog)
     {
         Provider.Instance.MeasurementProvider.UpdateAnalogMeasurement(multipleAnalog.Data);
     }
     else if (message is SingleDiscreteValueSCADAMessage singleDiscrete)
     {
         Dictionary <long, DiscreteModbusData> data = new Dictionary <long, DiscreteModbusData>(1)
         {
             { singleDiscrete.DiscreteModbusData.MeasurementGid, singleDiscrete.DiscreteModbusData },
         };
         Provider.Instance.MeasurementProvider.UpdateDiscreteMeasurement(data);
     }
     else if (message is MultipleDiscreteValueSCADAMessage multipleDiscrete)
     {
         Provider.Instance.MeasurementProvider.UpdateDiscreteMeasurement(multipleDiscrete.Data);
     }
     else
     {
         logger.LogError($"Message has unsupported type [{message.GetType().ToString()}].");
     }
 }
        public void Notify(IPublishableMessage message)
        {
            if (message is ActiveOutageMessage activeOutage)
            {
                _dispatcher.Connect();

                try
                {
                    _dispatcher.NotifyActiveOutageUpdate(activeOutage);
                }
                catch (Exception)
                {
                    //log error
                    // retry ?
                }
            }
            else if (message is ArchivedOutageMessage archivedOutage)
            {
                _dispatcher.Connect();

                try
                {
                    _dispatcher.NotifyArchiveOutageUpdate(archivedOutage);
                }
                catch (Exception)
                {
                    //log error
                    // retry ?
                }
            }
            else
            {
                //todo: if anything?
            }
        }
        private void TrackPublications(ISubscriberCallback subscriber, string subscriberName)
        {
            Logger.LogInfo($"Thread for tracking publications STARTED. Subscriber [{subscriberName}]");
            bool end           = false;
            bool isMessageNull = false;

            while (!end)
            {
                IPublishableMessage message = Subscribers.Instance.GetNextMessage(subscriber, isMessageNull);

                isMessageNull = message == null;

                if (!isMessageNull)
                {
                    try
                    {
                        subscriber.Notify(message);
                        Logger.LogDebug($"Subscriber [{subscriberName}] notified SUCCESSFULLY.");
                    }
                    catch (Exception)
                    {
                        Logger.LogWarn($"Subscriber [{subscriberName}] is no longer in subscriber list.");
                        Subscribers.Instance.RemoveSubscriber(subscriber);
                        Publications.Instance.RemoveSubscriber(subscriber);
                        end = true;
                    }
                }

                Thread.Sleep(200);
            }

            Logger.LogInfo($"Thread for tracking publications STOPPED. Subscriber [{subscriberName}]");
        }
Esempio n. 4
0
        public void Notify(IPublishableMessage message)
        {
            if (message is OMSModelMessage omsModelMessage)
            {
                TopologyModel = omsModelMessage.OutageTopologyModel; //TODO: Da li su subsciber callback pozivi sinhroni?
                HashSet <long> energizedConsumers = new HashSet <long>();

                foreach (var element in TopologyModel.OutageTopology.Values)
                {
                    if (element.DmsType.Equals(DMSType.ENERGYCONSUMER.ToString()))
                    {
                        if (element.IsActive)
                        {
                            energizedConsumers.Add(element.Id);
                        }
                    }
                }

                ConsumersEnergized?.Invoke(energizedConsumers);
                //foreach pair in queue
                //while queue.COunt > 0
                //queue.Dequee
                while (PotentialOutage.Count > 0)
                {
                    var tuple = PotentialOutage.Dequeue();
                    OutageService.reportOutageService.ReportPotentialOutage(tuple.Item1, tuple.Item2); //TODO: enum (error, noAffectedConsumers, success,...)
                }
            }
            else
            {
                Logger.LogWarn("OutageModel::Notify => UNKNOWN message type. OMSModelMessage expected.");
            }
        }
        public async Task Notify(IPublishableMessage message, string publisherName)
        {
            while (!ReliableDictionariesInitialized)
            {
                await Task.Delay(1000);
            }

            if (!(message is MultipleDiscreteValueSCADAMessage multipleDiscreteValueSCADAMessage))
            {
                string errorMessage = $"SCADA returned wrong value for in SCADAPublication. {typeof(MultipleDiscreteValueSCADAMessage)} excepted.";
                Logger.LogError(errorMessage);
                throw new Exception(errorMessage);
            }

            var enumerableMonitoredPoints = await MonitoredIsolationPoints.GetEnumerableDictionaryAsync();

            var enumerableCommandedValues = await CommandedValues.GetEnumerableDictionaryAsync();

            foreach (long measurementGid in multipleDiscreteValueSCADAMessage.Data.Keys)
            {
                if (!enumerableMonitoredPoints.ContainsKey(measurementGid))
                {
                    continue;
                }

                var scadaDataValue = multipleDiscreteValueSCADAMessage.Data[measurementGid].Value;

                await UpdateMonitoredPoints(measurementGid, enumerableMonitoredPoints, scadaDataValue);

                await UpdateCommandedValues(measurementGid, enumerableCommandedValues, scadaDataValue);
            }
        }
        public void Notify(IPublishableMessage msg)
        {
            Console.WriteLine("Message from PubSub: " + msg);

            if (msg is MultipleAnalogValueSCADAMessage multipleAnalogValue)
            {
                foreach (long gid in multipleAnalogValue.Data.Keys)
                {
                    double            currentValue  = multipleAnalogValue.Data[gid].Value;
                    AlarmType         alarm         = multipleAnalogValue.Data[gid].Alarm;
                    CommandOriginType commandOrigin = multipleAnalogValue.Data[gid].CommandOrigin;
                    Console.WriteLine($"Analog => Gid: 0x{gid:X16} Value: {currentValue}, Alarm: {alarm}, Origin: {commandOrigin}");
                }
            }
            else if (msg is MultipleDiscreteValueSCADAMessage multipleDiscreteValue)
            {
                foreach (long gid in multipleDiscreteValue.Data.Keys)
                {
                    ushort            currentValue  = multipleDiscreteValue.Data[gid].Value;
                    AlarmType         alarm         = multipleDiscreteValue.Data[gid].Alarm;
                    CommandOriginType commandOrigin = multipleDiscreteValue.Data[gid].CommandOrigin;
                    Console.WriteLine($"Discrete => Gid: 0x{gid:X16}, Value: {currentValue}, Alarm: {alarm}, Origin: {commandOrigin}");
                }
            }
            else if (msg is ActiveOutageMessage activeOutage)
            {
                Console.WriteLine($"Active outage id: {activeOutage.OutageId}, affected consumers:{activeOutage.AffectedConsumers}, affected element: 0x{activeOutage.OutageElementGid:x16}");
            }
        }
Esempio n. 7
0
        public void Notify(IPublishableMessage message)
        {
            if (message is MultipleDiscreteValueSCADAMessage multipleDiscreteValueSCADAMessage)
            {
                //UPDATE


                foreach (long gid in multipleDiscreteValueSCADAMessage.Data.Keys)
                {
                    if (optimumIsolationPointsModbusData.ContainsKey(gid))
                    {
                        if (multipleDiscreteValueSCADAMessage.Data[gid].Value != optimumIsolationPointsModbusData[gid].Value)
                        {
                            optimumIsolationPointsModbusData[gid] = multipleDiscreteValueSCADAMessage.Data[gid];
                        }
                    }
                }

                foreach (long gid in multipleDiscreteValueSCADAMessage.Data.Keys)
                {
                    if (defaultIsolationPointsModbusData.ContainsKey(gid))
                    {
                        if (multipleDiscreteValueSCADAMessage.Data[gid].Value != defaultIsolationPointsModbusData[gid].Value)
                        {
                            defaultIsolationPointsModbusData[gid] = multipleDiscreteValueSCADAMessage.Data[gid];
                        }
                    }
                }

                //COMMAND OPEN IF TRUE
                Dictionary <long, DiscreteModbusData> defaultIsolationPointsToBeOpened = new Dictionary <long, DiscreteModbusData>();

                foreach (long gid in defaultIsolationPointsModbusData.Keys)
                {
                    if (defaultToOptimumIsolationPointMap.ContainsKey(gid))
                    {
                        long optimumPointGid = defaultToOptimumIsolationPointMap[gid];

                        if (optimumIsolationPointsModbusData.ContainsKey(optimumPointGid))
                        {
                            ushort optimumIsolationPointValue = optimumIsolationPointsModbusData[optimumPointGid].Value;

                            if (optimumIsolationPointValue == (ushort)DiscreteCommandingType.CLOSE)
                            {
                                defaultIsolationPointsToBeOpened.Add(gid, defaultIsolationPointsModbusData[gid]);
                            }
                        }
                    }
                }

                OpenIsolationPoints(defaultIsolationPointsToBeOpened);
            }
            else
            {
                string errorMessage = "SCADA returned wrong value for in SCADAPublication. MultipleDiscreteValueSCADAMessage excepted.";
                Logger.LogError(errorMessage);
                throw new Exception(errorMessage);
            }
        }
Esempio n. 8
0
        public async Task Notify(IPublishableMessage message, string publisherName)
        {
            while (!ReliableDictionariesInitialized)
            {
                await Task.Delay(1000);
            }

            if (message is EmailToOutageMessage emailMessage)
            {
                if (emailMessage.Gid == 0)
                {
                    Logger.LogError("Invalid email received.");
                    return;
                }

                Logger.LogInformation($"Received call from Energy Consumer with GID: 0x{emailMessage.Gid:X16}.");

                if (!modelResourcesDesc.GetModelCodeFromId(emailMessage.Gid).Equals(ModelCode.ENERGYCONSUMER))
                {
                    Logger.LogWarning($"Received GID 0x{emailMessage.Gid:X16} is not id of energy consumer.");
                    return;
                }

                var topologyProviderClient = TopologyProviderClient.CreateClient();
                var topology = await topologyProviderClient.GetOMSModel();

                if (!topology.GetElementByGid(emailMessage.Gid, out OutageTopologyElement elment))
                {
                    Logger.LogWarning($"Received GID 0x{emailMessage.Gid:X16} is not part of topology.");
                    return;
                }

                if (!timer.Enabled)
                {
                    timer.Start();
                }

                await Calls.SetAsync(emailMessage.Gid, emailMessage.Gid);

                Logger.LogInformation($"Current number of calls is: {await Calls.GetCountAsync()}.");

                if (await Calls.GetCountAsync() >= expectedCalls)
                {
                    await trackingAlgorithm.Start((await Calls.GetDataCopyAsync()).Keys.ToList());

                    await Calls.ClearAsync();

                    timer.Stop();
                }
            }
        }
Esempio n. 9
0
        public void PublishMessage(ISubscriberCallback subscriber, IPublishableMessage message)
        {
            bool   success        = subscribers.TryGetValue(subscriber, out Queue <IPublishableMessage> queueOfMessages);
            string subscriberName = GetSubscriberName(subscriber);

            if (success)
            {
                queueOfMessages.Enqueue(message);
                //TODO: check this log in particular
                Logger.LogDebug($"Published message [{message}] SUCCESSFYLLY enqueued on Subscriber [{subscriberName}]");
            }
            else if (!subscribers.ContainsKey(subscriber))
            {
                Logger.LogWarn($"Subscriber [{subscriberName}, HasCode: {subscriber.GetHashCode()}] does not exist in collection of all subscribers.");
            }
        }
        /// <summary>
        /// Maps the input topology object to a graph object and dispatches it
        /// to a Graph Hub endpoint
        /// </summary>
        /// <param name="message"></param>
        public void Notify(IPublishableMessage message)
        {
            if (message is TopologyForUIMessage topologyMessage)
            {
                OmsGraphViewModel graph = _mapper.Map(topologyMessage.UIModel);

                _dispatcher.Connect();
                try
                {
                    _dispatcher.NotifyGraphUpdate(graph.Nodes, graph.Relations);
                }
                catch (Exception)
                {
                    // retry ?
                }
            }
        }
Esempio n. 11
0
        public IPublishableMessage GetNextMessage(ISubscriberCallback subscriber, bool lastMessageWasNull = false)
        {
            IPublishableMessage message = null;

            bool   success        = subscribers.TryGetValue(subscriber, out Queue <IPublishableMessage> queueOfMessages) && queueOfMessages.Count > 0;
            string subscriberName = GetSubscriberName(subscriber);

            if (success)
            {
                if (queueOfMessages.Count > 0)
                {
                    message = queueOfMessages.Dequeue();
                    Logger.LogDebug($"Published message [{message}] SUCCESSFYLLY dequeued from Subscriber's queue of messages [Subscriber name: '{subscriberName}'].");
                }
            }

            return(message);
        }
Esempio n. 12
0
        public void Notify(IPublishableMessage message)
        {
            if (message is MultipleDiscreteValueSCADAMessage multipleDiscreteValueSCADAMessage)
            {
                long headBreakerID = OutageIsolationAlgorithmParameters.HeadBreakerMeasurementId;
                long recloserID    = OutageIsolationAlgorithmParameters.RecloserMeasurementId;

                Logger.LogDebug("ScadaNotify from outage.");
                if (multipleDiscreteValueSCADAMessage.Data.ContainsKey(headBreakerID))
                {
                    if (multipleDiscreteValueSCADAMessage.Data[headBreakerID].Value == (ushort)DiscreteCommandingType.OPEN)
                    {
                        Logger.LogDebug("ScadaNotify from outage, open command.");
                        OutageIsolationAlgorithmParameters.AutoResetEvent.Set();
                    }
                }
            }
        }
Esempio n. 13
0
        public async Task Notify(IPublishableMessage message, string publisherName)
        {
            Console.WriteLine($"Message received. Message Type: {message.GetType()}, PublisherName: {publisherName}");

            if (message is TopologyForUIMessage uiTopologyMessage)
            {
                string uiTopologyString = $"FirstNode: 0x{uiTopologyMessage.UIModel.FirstNode:X16}{Environment.NewLine}" +
                                          $"Count of Nodes: {uiTopologyMessage.UIModel.Nodes.Count}{Environment.NewLine}" +
                                          $"Count of Relations: {uiTopologyMessage.UIModel.Relations.Count}{Environment.NewLine}";
                Console.WriteLine(uiTopologyString);
            }
            else if (message is OMSModelMessage omsModelMessage)
            {
                string omsModelString = $"FirstNode: 0x{omsModelMessage.OutageTopologyModel.FirstNode:X16}{Environment.NewLine}" +
                                        $"Count of Elements: {omsModelMessage.OutageTopologyModel.OutageTopology.Count}{Environment.NewLine}";
                Console.WriteLine(omsModelString);
            }
        }
        public async Task Notify(IPublishableMessage message, string publisherName)
        {
            if (message  is SingleAnalogValueSCADAMessage singleAnalog)
            {
                var    analogData  = singleAnalog.AnalogModbusData;
                string dataMessage = $"Gid: 0x{analogData.MeasurementGid:X16} | Value: {analogData.Value} | Alarm: {analogData.Alarm} | Origin: {analogData.CommandOrigin}";
                ServiceEventSource.Current.ServiceMessage(this.Context, $"[TestService] Notify message single analog: {dataMessage}");
                Logger.LogDebug(dataMessage);
            }
            else if (message is MultipleAnalogValueSCADAMessage multipleAnalog)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("[TestService] Notify message multiple analog: ");

                foreach (var analogData in multipleAnalog.Data.Values)
                {
                    sb.AppendLine($"Gid: 0x{analogData.MeasurementGid:X16} | Value: {analogData.Value} | Alarm: {analogData.Alarm} | Origin: {analogData.CommandOrigin}");
                }

                ServiceEventSource.Current.ServiceMessage(this.Context, sb.ToString());
                Logger.LogDebug(sb.ToString());
            }
            else if (message is SingleDiscreteValueSCADAMessage singleDiscrete)
            {
                var    discreteData = singleDiscrete.DiscreteModbusData;
                string dataMessage  = $"Gid: 0x{discreteData.MeasurementGid:X16} | Value: {discreteData.Value} | Alarm: {discreteData.Alarm} | Origin: {discreteData.CommandOrigin}";
                ServiceEventSource.Current.ServiceMessage(this.Context, $"[TestService] Notify message single discrete: {dataMessage}");
                Logger.LogDebug(dataMessage);
            }
            else if (message is MultipleDiscreteValueSCADAMessage multipleDiscrete)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("[TestService] Notify message multiple discrete: ");

                foreach (var discreteData in multipleDiscrete.Data.Values)
                {
                    sb.AppendLine($"Gid: 0x{discreteData.MeasurementGid:X16} | Value: {discreteData.Value} | Alarm: {discreteData.Alarm} | Origin: {discreteData.CommandOrigin}");
                }

                ServiceEventSource.Current.ServiceMessage(this.Context, sb.ToString());
                Logger.LogDebug(sb.ToString());
            }
        }
Esempio n. 15
0
        public void Notify(IPublishableMessage message)
        {
            if (message is SingleAnalogValueSCADAMessage)
            {
                SingleAnalogValueSCADAMessage msg = (SingleAnalogValueSCADAMessage)message;
                Console.WriteLine($"Merenje: {msg.AnalogModbusData.MeasurementGid} {msg.AnalogModbusData.Value}");
            }
            else if (message is MultipleAnalogValueSCADAMessage)
            {
                MultipleAnalogValueSCADAMessage msg = (MultipleAnalogValueSCADAMessage)message;
                foreach (var item in msg.Data)
                {
                    Console.WriteLine($"Merenje: {item.Key} {item.Value}");
                }
            }
            TopologyForUIMessage model = message as TopologyForUIMessage;

            PrintUI(model.UIModel);
        }
Esempio n. 16
0
        public async Task Notify(IPublishableMessage message, string publisherName)
        {
            Logger.LogDebug($"{baseLogString} Notify method invoked.");

            if (message is SingleAnalogValueSCADAMessage singleAnalog)
            {
                Dictionary <long, AnalogModbusData> data = new Dictionary <long, AnalogModbusData>(1)
                {
                    { singleAnalog.AnalogModbusData.MeasurementGid, singleAnalog.AnalogModbusData },
                };

                Logger.LogDebug($"{baseLogString} Calling Update analog measurement from measurement provider.");
                var measurementProviderClient = MeasurementProviderClient.CreateClient();
                await measurementProviderClient.UpdateAnalogMeasurement(data);
            }
            else if (message is MultipleAnalogValueSCADAMessage multipleAnalog)
            {
                Logger.LogDebug($"{baseLogString} Calling Update analog measurement from measurement provider.");
                var measurementProviderClient = MeasurementProviderClient.CreateClient();
                await measurementProviderClient.UpdateAnalogMeasurement(multipleAnalog.Data);
            }
            else if (message is SingleDiscreteValueSCADAMessage singleDiscrete)
            {
                Dictionary <long, DiscreteModbusData> data = new Dictionary <long, DiscreteModbusData>(1)
                {
                    { singleDiscrete.DiscreteModbusData.MeasurementGid, singleDiscrete.DiscreteModbusData },
                };

                Logger.LogDebug($"{baseLogString} Calling Update discrete measurement from measurement provider.");
                var measurementProviderClient = MeasurementProviderClient.CreateClient();
                await measurementProviderClient.UpdateDiscreteMeasurement(data);
            }
            else if (message is MultipleDiscreteValueSCADAMessage multipleDiscrete)
            {
                Logger.LogDebug($"{baseLogString} Calling Update discrete measurement from measurement provider.");
                var measurementProviderClient = MeasurementProviderClient.CreateClient();
                await measurementProviderClient.UpdateDiscreteMeasurement(multipleDiscrete.Data);
            }
            else
            {
                Logger.LogError($"{baseLogString} ERROR Message has unsupported type [{message.GetType().ToString()}].");
            }
        }
        public void Notify(IPublishableMessage message)
        {
            if (message is EmailToOutageMessage emailMessage)
            {
                if (emailMessage.Gid == 0)
                {
                    Logger.LogError("Invalid email received.");
                    return;
                }

                Logger.LogInfo($"Received call from Energy Consumer with GID: 0x{emailMessage.Gid:X16}.");

                if (!resourcesDesc.GetModelCodeFromId(emailMessage.Gid).Equals(ModelCode.ENERGYCONSUMER))
                {
                    Logger.LogWarn("Received GID is not id of energy consumer.");
                }
                else if (!outageModel.TopologyModel.OutageTopology.ContainsKey(emailMessage.Gid) && outageModel.TopologyModel.FirstNode != emailMessage.Gid)
                {
                    Logger.LogWarn("Received GID is not part of topology");
                }
                else
                {
                    if (!timer.Enabled) //first message
                    {
                        StartTimer();
                    }

                    calls.Enqueue(emailMessage.Gid);
                    Logger.LogInfo($"Current number of calls is: {calls.Count}.");
                    if (calls.Count >= expectedCalls)
                    {
                        trackingAlgorithm.Start(calls);

                        StopTimer();
                    }
                }
            }
            else
            {
                Logger.LogWarn("Received message is not EmailToOutageMessage.");
            }
        }
Esempio n. 18
0
        public void Notify(IPublishableMessage message)
        {
            if (message is MultipleAnalogValueSCADAMessage analogValuesMessage)
            {
                Dictionary <long, AnalogModbusData> analogModbusData = new Dictionary <long, AnalogModbusData>(analogValuesMessage.Data);

                _dispatcher.Connect();

                try
                {
                    _dispatcher.NotifyScadaDataUpdate(analogModbusData);
                }
                catch (Exception)
                {
                    //log error
                    // retry ?
                }
            }
            else
            {
                //todo: if anything?
            }
        }
 protected Publication(Topic topic, IPublishableMessage message)
 {
     Topic   = topic;
     Message = message;
 }
Esempio n. 20
0
 public EmailServicePublication(Topic topic, IPublishableMessage message)
     : base(topic, message)
 {
 }
 public when_publishing_topic_message_to_rabbitmq()
 {
     bus = new FakeBus();
     message = new TopicTestMessage();
     publisher = new RabbitMQ.Publisher(bus);
 }
Esempio n. 22
0
 public void Notify(IPublishableMessage message)
 {
     Logger.LogDebug($"Message recived from PubSub with type {message.GetType().ToString()}.");
     Provider.Instance.SCADAResultHandler.HandleResult(message);
 }
 /// <summary>
 /// OBAZRIVO, treba srediti cancellation tokene, sa tajmerima...
 /// </summary>
 /// <param name="message"></param>
 /// <returns></returns>
 public Task Notify(IPublishableMessage message, string publisherName)
 {
     //return MethodWrapperAsync("Notify", new object[2] { message, publisherName });
     return(InvokeWithRetryAsync(client => client.Channel.Notify(message, publisherName)));
 }
Esempio n. 24
0
        public async Task Notify(IPublishableMessage message, string publisherName)
        {
            Logger.LogDebug($"{baseLogString} Notify method invoked. Publisher {publisherName}.");

            while (!isActiveOutagesInitialized)
            {
                await Task.Delay(1000);
            }

            if (message is ActiveOutageMessage activeOutageMessage)
            {
                await ActiveOutages.SetAsync(activeOutageMessage.OutageId, activeOutageMessage);

                foreach (var equipment in activeOutageMessage.OptimumIsolationPoints)
                {
                    await this.historyDBManager.UpdateClosedSwitch(equipment.EquipmentId, activeOutageMessage.OutageId);
                }

                foreach (var equipment in activeOutageMessage.DefaultIsolationPoints)
                {
                    await this.historyDBManager.UpdateClosedSwitch(equipment.EquipmentId, activeOutageMessage.OutageId);
                }

                foreach (var consumer in activeOutageMessage.AffectedConsumers)
                {
                    await this.historyDBManager.UpdateConsumer(consumer.ConsumerId, activeOutageMessage.OutageId);
                }
            }
            else if (message is ArchivedOutageMessage archiveOutageMessage)
            {
                if (await ActiveOutages.ContainsKeyAsync(archiveOutageMessage.OutageId))
                {
                    await ActiveOutages.TryRemoveAsync(archiveOutageMessage.OutageId);
                }
                else
                {
                    Logger.LogWarning($"{baseLogString} WARNING Acrhived outage arrived, but there is no such in active outages. Outage Id {archiveOutageMessage.OutageId}.");
                }
            }
            else if (message is TopologyForUIMessage topology)
            {
                List <long>    blackedOut = new List <long>();
                HashSet <long> energized  = new HashSet <long>();

                Dictionary <long, ActiveOutageMessage> outages = await ActiveOutages.GetEnumerableDictionaryAsync();

                foreach (var element in topology.UIModel.Nodes.Values)
                {
                    DMSType type = (DMSType)ModelCodeHelper.ExtractTypeFromGlobalId(element.Id);

                    if (type == DMSType.ENERGYCONSUMER)
                    {
                        if (element.IsActive)
                        {
                            energized.Add(element.Id);
                        }
                        else
                        {
                            var outageId = await CheckConsumer(element.Id);

                            await this.historyDBManager.OnConsumerBlackedOut(element.Id, outageId);

                            //blackedOut.Add(element.Id);
                        }
                    }
                    else if (type == DMSType.LOADBREAKSWITCH ||
                             type == DMSType.BREAKER ||
                             type == DMSType.FUSE ||
                             type == DMSType.DISCONNECTOR)
                    {
                        if (IsOpened(element))
                        {
                            var outageId = await CheckSwitch(element.Id);

                            await this.historyDBManager.OnSwitchOpened(element.Id, outageId);
                        }
                        else
                        {
                            await this.historyDBManager.OnSwitchClosed(element.Id);
                        }
                    }
                }

                //await this.historyDBManager.OnConsumerBlackedOut(blackedOut, null);
                await this.historyDBManager.OnConsumersEnergized(energized);
            }
        }
Esempio n. 25
0
 public void Notify(IPublishableMessage message)
 {
     IOutageTopologyModel outageTopologyModel = message as IOutageTopologyModel;
 }
Esempio n. 26
0
        public async Task Notify(IPublishableMessage message, string publisherName)
        {
            if (message is ActiveOutageMessage activeOutage)
            {
                Logger.LogInformation($"{baseLogString} Notify => ActiveOutageMessageReceived. OutageId: 0x{activeOutage.OutageId:x16} ElementId: 0x{activeOutage.OutageElementGid}");
                var outageDispatcher = new OutageHubDispatcher(_outageMapper);
                outageDispatcher.Connect();

                try
                {
                    await outageDispatcher.NotifyActiveOutageUpdate(activeOutage);
                }
                catch (Exception e)
                {
                    string errorMessage = $"{baseLogString} Notify => exception {e.Message}";
                    Logger.LogError(errorMessage, e);
                }
            }
            else if (message is ArchivedOutageMessage archivedOutage)
            {
                var outageDispatcher = new OutageHubDispatcher(_outageMapper);
                outageDispatcher.Connect();

                try
                {
                    await outageDispatcher.NotifyArchiveOutageUpdate(archivedOutage);
                }
                catch (Exception e)
                {
                    string errorMessage = $"{baseLogString} Notify => exception {e.Message}";
                    Logger.LogError(errorMessage, e);
                }
            }
            else if (message is TopologyForUIMessage topologyMessage)
            {
                OmsGraphViewModel graph = _graphMapper.Map(topologyMessage.UIModel);

                var graphDispatcher = new GraphHubDispatcher();
                graphDispatcher.Connect();

                try
                {
                    await graphDispatcher.NotifyGraphUpdate(graph.Nodes, graph.Relations);
                }
                catch (Exception e)
                {
                    string errorMessage = $"{baseLogString} Notify => exception {e.Message}";
                    Logger.LogError(errorMessage, e);
                }
            }
            else if (message is MultipleAnalogValueSCADAMessage analogValuesMessage)
            {
                Dictionary <long, AnalogModbusData> analogModbusData = new Dictionary <long, AnalogModbusData>(analogValuesMessage.Data);

                var scadaDispatcher = new ScadaHubDispatcher();
                scadaDispatcher.Connect();

                try
                {
                    await scadaDispatcher.NotifyScadaDataUpdate(analogModbusData);
                }
                catch (Exception e)
                {
                    string errorMessage = $"{baseLogString} Notify => exception {e.Message}";
                    Logger.LogError(errorMessage, e);
                }
            }
        }
 public when_publishing_a_null_message_to_rabbitmq()
 {
     bus = new FakeBus();
     message = null;
     publisher = new global::Workflow.RabbitMQ.Publisher(bus);
 }
        public async Task Notify(IPublishableMessage message, string publisherName)
        {
            Logger.LogDebug($"{baseLogString} Notify method started.");

            while (!ReliableDictionariesInitialized)
            {
                await Task.Delay(1000);
            }

            try
            {
                if (message is MultipleDiscreteValueSCADAMessage multipleDiscreteValueSCADAMessage)
                {
                    Logger.LogDebug($"{baseLogString} MultipleDiscreteValueSCADAMessage received.");
                    var discreteData = multipleDiscreteValueSCADAMessage.Data;

                    #region HeadBreakers
                    var enumerableHeadBreakerMeasurements = await MonitoredHeadBreakerMeasurements.GetEnumerableDictionaryAsync();

                    foreach (var headMeasurementGid in enumerableHeadBreakerMeasurements.Keys)
                    {
                        if (!discreteData.ContainsKey(headMeasurementGid))
                        {
                            continue;
                        }

                        await MonitoredHeadBreakerMeasurements.SetAsync(headMeasurementGid, discreteData[headMeasurementGid]);
                    }
                    #endregion HeadBreakers

                    #region CommandedElements
                    var measurementProviderClient   = MeasurementProviderClient.CreateClient();
                    var enumerableCommandedElements = await CommandedElements.GetEnumerableDictionaryAsync();

                    foreach (var commandedElementGid in enumerableCommandedElements.Keys)
                    {
                        var measurementGid = (await measurementProviderClient.GetMeasurementsOfElement(commandedElementGid)).FirstOrDefault();
                        var measurement    = await measurementProviderClient.GetDiscreteMeasurement(measurementGid);

                        if (measurement is ArtificalDiscreteMeasurement)
                        {
                            await CommandedElements.TryRemoveAsync(commandedElementGid);

                            Logger.LogInformation($"{baseLogString} Notify => Command on element 0x{commandedElementGid:X16} executed (ArtificalDiscreteMeasurement). New value: {measurement.CurrentOpen}");
                            continue;
                        }

                        if (!discreteData.ContainsKey(measurementGid))
                        {
                            continue;
                        }

                        if (discreteData[measurementGid].Value == (ushort)enumerableCommandedElements[commandedElementGid].CommandingType)
                        {
                            if ((await CommandedElements.TryRemoveAsync(commandedElementGid)).HasValue)
                            {
                                Logger.LogInformation($"{baseLogString} Notify => Command on element 0x{commandedElementGid:X16} executed. New value: {discreteData[measurementGid].Value}");
                            }
                        }
                    }
                    #endregion CommandedElements
                }
                else if (message is OMSModelMessage omsModelMessage)
                {
                    Logger.LogDebug($"{baseLogString} OMSModelMessage received. Count {omsModelMessage.OutageTopologyModel.OutageTopology.Count}");

                    OutageTopologyModel topology = omsModelMessage.OutageTopologyModel;
                    await OutageTopologyModel.SetAsync(ReliableDictionaryNames.OutageTopologyModel, topology);

                    var reportingOutageClient = PotentialOutageReportingClient.CreateClient();

                    while (true)
                    {
                        var result = await PotentialOutagesQueue.TryDequeueAsync();

                        if (!result.HasValue)
                        {
                            break;
                        }

                        var command = result.Value;

                        await reportingOutageClient.ReportPotentialOutage(command.ElementGid, command.CommandOriginType, command.NetworkType);

                        Logger.LogInformation($"{baseLogString} PotentianOutageCommand executed. ElementGid: 0x{command.ElementGid:X16}, OriginType: {command.CommandOriginType}");
                    }
                }
                else
                {
                    Logger.LogWarning($"{baseLogString} Notify => unexpected type of message: {message.GetType()}");
                    return;
                }
            }
            catch (Exception e)
            {
                string errorMessage = $"{baseLogString} Notify => Exception: {e.Message}";
                Logger.LogError(errorMessage, e);
            }
        }
 public when_publishing_a_message_and_the_underlying_bus_fails()
 {
     bus = new FailingBus();
     message = new TestMessage();
     publisher = new global::Workflow.RabbitMQ.Publisher(bus, new TestingRetryStrategy());
 }
Esempio n. 30
0
 /// <summary>
 /// Publish an encapsulated message to the bus
 /// </summary>
 /// <param name="messageBus">The message bus</param>
 /// <param name="message">The encapsulated message with all necessary publish details</param>
 public static void PublishMessage(this IPublishable messageBus, IPublishableMessage message)
 {
     Assert.ArgumentNotNull(messageBus, nameof(messageBus));
     Assert.ArgumentNotNull(message, nameof(message));
     message.PublishTo(messageBus);
 }