Beispiel #1
0
        private bool PLCStatus(IIncomingMessage Message)
        {
            bool RetValue = true;

            // get msg application data
            var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as PLCStatusData;

            Logger.InfoFormat("Ricevuto Messaggio {1}:{2} da {0}", Message.SourceApplicationName, MsgData.PLCName, MsgData.Status, MsgData.validation);

            RetValue = MsgData.validation;

            if (MsgData.validation)
            {
                var plc = model.ListPLCItems.FirstOrDefault(item => item.Name == MsgData.PLCName);
                if (plc != null)
                {
                    plc.ConnectionStatus = MsgData.Status;
                }
                else
                {
                    RetValue = false;
                }
            }

            return(RetValue);
        }
Beispiel #2
0
        /// <summary>
        /// Implementazione esecuzione comando di rimozione della sottoscrizione di una lista di plctags
        /// </summary>
        /// <param name="Message">Dati messaggio ricevuto</param>
        /// <returns>true se tutto bene, altrimenti false</returns>
        private bool RemovePLCTags(IIncomingMessage Message)
        {
            bool RetValue = true;

            // get msg application data
            var MsgData  = GeneralHelper.DeserializeObject(Message.MessageData) as PLCTagsData;
            var tagslist = MsgData.Tags;

            Logger.InfoFormat("{0}", Message.SourceApplicationName);

            for (int i = 0; i < tagslist.Count; i++)
            {
                var tag = tagslist[i];

                if (!RemovePLCTag(Message.SourceApplicationName, tag))
                {
                    tag.Validation = false;
                    RetValue       = false;
                }
                else
                {
                    tag.Validation = true;
                }
            }

            // invio messaggio di risposta generica
            return(SendResponse(Message, MsgCodes.ResultRemovePLCTags, MsgData, RetValue));
        }
Beispiel #3
0
        private bool DisconnectSubscriber(IIncomingMessage Message)
        {
            bool RetValue = true;

            // get msg application data (not useful for now)
            var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as MsgData;

            Logger.InfoFormat("{1} da {0}", Message.SourceApplicationName, MsgData.MsgCode);

            // gestione subscriptions
            if (ListSubscriptions.ContainsKey(Message.SourceApplicationName))
            {
                foreach (var sub in ListSubscriptions[Message.SourceApplicationName].ToList())
                {
                    RemoveProperty(Message.SourceApplicationName, new Property()
                    {
                        ObjPath = sub.ObjPath
                    });
                }
                ListSubscriptions.Remove(Message.SourceApplicationName);
            }
            else
            {
                // non esiste !
                Logger.WarnFormat("{0} non sottoscritto!", Message.SourceApplicationName);
                RetValue = false;
            }

            /* invio messaggio di risposta */
            return(SendResponse(Message, MsgCodes.ResultDisconnectSubscriber, MsgData, RetValue));
        }
Beispiel #4
0
        private bool SubscribeProperty(IIncomingMessage Message)
        {
            bool RetValue = true;

            // get msg application data
            var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as PropertyData;
            var prop    = MsgData.Prop;

            Logger.InfoFormat("{1} da {0}", Message.SourceApplicationName, prop.ObjPath);


            RetValue = SubscribeProperty(Message.SourceApplicationName, prop);

            /* invio messaggio di risposta */
            RetValue = SendResponse(Message, MsgCodes.ResultSubscribeProperty, MsgData, RetValue);

            // all'atto della sottoscrizione invio valore attuale della property
            if (RetValue)
            {
                PropertyNotifyToSubscriber(Message.SourceApplicationName, prop);
            }


            return(RetValue);
        }
Beispiel #5
0
        private bool PLCTagsChanged(IIncomingMessage Message)
        {
            bool RetValue = true;

            // get msg application data
            var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as PLCTagsData;
            var plctags = MsgData.Tags;

            Logger.InfoFormat("Ricevuto Messaggio da {0}", Message.SourceApplicationName);

            foreach (var plctag in plctags)
            {
                bool bOK = true;

                // trova il tag corrispondente (uno solo) all'indirizzo sottoscritto
                TagItem tag = ListTagItems.FirstOrDefault(item => item.PLCName == plctag.PLCName && item.Address == plctag.Address);

                if (tag != null)
                {
                    //
                    try
                    {
                        tag.Value = plctag.Value;
                        Logger.InfoFormat("Cambiato Tag {0} : {1}/{2}:{3} -> {4}", tag.Name, tag.PLCName, tag.Address, tag.Type, tag.Value);
                    }
                    catch (Exception exc)
                    {
                        Logger.WarnFormat("Errore in cambio Tag value {0} : {1}/{2}:{3} -> {4} {5}", tag.Name, tag.PLCName, tag.Address, tag.Type, tag.Value, exc.Message);
                    }

                    // recuperare la lista delle properties dell'impianto
                    List <MariniProperty> props = mariniImpiantoTree.MariniImpianto.GetObjectListByType(typeof(MariniProperty)).Cast <MariniProperty>().ToList();
                    // trova la property associata e cambia il valore
                    MariniProperty property = props.FirstOrDefault(prp => prp.bind == tag.Name);

                    if (property != null)
                    {
                        try
                        {
                            property.value = tag.Value;
                        }
                        catch (Exception exc)
                        {
                            Logger.WarnFormat("Errore in cambio valore property {0}:{1} {2}", property.name, tag.Value, exc.Message);
                            bOK = false;
                        }
                    }
                }
                else
                {
                    Logger.InfoFormat("Tag associato a : {0}/{1} non trovato", plctag.PLCName, plctag.Address);
                    bOK = false;
                }
                if (bOK == false)
                {
                    RetValue = bOK;
                }
            }
            return(RetValue);
        }
Beispiel #6
0
        /// <summary>
        /// Implementazione esecuzione comando di disconnessione di un client sottoscrittore
        /// </summary>
        /// <param name="Message">Dati messaggio ricevuto</param>
        /// <returns>true se tutto bene, altrimenti false</returns>
        private bool DisconnectSubscriber(IIncomingMessage Message)
        {
            bool RetValue = true;

            // get msg application data
            var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as MsgData;

            Logger.InfoFormat("{1} da {0}", Message.SourceApplicationName, MsgData.MsgCode);

            // gestione subscriptions
            if (_Subs.ContainsKey(Message.SourceApplicationName))
            {
                foreach (var sub in _Subs[Message.SourceApplicationName].ToList())
                {
                    RemovePLCTag(Message.SourceApplicationName, new PLCTag()
                    {
                        PLCName = sub.PLCName, Address = sub.TagAddress
                    });
                }
                _Subs.Remove(Message.SourceApplicationName);
            }
            else
            {
                // non esiste !
                Logger.WarnFormat("{0} non sottoscritto!", Message.SourceApplicationName);
                RetValue = false;
            }

            /* invio messaggio di risposta generica */
            return(SendResponse(Message, MsgCodes.ResultDisconnectSubscriber, MsgData, RetValue));
        }
Beispiel #7
0
        private bool ResultDisconnectPLC(IIncomingMessage Message)
        {
            bool RetValue = true;

            // get msg application data
            var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as PLCData;

            Logger.InfoFormat("Ricevuto Messaggio {1} da {0}", Message.SourceApplicationName, MsgData.PLCName);

            RetValue = MsgData.validation;

            if (MsgData.validation)
            {
                var plc = model.ListPLCItems.FirstOrDefault(item => item.Name == MsgData.PLCName);
                if (plc != null)
                {
                    // reentrant... approfondire
                    Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
                    {
                        model.ListPLCItems.Remove(plc);
                    }));
                }
            }

            return(RetValue);
        }
        /// <summary>
        /// Sends remote method invocation message to the remote application and gets result.
        /// This simplifies remove method invocation like calling a method locally.
        /// It throws Exception if any Exception occured on remote application's method.
        /// </summary>
        /// <param name="methodName">Method name to invoke</param>
        /// <param name="args">Method parameters</param>
        /// <returns>Return value of remote method</returns>
        protected object InvokeRemoteMethodAndGetResult(string methodName, params object[] args)
        {
            //Create MDSRemoteInvokeMessage object that contains invocation informations
            var invokeMessage = new MDSRemoteInvokeMessage {
                ServiceClassName = _serviceClassName, MethodName = methodName, Parameters = args
            };

            //Create MDS message to transmit MDSRemoteInvokeMessage.
            var outgoingMessage = _serviceConsumer.MdsClient.CreateMessage();

            outgoingMessage.DestinationServerName      = RemoteApplication.ServerName;
            outgoingMessage.DestinationApplicationName = RemoteApplication.ApplicationName;
            outgoingMessage.DestinationCommunicatorId  = RemoteApplication.CommunicatorId;
            outgoingMessage.TransmitRule = MessageTransmitRules.DirectlySend;
            outgoingMessage.MessageData  = GeneralHelper.SerializeObject(invokeMessage);

            //Send message and get response
            var incomingMessage = outgoingMessage.SendAndGetResponse(Timeout);

            incomingMessage.Acknowledge();

            //Deserialize and check return value
            var invokeReturnMessage = (MDSRemoteInvokeReturnMessage)GeneralHelper.DeserializeObject(incomingMessage.MessageData);

            if (invokeReturnMessage.RemoteException != null)
            {
                throw invokeReturnMessage.RemoteException;
            }

            //Success
            return(invokeReturnMessage.ReturnValue);
        }
Beispiel #9
0
        private bool PLCTagChanged(IIncomingMessage Message)
        {
            bool RetValue = true;

            // get msg application data
            var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as PLCTagData;

            Logger.InfoFormat("Ricevuto Messaggio {1}/{2}:{3} da {0}", Message.SourceApplicationName, MsgData.Tag.PLCName, MsgData.Tag.Address, MsgData.Tag.Value);

            var tag = model.ListTagItems.FirstOrDefault(item => item.Address == MsgData.Tag.Address);

            if (tag != null)
            {
                // funzionano entrambe, la Invoke esegue in modo bloccante, la BeginInvoke esegue in parallelo

                //Application.Current.Dispatcher.Invoke(new Action(() =>
                //{
                //    tag.Value = MsgData.Tag.Value.ToString();
                //}));

                Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
                {
                    tag.Value = MsgData.Tag.Value.ToString();
                }));
            }
            else
            {
                Logger.InfoFormat("Tag {0}/{1} non trovato", tag.PLCName, tag.Address);
                RetValue = false;
            }

            return(RetValue);
        }
Beispiel #10
0
        private bool ResultSubscribePLCTag(IIncomingMessage Message)
        {
            bool RetValue = true;

            // get msg application data
            var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as PLCTagData;

            Logger.InfoFormat("Ricevuto Messaggio {1}/{2}:{3} da {0}", Message.SourceApplicationName, MsgData.Tag.PLCName, MsgData.Tag.Address, MsgData.Tag.Value);

            TagItem tag = new TagItem()
            {
                PLCName = MsgData.Tag.PLCName, Address = MsgData.Tag.Address
            };

            if (tag != null)
            {
                Logger.InfoFormat("Aggiunto {0}/{1}", tag.PLCName, tag.Address);

                if (GuiContext != null)
                {
                    GuiContext.Send((o) => { model.ListTagItems.Add(tag); }, null);
                }
                else
                {
                    Logger.InfoFormat("GuiContext NULL");
                    Debug.Assert(false);
                }
            }
            return(RetValue);
        }
Beispiel #11
0
        /// <summary>
        /// Implementazione esecuzione comando di richiesta lista plctags sotoscritti
        /// </summary>
        /// <param name="Message">Dati messaggio ricevuto</param>
        /// <returns>true se tutto bene, altrimenti false</returns>
        private bool GetSubscribedPLCTags(IIncomingMessage Message)
        {
            bool RetValue = true;
            var  tagslist = new List <PLCTag>();

            // get msg application data
            var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as MsgData;

            Logger.InfoFormat("{0}", Message.SourceApplicationName);

            // gestione subscriptions
            if (!_Subs.ContainsKey(Message.SourceApplicationName))
            {
                Logger.WarnFormat("[{0}] has no subscriptions", Message.SourceApplicationName);
                RetValue = false;
            }
            else
            {
                // costruisco la lista da inviare come risposta
                foreach (var sub in _Subs[Message.SourceApplicationName].ToList())
                {
                    var tag = new PLCTag()
                    {
                        PLCName = sub.PLCName, Address = sub.TagAddress, Validation = true
                    };
                    tagslist.Add(tag);
                }
            }

            // invio messaggio di risposta generica
            return(SendResponse(Message, MsgCodes.SubscribedPLCTags, new PLCTagsData()
            {
                MsgCode = MsgCodes.SubscribedPLCTags, Tags = tagslist
            }, RetValue));
        }
Beispiel #12
0
        /// <summary>
        /// This method handles received messages from other applications via DotNetMQ.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e">Message parameters</param>
        private void hmi_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            // Get message
            var Message = e.Message;

            try
            {
                // Get message data
                var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as MsgData;

                switch (MsgData.MsgCode)
                {
                case MsgCodes.PropertiesChanged: /* gestione da fare */ break;

                case MsgCodes.PropertyChanged:             PropertyChanged(Message);  break;

                case MsgCodes.SubscribedProperties: /* Da implementare */ break;

                case MsgCodes.ResultSubscribeProperty: /* Da implementare */ break;

                case MsgCodes.ResultSubscribeProperties: /* Da implementare */ break;

                case MsgCodes.ResultRemoveProperty: /* Da implementare */ break;

                case MsgCodes.ResultRemoveProperties: /* Da implementare */ break;
                }
            }
            catch (Exception ex)
            {
                Logger.Warn(ex.Message, ex);
            }

            // Acknowledge that message is properly handled and processed. So, it will be deleted from queue.
            e.Message.Acknowledge();
        }
Beispiel #13
0
        private bool RemoveProperties(IIncomingMessage Message)
        {
            bool RetValue = true;

            // get msg application data
            var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as PropertiesData;
            var props   = MsgData.Props;

            Logger.InfoFormat("{0}", Message.SourceApplicationName);

            for (int i = 0; i < props.Count(); i++)
            {
                var prop = props[i];
                if (!RemoveProperty(Message.SourceApplicationName, prop))
                {
                    RetValue        = false;
                    prop.Validation = false;
                }
                else
                {
                    prop.Validation = true;
                }
            }

            /* invio messaggio di risposta */
            return(SendResponse(Message, MsgCodes.ResultRemoveProperties, MsgData, RetValue));
        }
Beispiel #14
0
        void client_MessageReceived(object sender, MDS.Client.MessageReceivedEventArgs e)
        {
            var      instance  = GeneralHelper.DeserializeObject(e.Message.MessageData);
            IMessage message   = new DotNetMQ(e.Message);
            var      eventArgs = new MessageReceivedEventArgs(this, message);

            OnReceived(this, eventArgs);
        }
Beispiel #15
0
        static void MDSClient_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            //Get message
            var stockQueryMessage = GeneralHelper.DeserializeObject(e.Message.MessageData) as StockQueryMessage;

            if (stockQueryMessage == null)
            {
                return;
            }

            //Write message content
            Console.WriteLine("Stock Query Message for: " + stockQueryMessage.StockCode);

            //Get stock counts from a database...
            int reservedStockCount;
            int totalStockCount;

            switch (stockQueryMessage.StockCode)
            {
            case "S01":
                reservedStockCount = 14;
                totalStockCount    = 80;
                break;

            case "S02":
                reservedStockCount = 0;
                totalStockCount    = 25;
                break;

            default:
                reservedStockCount = -1;
                totalStockCount    = -1;
                break;
            }

            //Create a reply message for stock query
            var stockQueryResult = new StockQueryResultMessage
            {
                StockCode          = stockQueryMessage.StockCode,
                ReservedStockCount = reservedStockCount,
                TotalStockCount    = totalStockCount
            };

            //Create a MDS response message to send to client
            var responseMessage = e.Message.CreateResponseMessage();

            responseMessage.MessageData = GeneralHelper.SerializeObject(stockQueryResult);

            //Send message
            responseMessage.Send();

            //Acknowledge the original request message. So, it will be deleted from queue.
            e.Message.Acknowledge();
        }
Beispiel #16
0
        /// <summary>
        /// This method handles received messages from other applications via DotNetMQ.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e">Message parameters</param>
        private void PLCServer_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            // Get message
            var Message = e.Message;

            // Acknowledge that message is properly handled and processed. So, it will be deleted from queue.
            e.Message.Acknowledge();

            // Get message data
            var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as MsgData;

            try
            {
                switch (MsgData.MsgCode)
                {
                case MsgCodes.ConnectSubscriber:      ConnectSubscriber(Message);       break;

                case MsgCodes.DisconnectSubscriber:   DisconnectSubscriber(Message);    break;

                case MsgCodes.SubscribePLCTag:        SubscribePLCTag(Message);         break;

                case MsgCodes.SubscribePLCTags:       SubscribePLCTags(Message);        break;

                case MsgCodes.RemovePLCTag:           RemovePLCTag(Message);            break;

                case MsgCodes.RemovePLCTags:          RemovePLCTags(Message);           break;

                case MsgCodes.GetSubscribedPLCTags:   GetSubscribedPLCTags(Message);    break;

                case MsgCodes.SetPLCTags:             SetPLCTags(Message);              break;

                case MsgCodes.GetPLCTags:             GetPLCTags(Message);              break;

                case MsgCodes.SetPLCTag:              SetPLCTag(Message);               break;

                case MsgCodes.GetPLCTag:              GetPLCTag(Message);               break;

                case MsgCodes.StartCheckPLCTags:      StartCheckPLCTags(Message);       break;

                case MsgCodes.StopCheckPLCTags:       StopCheckPLCTags(Message);        break;

                case MsgCodes.GetPLCStatus:           GetPLCStatus(Message);            break;

                case MsgCodes.ConnectPLC:             ConnectPLC(Message);              break;

                case MsgCodes.DisconnectPLC:          DisconnectPLC(Message);           break;
                }
            }
            catch (Exception ex)
            {
                Logger.Warn(ex.Message, ex);
            }
        }
Beispiel #17
0
        /// <summary>
        /// Ricezione messaggio di valore di plctag sottoscritto cambiato
        /// se la property associata è sottoscritta invio messaggio di notifica al sottoscrittore
        /// </summary>
        /// <param name="Message"></param>
        /// <returns><c>true</c> if the tag is effectively subscribed; otherwise, <c>false</c>.</returns>
        private bool PLCTagChanged(IIncomingMessage Message)
        {
            bool RetValue = true;

            // get msg application data
            var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as PLCTagData;
            var plctag  = MsgData.Tag;

            Logger.InfoFormat("{0} -> {1}/{2}:{3}", Message.SourceApplicationName, plctag.PLCName, plctag.Address, plctag.Value);

            // trova il tag corrispondente all'indirizzo sottoscritto
            TagItem tag;

            if ((tag = ListTagItems.FirstOrDefault(item => item.PLCName == plctag.PLCName && item.Address == plctag.Address)) != null)
            {
                //
                try
                {
                    tag.Value = MsgData.Tag.Value;
                }
                catch (Exception exc)
                {
                    Logger.WarnFormat("Errore in cambio Tag value {0} : {1}/{2}:{3} -> {4} {5}", tag.Name, tag.PLCName, tag.Address, tag.Type, tag.Value, exc.Message);
                    RetValue = false;
                }

                // recupero la lista delle properties dell'impianto
                // LG: Ma la uso anche in SubscribePLCTags!!! Devo fare tutte le volte sta roba?
                List <PropertyObject> props = dataManager.PathObjectsDictionary.Values.Where(item => item.GetType() == typeof(PropertyObject)).Cast <PropertyObject>().ToList();

                // trova la property associata e cambia il valore
                PropertyObject property = props.FirstOrDefault(prp => prp.bind == tag.Name);

                if (property != null)
                {
                    try
                    {
                        property.value = tag.Value;
                    }
                    catch (Exception exc)
                    {
                        Logger.WarnFormat("Errore in cambio valore property {0}:{1} {2}", property.path, tag.Value, exc.Message);
                        RetValue = false;
                    }
                }
            }
            else
            {
                Logger.InfoFormat("Tag associato a : {0}/{1} non trovato", plctag.PLCName, plctag.Address);
                RetValue = false;
            }
            return(RetValue);
        }
Beispiel #18
0
        /// <summary>
        /// Implementazione esecuzione comando di richiesta valore lista plctags
        /// </summary>
        /// <param name="Message">Dati messaggio ricevuto</param>
        /// <returns>true se tutto bene, altrimenti false</returns>
        private bool GetPLCTags(IIncomingMessage Message)
        {
            bool RetValue = true;


            // get msg application data
            var MsgData  = GeneralHelper.DeserializeObject(Message.MessageData) as PLCTagsData;
            var tagslist = MsgData.Tags;

            Logger.InfoFormat("{0}", Message.SourceApplicationName);

            for (int i = 0; i < tagslist.Count; i++)
            {
                var tag = tagslist[i];

                // verifico connessione/esistenza PLC interessato
                if (!_PLCs.ContainsKey(tag.PLCName))
                {
                    // log
                    Logger.WarnFormat("PLC [{1}] not connected", tag.PLCName);

                    tag.Validation = true;
                    RetValue       = false;
                }
                else
                {
                    try
                    {
                        /* leggo tag value */
                        var plctag = _PLCs[tag.PLCName].Read(new S7NetWrapper.Tag(tag.Address));
                        if (plctag != null)
                        {
                            tag.Value      = plctag.ItemValue;
                            tag.Validation = true;
                        }
                    }
                    catch (Exception exc)
                    {
                        // log
                        Logger.WarnFormat("PLC [{0}] error reading tag {1} : {2}", tag.PLCName, tag.Address, exc.Message);
                        tag.Validation = true;
                        RetValue       = false;
                    }
                }
            }

            // invio messaggio di risposta generica
            return(SendResponse(Message, MsgCodes.ResultGetPLCTags, new PLCTagsData()
            {
                MsgCode = MsgCodes.ResultGetPLCTags, Tags = tagslist
            }, RetValue));
        }
Beispiel #19
0
        /// <summary>
        /// Implementazione esecuzione comando di rimozione di un plctags
        /// </summary>
        /// <param name="Message">Dati messaggio ricevuto</param>
        /// <returns>true se tutto bene, altrimenti false</returns>
        private bool RemovePLCTag(IIncomingMessage Message)
        {
            bool RetValue = true;

            // get msg application data
            var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as PLCTagData;
            var tag     = MsgData.Tag;

            RetValue = RemovePLCTag(Message.SourceApplicationName, tag);

            // invio messaggio di risposta generica
            return(SendResponse(Message, MsgCodes.ResultRemovePLCTag, MsgData, RetValue));
        }
Beispiel #20
0
        /// <summary>
        /// This method handles all incoming messages from MDS server.
        /// </summary>
        /// <param name="sender">Creator object of method (MDSClient object)</param>
        /// <param name="e">Message event arguments</param>
        private void MdsClient_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            //Deserialize message
            MDSRemoteInvokeMessage invokeMessage;

            try
            {
                invokeMessage = (MDSRemoteInvokeMessage)GeneralHelper.DeserializeObject(e.Message.MessageData);
            }
            catch (Exception ex)
            {
                AcknowledgeMessage(e.Message);
                SendException(e.Message, new MDSRemoteException("Incoming message can not be deserialized to MDSRemoteInvokeMessage.", ex));
                return;
            }

            //Check service class name
            if (!_serviceObjects.ContainsKey(invokeMessage.ServiceClassName))
            {
                AcknowledgeMessage(e.Message);
                SendException(e.Message, new MDSRemoteException("There is no service with name '" + invokeMessage.ServiceClassName + "'"));
                return;
            }

            //Get service object
            var serviceObject = _serviceObjects[invokeMessage.ServiceClassName];

            //Invoke service method and get return value
            object returnValue;

            try
            {
                //Set request variables to service object and invoke method
                serviceObject.Service.IncomingMessage = e.Message;
                returnValue = serviceObject.InvokeMethod(invokeMessage.MethodName, invokeMessage.Parameters);
            }
            catch (Exception ex)
            {
                SendException(e.Message,
                              new MDSRemoteException(
                                  ex.Message + Environment.NewLine + "Service Class: " +
                                  invokeMessage.ServiceClassName + " " + Environment.NewLine +
                                  "Service Version: " + serviceObject.ServiceAttribute.Version, ex));
                return;
            }

            //Send return value to sender application
            SendReturnValue(e.Message, returnValue);
        }
Beispiel #21
0
        /// <summary>
        /// Implementazione esecuzione comando di richiesta valore plctag
        /// </summary>
        /// <param name="Message">Dati messaggio ricevuto</param>
        /// <returns>true se tutto bene, altrimenti false</returns>
        private bool GetPLCTag(IIncomingMessage Message)
        {
            bool RetValue = true;

            // get msg application data
            var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as PLCTagData;
            var tag     = MsgData.Tag;

            Logger.InfoFormat("{0}/{1} da {2}", tag.PLCName, tag.Address, Message.SourceApplicationName);

            RetValue = GetPLCTag(ref tag);

            // invio messaggio di risposta generica
            return(SendResponse(Message, MsgCodes.ResultGetPLCTag, MsgData, RetValue));
        }
Beispiel #22
0
        private bool RemoveProperty(IIncomingMessage Message)
        {
            bool RetValue = true;

            // get msg application data
            var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as PropertyData;
            var prop    = MsgData.Prop;

            Logger.InfoFormat("{1} da {0}", Message.SourceApplicationName, prop.ObjPath);

            RetValue = RemoveProperty(Message.SourceApplicationName, prop);

            /* invio messaggio di risposta */
            return(SendResponse(Message, MsgCodes.ResultRemoveProperty, MsgData, RetValue));
        }
Beispiel #23
0
        private bool ResultConnectSubscriber(IIncomingMessage Message)
        {
            bool RetValue = true;

            // get msg application data
            var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as MsgData;

            Logger.InfoFormat("Ricevuto Messaggio {1} da {0}", Message.SourceApplicationName, MsgData.validation);

            RetValue = MsgData.validation;

            model.ConnectionState = true;

            return(RetValue);
        }
Beispiel #24
0
        /// <summary>
        /// This method handles received messages from other applications via DotNetMQ.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e">Message parameters</param>
        private void hmi_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            try
            {
                // Get message
                var Message = e.Message;


                // Acknowledge that message is properly handled and processed. So, it will be deleted from queue.
                e.Message.Acknowledge();

                // Get message data
                var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as MsgData;

                Logger.InfoFormat("Ricevuto Messaggio {0}", MsgData.MsgCode);


                switch (MsgData.MsgCode)
                {
                case MsgCodes.PLCTagsChanged: /* gestione da fare */ break;

                case MsgCodes.PLCTagChanged:           PLCTagChanged(Message);           break;

                case MsgCodes.PLCStatus:               PLCStatus(Message);               break;

                case MsgCodes.ResultSubscribePLCTag:   ResultSubscribePLCTag(Message);   break;

                case MsgCodes.ResultSubscribePLCTags:           break;

                case MsgCodes.ResultSetPLCTag:                  break;

                case MsgCodes.ResultSetPLCTags:                 break;

                case MsgCodes.ResultConnectSubscriber:    ResultConnectSubscriber(Message);    break;

                case MsgCodes.ResultDisconnectSubscriber: ResultDisconnectSubscriber(Message); break;

                case MsgCodes.ResultConnectPLC:           ResultConnectPLC(Message);           break;

                case MsgCodes.ResultDisconnectPLC:        ResultDisconnectPLC(Message);        break;
                }
            }
            catch (Exception ex)
            {
                Logger.Warn(ex.Message, ex);
            }
        }
Beispiel #25
0
        /// <summary>
        /// Implementazione esecuzione comando di set valore lista plctags
        /// </summary>
        /// <param name="Message">Dati messaggio ricevuto</param>
        /// <returns>true se tutto bene, altrimenti false</returns>
        private bool SetPLCTags(IIncomingMessage Message)
        {
            bool RetValue = true;

            // get msg application data
            var MsgData  = GeneralHelper.DeserializeObject(Message.MessageData) as PLCTagsData;
            var tagslist = MsgData.Tags;

            Logger.InfoFormat("{0}", Message.SourceApplicationName);

            for (int i = 0; i < tagslist.Count; i++)
            {
                var tag = tagslist[i];

                /* verifico connessione/esistenza PLC interessato */
                if (!_PLCs.ContainsKey(tag.PLCName))
                {
                    // log
                    Logger.WarnFormat("PLC [{0}] not connected", tag.PLCName);
                    tag.Validation = false;
                    RetValue       = false;
                }
                else
                {
                    try
                    {
                        /* scrivo tag */
                        var plctag = new S7NetWrapper.Tag(tag.Address, tag.Value);
                        _PLCs[tag.PLCName].Write(plctag);
                        tag.Validation = true;
                    }
                    catch (Exception exc)
                    {
                        // log
                        Logger.WarnFormat("PLC [{0}] error writing tag {1} : {2}", tag.PLCName, tag.Address, exc.Message);
                        tag.Validation = false;
                        RetValue       = false;
                    }
                }
            }

            /* invio messaggio di risposta generica */
            return(SendResponse(Message, MsgCodes.ResultSetPLCTags, MsgData, RetValue));
        }
Beispiel #26
0
        private bool PropertyChanged(IIncomingMessage Message)
        {
            bool RetValue = true;

            // get msg application data
            var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as PropertyData;
            var prop    = MsgData.Prop;

            Logger.InfoFormat("Ricevuto Messaggio {1}:{2} da {0}", Message.SourceApplicationName, prop.ObjPath, prop.Value);

            RetValue = PropertyChanged(prop);

            if (RetValue == false)
            {
                Logger.InfoFormat("Property {0} non trovata", prop.ObjPath);
            }

            return(RetValue);
        }
Beispiel #27
0
        /// <summary>
        /// Implementazione esecuzione comando di richiesta plc status
        /// </summary>
        /// <param name="Message">Dati messaggio ricevuto</param>
        /// <returns>true se tutto bene, altrimenti false</returns>
        private bool GetPLCStatus(IIncomingMessage Message)
        {
            bool RetValue = true;
            PLCConnectionStatus ConnectionStatus;

            // get msg application data
            var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as PLCData;

            Logger.InfoFormat("{0} da {1}", MsgData.PLCName, Message.SourceApplicationName);

            if (!_PLCs.ContainsKey(MsgData.PLCName))
            {
                // log
                Logger.WarnFormat("PLC [{0}] not connected", MsgData.PLCName);
                ConnectionStatus = PLCConnectionStatus.NotConnected;
                RetValue         = false;
            }
            else
            {
                var plc = _PLCs[MsgData.PLCName];

                switch (plc.ConnectionState)
                {
                case S7NetWrapper.ConnectionStates.Connecting:
                    ConnectionStatus = PLCConnectionStatus.InConnection;
                    break;

                default:
                case S7NetWrapper.ConnectionStates.Offline:
                    ConnectionStatus = PLCConnectionStatus.NotConnected;
                    break;

                case S7NetWrapper.ConnectionStates.Online:
                    ConnectionStatus = PLCConnectionStatus.Connected;
                    break;
                }
            }

            // invio messaggio di risposta generica
            return(SendResponse(Message, MsgCodes.PLCStatus, new PLCStatusData {
                PLCName = MsgData.PLCName, Status = ConnectionStatus
            }, RetValue));
        }
Beispiel #28
0
        static void Main(string[] args)
        {
            Console.WriteLine("Press enter to query a stock status");
            Console.ReadLine();

            //Connect to DotNetMQ
            var mdsClient = new MDSClient("StockClient");

            mdsClient.MessageReceived += mdsClient_MessageReceived;
            mdsClient.Connect();

            //Create a stock request message
            var stockQueryMessage = new StockQueryMessage {
                StockCode = "S01"
            };

            //Create a MDS message
            var requestMessage = mdsClient.CreateMessage();

            requestMessage.DestinationApplicationName = "StockServer";
            requestMessage.TransmitRule = MessageTransmitRules.NonPersistent;
            requestMessage.MessageData  = GeneralHelper.SerializeObject(stockQueryMessage);

            //Send message and get response
            var responseMessage = requestMessage.SendAndGetResponse();

            //Get stock query result message from response message
            var stockResult = (StockQueryResultMessage)GeneralHelper.DeserializeObject(responseMessage.MessageData);

            //Write stock query result
            Console.WriteLine("StockCode          = " + stockResult.StockCode);
            Console.WriteLine("ReservedStockCount = " + stockResult.ReservedStockCount);
            Console.WriteLine("TotalStockCount    = " + stockResult.TotalStockCount);

            //Acknowledge received message
            responseMessage.Acknowledge();

            Console.ReadLine();

            //Disconnect from DotNetMQ server.
            mdsClient.Disconnect();
        }
Beispiel #29
0
        /// <summary>
        /// Implementazione esecuzione comando di connessione di un plc
        /// </summary>
        /// <param name="Message">Dati messaggio ricevuto</param>
        /// <returns>true se tutto bene, altrimenti false</returns>
        private bool ConnectPLC(IIncomingMessage Message)
        {
            bool RetValue = true;

            // get msg application data
            var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as PLCConnectionData;

            Logger.InfoFormat("{1}-{2}-{3}-{4}-{5}-{6} da {0}", Message.SourceApplicationName, MsgData.PLCName, MsgData.Cputype.ToString(), MsgData.IpAddress, MsgData.Rack, MsgData.Slot, MsgData.Delay);

            if (!_Subs.ContainsKey(Message.SourceApplicationName))
            {
                Logger.WarnFormat("[{0}] not subscribed", Message.SourceApplicationName);
                RetValue = false;
            }
            else
            {
                RetValue = ConnectPLC(MsgData);
            }

            // invio messaggio di risposta generica
            return(SendResponse(Message, MsgCodes.ResultConnectPLC, MsgData, RetValue));
        }
Beispiel #30
0
        /// <summary>
        /// Implementazione esecuzione comando di disconnessione di un plc
        /// </summary>
        /// <param name="Message">Dati messaggio ricevuto</param>
        /// <returns>true se tutto bene, altrimenti false</returns>
        private bool DisconnectPLC(IIncomingMessage Message)
        {
            bool RetValue = true;

            // get msg application data
            var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as PLCData;

            Logger.InfoFormat("{1} da {0}", Message.SourceApplicationName, MsgData.PLCName);

            if (!_Subs.ContainsKey(Message.SourceApplicationName))
            {
                Logger.WarnFormat("[{0}] not subscribed", Message.SourceApplicationName);
                RetValue = false;
            }
            else
            {
                RetValue = DisconnectPLC(MsgData);
            }

            // invio messaggio di risposta generica
            return(SendResponse(Message, MsgCodes.ResultDisconnectPLC, MsgData, RetValue));
        }