private static void Main(string[] args)
        {
            InstantLogger.writeLogConsole = false;
            using (Logger l = new Logger("Fledged")) {
                try {
                    var o = new HeatChangeEvent(); /// нужно чтобы сборка загрузилась
                    m_pushGate = new ConnectionProvider.Client();

                    var mainConf = System.Configuration.ConfigurationManager.OpenExeConfiguration("");
                    var progId = mainConf.AppSettings.Settings["OPCServerProgID"].Value;
                    var addrFmt = mainConf.AppSettings.Settings["OPCAddressFormat"].Value;
                    var dest = mainConf.AppSettings.Settings["OPCDestination"].Value;
                    var convSchema = Convert.ToInt32(mainConf.AppSettings.Settings["OPCConvSchema"].Value);
                    var reqUpdateRateMs = Convert.ToInt32(mainConf.AppSettings.Settings["OPCCReqUpdateRate_ms"].Value);
                    l.msg("OPC Fledged started with ProgID=[{0}] for {1} aids conv schema {2}", progId, dest, convSchema);
                    OPCCon = new OpcConnector(progId, dest, addrFmt, convSchema, reqUpdateRateMs);

                    var receiverThread = new Thread(Receiver);
                    receiverThread.Start();

                    Console.WriteLine("Нажмите <ENTER> для выхода.");
                    Console.ReadLine();
                    OPCCon.CloseConnection();
                    l.msg("OPC Fledged exit");
                }
                catch (Exception e) {
                    l.err("Exception <{0}> -- execution terminated", e.ToString());
                }
                catch {
                    l.err("Unknown exception -- execution terminated");
                }
            }
        }
 public static void Main(string[] args)
 {
     using (Logger l = new Logger("Bazooka"))
     {
         try
         {
             for (int i = 0; i < args.Count(); i++)
             {
                 l.msg("Command line argument {0} is <{1}>", i, args[i]);
                 if (i > 0)
                 {
                     string[] res = args[i].Split(new[] {'='}, 2);
                     ArgList.Add(res[0], res[1]);
                     l.msg("\tRecognized as <{0}>=<{1}> key-value pair", res[0], res[1]);
                 }
             }
             var o = new HeatChangeEvent(); /// нужно чтобы сборка загрузилась
             EventsList = BaseEvent.GetEvents();
             bool found = false;
             for (int index = 0; index < EventsList.Length; index++)
             {
                 if (EventsList[index].Name == args[0])
                 {
                     l.msg("Event {0} found -- preparing parameters:", args[0]);
                     EventToPush = (CommonTypes.BaseEvent) Activator.CreateInstance(EventsList[index]);
                     // Enum all the properties
                     foreach (var prop in EventsList[index].GetProperties())
                     {
                         l.msg("\tProperty {0} {1} == {2}", prop.PropertyType.ToString(), prop.Name,
                               prop.GetValue(EventToPush, null));
                     }
                     // real processing
                     found = true;
                     break;
                 }
             }
             if (found)
             {
                 m_pushGate = new ConnectionProvider.Client();
                 m_pushGate.PushEvent(EventToPush);
                 System.Threading.Thread.Sleep(1000);
                 l.msg("Event fired>\n{0}", EventToPush.ToString());
             }
             else
             {
                 l.err("Unknown event {0}", args[0]);
             }
         }
         catch (Exception e)
         {
             l.err("Exception caught:\n{0}", e.ToString());
         }
     }
 }
        //public static Type[] EventsList;
        public static void ProcessEvent(OPCDirectReadEvent ev)
        {
            using (Logger l = new Logger("OPCDirectReader")) {
                bool foundEvent = false;
                bool foundToAddedEvent = false;
                List<int> readHsrv = new List<int>();
                for (int index = 0; index < EventsList.Length; index++) {
                    if (EventsList[index].Name == ev.EventName) {
                        for (int i = 0; i < m_Item_props.Count; i++) {
                            //InstantLogger.log(m_Item_props[i].eventId.ToString() + "  " + m_Item_props[i].eventPlcpId.ToString() + "  " + m_Item_props[i].eventPropId.ToString());
                            if (index == m_Item_props[i].eventId) {
                                //l.msg("OPC Related event found: {0}", evt.EventName);
                                foundToAddedEvent = true;
                                //processing

                                //m_Item_defs[0]
                                //InstantLogger.log(m_Item_props[i].eventId.ToString() + "  " + m_Item_props[i].eventPlcpId.ToString() + "  " + m_Item_props[i].eventPropId.ToString() + " -- " + m_Handles_srv[m_Item_props[i].eventPropId]);
                                /*for (int j = 0; j < m_Handles_srv.Length; j++)
                                {
                                    InstantLogger.log(m_Handles_srv[j].ToString());
                                }*/

                                //!!! readHsrv.Add(m_Handles_srv[m_Item_props[i].eventPropId]);
                                //int[] m_readHsrv;
                                //m_readHsrv.
                                /*int[] aE;
                                int cancelId;
                                int[] m_readHsrv = new int[];
                                m_The_grp.Read(m_readHsrv, 55667788, out cancelId, out aE);*/
                                //break;
                            }
                        }
                        foundEvent = true;
                        Program.m_pushGate.PushEvent(EventStore[index]);
                        l.msg(EventStore[index].ToString());
                        break;
                    }
                }
                int[] aE;
                int cancelId;
                if (!foundEvent)
                    l.err("Unknown event {0}", ev.EventName);
                else if (!foundToAddedEvent)
                    l.err("OPC group have no event {0}", ev.EventName);
                else {
                    l.msg("OPC Related event found and read");
                    m_The_grp.Read(readHsrv.ToArray(), 55667788, out cancelId, out aE);
                }
            }
        }
        private static void Main(string[] argv)
        {
            using (var l = new Logger("PipeCatcher"))
            {
                try
                {
                    var o = new FlexEvent("dummy"); /// нужно чтобы сборка загрузилась
                    CoreGate = new ConnectionProvider.Client();
                    var conf = ConfigurationManager.OpenExeConfiguration("");
                    var settings = conf.AppSettings.Settings;
                    var dbrlist = new List<DBReader>();
                    foreach (KeyValueConfigurationElement pipe in settings)
                    {
                        if (!pipe.Key.StartsWith("pipe")) continue;
                        foreach (KeyValueConfigurationElement kvel in settings)
                        {
                            if (kvel.Key.StartsWith("connectionString"))
                            {
                                dbrlist.Add(new DBReader(kvel.Value, pipe.Value));
                            }
                        }
                    }
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);

                    Application.Run(new Catcher(dbrlist, Application.ExecutablePath));
                }
                catch (Exception e)
                {
                    l.err("PipeCatcher.Main exception {0}", e);
                }
            }
        }
        public static void Load()
        {
            using (Logger l = new Logger("LoadMatrix")) {
                CapturedEvents = new List<CEDataFormat>();
                string[] strings;
                try {
                    strings = File.ReadAllLines(Patch);
                }
                catch {
                    strings = new string[0];
                    l.err("Cannot read the file: {0}", Patch);
                    return;
                }

                try {
                    for (int strCnt = 1; strCnt < strings.Count(); strCnt++) {
                        string[] values = strings[strCnt].Split(Separator);
                        if (values.Any()) {
                            if (values[0] != "") {
                                var capturedEvent = new CEDataFormat();
                                capturedEvent.Operation = values[0];
                                capturedEvent.CountTotal = Convertion.StrToInt64(values[1]);
                                capturedEvent.CountDayAverage = Convertion.StrToInt64(values[2]);
                                capturedEvent.CaptureTime = Convertion.StrToDateTime(values[3]);
                                capturedEvent.Comment = values[7];
                                CapturedEvents.Add(capturedEvent);
                            }
                            else {
                                var att = new AttDataFormat();
                                att.Key = values[4];
                                att.Type = values[5];
                                att.ExampleValue = values[6];
                                att.Comment = values[7];
                                CapturedEvents[CapturedEvents.Count - 1].AttList.Add(att);
                            }
                        }
                    }
                }
                catch (Exception e) {
                    l.err("Cannot read the file: {0}, bad format call exeption: {1}", Patch, e.ToString());
                    return;
                    //throw e;
                }
            }
        }
 private static void Main()
 {
     using (var l = new Logger("TransferModelOutput"))
     {
         try
         {
             var pointStyle = new NumberFormatInfo();
             pointStyle.NumberDecimalSeparator = ".";
             CoreGate = new ConnectionProvider.Client();
             var conf = ConfigurationManager.OpenExeConfiguration("");
             var settings = conf.AppSettings.Settings;
             var fex = new ConnectionProvider.FlexHelper(Convert.ToString(settings["?"].Value));
             do
             {
                 foreach (KeyValueConfigurationElement kvel in settings)
                 {
                     if (!kvel.Key.StartsWith("?"))
                     {
                         if (kvel.Value.StartsWith("i", true, null))
                         {
                             string[] imarg = kvel.Value.Substring(1).Split(':');
                             fex.AddInt(kvel.Key, rnd.Next(Convert.ToInt32(imarg[0]),
                                 Convert.ToInt32(imarg[1])));
                         }
                         else if (kvel.Value.StartsWith("#"))
                         {
                             fex.AddStr(kvel.Key, kvel.Value.Substring(1));
                         }
                         else
                         {
                             string[] marg = kvel.Value.Split(':');
                             fex.AddDbl(kvel.Key,
                                        randomFromTo(Convert.ToDouble(marg[0], pointStyle),
                                                     Convert.ToDouble(marg[1], pointStyle)));
                         }
                     }
                 }
                 fex.Fire(CoreGate);
                 l.msg("Event fired>\n{0}", fex.evt);
                 for (int i = 0; i < 3; i++)
                 {
                     Console.Write(".");
                     System.Threading.Thread.Sleep(300);
                 }
                 fex.ClearArgs();
                 Console.Write(">");
             } while ("q" != Console.ReadLine());
             Console.WriteLine("Done");
         }
         catch (Exception e)
         {
             l.err("TransferModelOutput.Main exception {0}", e);
         }
     }
 }
        public static void LoadMatrix(string path, char separator, out List<MFCMDataFull> matrixStateData)
        {
            using (Logger l = new Logger("LoadMatrix")) {
                matrixStateData = new List<MFCMDataFull>();
                string[] strings;
                try {
                    strings = File.ReadAllLines(path);
                }
                catch {
                    strings = new string[0];
                    l.err("Cannot read the file: {0}", path);
                    return;
                }

                try {
                    for (int strCnt = 0; strCnt < strings.Count(); strCnt++) {
                        string[] values = strings[strCnt].Split(separator);
                        matrixStateData.Add(new MFCMDataFull() {
                                                                   IdHeat = Convertion.StrToInt32(values[0]),
                                                                   NumberHeat = Convertion.StrToInt64(values[1]),
                                                                   CarbonMonoxideVolumePercent =
                                                                       Convertion.StrToDouble(values[2]),
                                                                   CarbonOxideVolumePercent =
                                                                       Convertion.StrToDouble(values[3]),
                                                                   HeightLanceCentimeters =
                                                                       Convertion.StrToInt32(values[4]),
                                                                   OxygenVolumeRate = Convertion.StrToDouble(values[5]),
                                                                   SteelCarbonPercent =
                                                                       Convertion.StrToDouble(values[6]),
                                                                   SteelCarbonCalculationPercent =
                                                                       Convertion.StrToDouble(values[7])
                                                               });
                    }
                }
                catch (Exception e) {
                    l.err("Cannot read the file: {0}, bad format call exeption: {1}", path, e.ToString());
                    //return;
                    throw e;
                }
            }
        }
        public static void LoadMatrix(string path, out List<MFCPData> matrixStateData)
        {
            using (Logger l = new Logger("LoadMatrix")) {
                matrixStateData = new List<MFCPData>();
                string[] strings;
                try {
                    strings = File.ReadAllLines(path);
                }
                catch {
                    strings = new string[0];
                    l.err("Cannot read the file: {0}", path);
                    return;
                }

                try {
                    for (int strCnt = 0; strCnt < strings.Count(); strCnt++) {
                        string[] values = strings[strCnt].Split(Separator);
                        matrixStateData.Add(new MFCPData() {
                                                               HeatNumber = Convertion.StrToInt64(values[0]),
                                                               TimeFromX = Convertion.StrToInt32(values[1]),
                                                               CarbonOxideIVP = Convertion.StrToDouble(values[2]),
                                                               CarbonMonoxideVP = Convertion.StrToDouble(values[3]),
                                                               CarbonOxideVP = Convertion.StrToDouble(values[4]),
                                                               SteelCarbonPercent = Convertion.StrToDouble(values[5]),
                                                               SteelCarbonPercentCalculated =
                                                                   Convertion.StrToDouble(values[6]),
                                                               HightQualityHeat = Convertion.StrToBool(values[7])
                                                           });
                    }
                }
                catch (Exception e) {
                    l.err("Cannot read the file: {0}, bad format call exeption: {1}", path, e.ToString());
                    //return;
                    throw e;
                }
            }
        }
Пример #9
0
 public void CustomOnEvent(BaseEvent newEvent)
 {
     using (var l = new Logger("ConnectionProvider.PrimaryListener.EventProc")) {
         if (Client.protectedMode) {
             try {
                 m_EventListener.OnEvent(newEvent);
             }
             catch (Exception e) {
                 l.err("Event {0} exception {1}::{2} returned:\n{3} ", newEvent.ToString(), e.Source,
                       e.TargetSite, e.Message);
             }
         }
         else
             m_EventListener.OnEvent(newEvent);
     }
 }
        public void OnEvent(BaseEvent evt)
        {
            using (var l = new Logger("Listener")) {
                if (evt is HeatChangeEvent) {
                    var hce = evt as HeatChangeEvent;
                    if (hce.HeatNumber != CurrentHeatNumber) {
                        CurrentHeatNumber = hce.HeatNumber;
                        Program.Reset();
                    }
                }

                if (evt is LanceEvent) {
                    var le = evt as LanceEvent;
                    Program.LancePosition = le.LanceHeight;
                }

                if (evt is SublanceTemperatureEvent) {
                    var ste = evt as SublanceTemperatureEvent;

                    //Program.WaitSublanceData.Enabled = false;

                    const int maxT = 1770;
                    const int minT = 1550;
                    if ((ste.SublanceTemperature < maxT) && (ste.SublanceTemperature > minT)) {
                        Program.WaitSublanceData.Enabled = false;
                        Program.Data.CurrentT = ste.SublanceTemperature;

                        Program.Data.CurrentC = Program.FixedCalcCarbone;
                        l.msg("Calc carbone = {0}", Program.FixedCalcCarbone);

                        l.msg("SublanceTemperature = " + ste.SublanceTemperature);

                        Program.IsUncorrectMetering = false;

                        Program.Iterator();
                    }
                    else {
                        if (ste.SublanceTemperature == 1111)
                            Program.IsUncorrectMetering = false;
                        else {
                            Program.IsUncorrectMetering = true;
                            l.err("Uncorrect temperature data = " + ste.SublanceTemperature);
                        }
                    }
                }
                if (evt is SublanceCEvent) {
                    var sce = evt as SublanceCEvent;
                    //Program.WaitSublanceData.Enabled = false;
                    //Program.Data.CurrentC = sce.C;
                    //l.msg("sce.C = " + sce.C);
                    Program.Iterator();
                }
                if (evt is BlowingEvent) {
                    var be = evt as BlowingEvent;
                    Program.CurrentOxygen = be.O2TotalVol;
                    CurrentOxigen = be.O2TotalVol;

                    Program.Iterator();
                }
                if (evt is SublanceStartEvent) {
                    var sse = evt as SublanceStartEvent;
                    if (sse.SublanceStartFlag == 1) {
                        l.msg("Sublance begin metering");
                        const int uvm = 3;
                        if (Program.LanceMode == uvm) {
                            Program.WaitSublanceData.Interval = Program.MeteringWaitTimeUVM*1000;
                            Program.WaitSublanceData.Enabled = true;
                        }
                        else {
                            Program.WaitSublanceData.Interval = Program.MeteringWaitTimeManual*1000;
                            Program.WaitSublanceData.Enabled = true;
                        }
                    }
                    if (sse.SublanceStartFlag == 0) // sublance end metering
                    {
                        if (!Program.IsAfterMetering) {
                            Program.IsAfterMetering = true;
                            Program.MeteringOxygen = CurrentOxigen;
                        }
                    }
                }
                if (evt is ModeLanceEvent) {
                    var mle = evt as ModeLanceEvent;
                    Program.LanceMode = mle.LanceMode;
                }
                if (evt is CalculatedCarboneEvent) {
                    var cce = evt as CalculatedCarboneEvent;
                    //Program.CurrentCalcCarbone = cce.CarbonePercent;
                }
                if (evt is FixDataMfactorModelEvent) {
                    //Program.FixedCalcCarbone = Program.CurrentCalcCarbone;
                }

                if (evt is FlexEvent) {
                    var fxe = evt as FlexEvent;
                    if (fxe.Operation.StartsWith("ConverterUI.TargetValues")) {
                        var key = "C";
                        l.msg(fxe.ToString());
                        try {
                            Program.Data.TargetC = (double) fxe.Arguments[key];
                            //Program.Data.CurrentC = (double)fxe.Arguments[key];
                        }
                        catch (Exception e) {
                            l.err("ConverterUI.TargetValues - {1} : \n{0}", e.ToString(), key);
                        }

                        key = "T";
                        try {
                            Program.Data.TargetT = (int) fxe.Arguments[key];
                        }
                        catch (Exception e) {
                            l.err("ConverterUI.TargetValues - {1} : \n{0}", e.ToString(), key);
                        }

                        key = "TuMin";
                        try {
                            Program.Data.TargetTuMin = (int)fxe.Arguments[key];
                        }
                        catch (Exception e) {
                            l.err("ConverterUI.TargetValues - {1} : \n{0}", e.ToString(), key);
                        }

                        key = "TuMax";
                        try {
                            Program.Data.TargetTuMax = (int)fxe.Arguments[key];
                        }
                        catch (Exception e) {
                            l.err("ConverterUI.TargetValues - {1} : \n{0}", e.ToString(), key);
                        }
                    }
                    if (fxe.Operation.StartsWith("ConverterUI.RBBAccept")) {
                        var key = "SId";
                        l.msg(fxe.ToString());
                        try {
                            //if (Program.SidB == (Guid)fxe.Arguments[key])
                            //{
                            key = "AutomaticStop";
                            Program.AutomaticStop = (bool) fxe.Arguments[key];
                            if (!Program.IsActualOxygen) {
                                Program.EndBlowingOxygen = Program.CorrectionOxyT + Program.CurrentOxygen;
                                Program.IsActualOxygen = true;
                            }

                            key = "EndNow";
                            if ((bool) fxe.Arguments[key])
                                Program.EndNowHandler();
                            else
                                Program.EndMeteringAccept();

                            //key = "EndBlowingOxygen";
                            //Program.EndBlowingOxygen = (int) fxe.Arguments[key];
                            //}
                        }
                        catch (Exception e) {
                            l.err("ConverterUI.RBBAccept - {1} : \n{0}", e.ToString(), key);
                        }
                    }

                    if (fxe.Operation.StartsWith("CarbonSwitcher.Result")) {
                        var key = "C";
                        //InstantLogger.msg(fxe.ToString());
                        try {
                            //Carbon = (double)fxe.Arguments[key];
                            Program.CurrentCalcCarbone = (double) fxe.Arguments[key];
                        }
                        catch (Exception e) {
                            InstantLogger.err("CarbonSwitcher.Result - {1} : \n{0}", e.ToString(), key);
                        }
                    }

                    if (fxe.Operation.StartsWith("CarbonSwitcher.DataFix")) {
                        l.msg(fxe.ToString());
                        Program.FixedCalcCarbone = Program.CurrentCalcCarbone;
                    }

                    if (fxe.Operation.StartsWith("SQL.Corrections")) {
                        var fex = new FlexHelper(fxe);
                        if (fex.GetStr(Implements.DBFlex.ArgCommandName) == "GetScheme") {
                            if (fex.GetStr(Implements.DBFlex.ArgErrorCodeName) == "S_OK") {
                                Program.MatrixT = Program.LoadMatrixTFromFlex(Program.MatrixTDescription, fex);
                            }
                        }
                    }
                }
            }
        }
        public void OnEvent(BaseEvent evt)
        {
            using (var l = new Logger("Listener")) {
                if (evt is FlexEvent) {
                    var fxe = evt as FlexEvent;
                    if (fxe.Operation.StartsWith("Charge5.PatternNames")) {
                        l.msg(fxe.ToString());
                        var patternList = new List<string>();
                        try {
                            foreach (var argument in fxe.Arguments)
                                patternList.Add((string) argument.Value);
                            Pointer.PMainWindow.Dispatcher.Invoke(
                                new Action(delegate() { Pointer.PMainWindow.cbPattern.ItemsSource = patternList; }));
                            if (Pointer.PPatternEditor != null) {
                                Pointer.PPatternEditor.Dispatcher.Invoke(new Action(delegate() {
                                                                                        Pointer.PPatternEditor.
                                                                                            lstPatterns.ItemsSource =
                                                                                            patternList;
                                                                                        Pointer.PPatternEditor.
                                                                                            ConsolePush(fxe.ToString());
                                                                                    }));
                            }
                        }
                        catch (Exception e) {
                            l.err("Charge5.PatternNames: \n{0}", e.ToString());
                        }
                    }

                    if (fxe.Operation.StartsWith("Charge5.RespLoadPattern")) {
                        l.msg(fxe.ToString());
                        try {
                            if ((bool) fxe.Arguments["Loaded"]) {
                                Pointer.PMainWindow.Dispatcher.Invoke(new Action(delegate() {
                                                                                     Pointer.PMainWindow.lblPattern.
                                                                                         Content =
                                                                                         "паттерн успешно загружен";
                                                                                     Pointer.PMainWindow.lblPattern.
                                                                                         Background =
                                                                                         new SolidColorBrush(
                                                                                             Color.FromArgb(0, 0, 0, 0));
                                                                                 }));
                            }
                            else {
                                Pointer.PMainWindow.Dispatcher.Invoke(new Action(delegate() {
                                                                                     Pointer.PMainWindow.lblPattern.
                                                                                         Content =
                                                                                         "Ошибка загрузки паттерна";
                                                                                     Pointer.PMainWindow.lblPattern.
                                                                                         Background =
                                                                                         new SolidColorBrush(
                                                                                             Color.FromArgb(127, 255, 0,
                                                                                                            0));
                                                                                 }));
                            }
                        }
                        catch (Exception e) {
                            l.err("Charge5.RespLoadPattern: \n{0}", e.ToString());
                        }
                    }

                    if (fxe.Operation.StartsWith("Charge5.ResultCalc")) {
                        l.msg(fxe.ToString());
                        try {
                            Pointer.PMainWindow.Dispatcher.Invoke(new Action(delegate() {
                                                                                 if ((bool) fxe.Arguments["IsFound"]) {
                                                                                     Pointer.PMainWindow.lblMDlm.Content
                                                                                         =
                                                                                         fxe.Arguments["MDlm"].ToString();
                                                                                     Pointer.PMainWindow.lblMDlms.
                                                                                         Content =
                                                                                         fxe.Arguments["MDlms"].ToString
                                                                                             ();
                                                                                     Pointer.PMainWindow.lblMFom.Content
                                                                                         =
                                                                                         fxe.Arguments["MFom"].ToString();
                                                                                     Pointer.PMainWindow.lblMHi.Content
                                                                                         =
                                                                                         fxe.Arguments["MHi"].ToString();
                                                                                     Pointer.PMainWindow.lblMLi.Content
                                                                                         =
                                                                                         fxe.Arguments["MLi"].ToString();
                                                                                     Pointer.PMainWindow.lblMSc.Content
                                                                                         =
                                                                                         fxe.Arguments["MSc"].ToString();
                                                                                     Pointer.PMainWindow.lblStatus.
                                                                                         Content = "Расчет выполнен ...";
                                                                                     Pointer.PMainWindow.lblStatus.
                                                                                         Background =
                                                                                         new SolidColorBrush(
                                                                                             Color.FromArgb(127, 0, 100,
                                                                                                            0));
                                                                                 }
                                                                                 else {
                                                                                     Pointer.PMainWindow.lblStatus.
                                                                                         Content =
                                                                                         "Входные значения в таблицах не найдены";
                                                                                     Pointer.PMainWindow.lblStatus.
                                                                                         Background =
                                                                                         new SolidColorBrush(
                                                                                             Color.FromArgb(127, 255, 0,
                                                                                                            0));
                                                                                 }
                                                                             }));
                        }
                        catch (Exception e) {
                            l.err("Charge5.ResultCalc: \n{0}", e.ToString());
                        }
                    }

                    if (fxe.Operation.StartsWith("Charge5.Tables")) {
                        l.msg(fxe.ToString());
                        var patternList = new List<string>();
                        try {
                            if (Pointer.PPatternEditor != null) {
                                Pointer.PPatternEditor.Dispatcher.Invoke(new Action(delegate() {
                                                                                        Pointer.PPatternEditor.
                                                                                            ConsolePush(fxe.ToString());
                                                                                        Pointer.PPatternEditor.
                                                                                            StatusChange(
                                                                                                "Получен паттерн " +
                                                                                                fxe.Operation.Split('.')
                                                                                                    .Last());
                                                                                        Charge5Classes.
                                                                                            CSVTP_FlexEventConverter.
                                                                                            UnpackFromFlex(
                                                                                                fxe,
                                                                                                ref
                                                                                                    Pointer.
                                                                                                    PPatternEditor.
                                                                                                    InitTbl,
                                                                                                ref
                                                                                                    Pointer.
                                                                                                    PPatternEditor.
                                                                                                    Tables,
                                                                                                ref
                                                                                                    Pointer.
                                                                                                    PPatternEditor.
                                                                                                    PatternLoadedName
                                                                                            );
                                                                                        Pointer.PPatternEditor.
                                                                                            ConsolePush(
                                                                                                "Паттерн распакован");
                                                                                        Pointer.PPatternEditor.
                                                                                            DisplayPattern();
                                                                                        Pointer.PPatternEditor.
                                                                                            ConsolePush(
                                                                                                "Паттерн визуализирован");
                                                                                        Pointer.PPatternEditor.btnSave.
                                                                                            IsEnabled = true;
                                                                                    }));
                            }
                        }
                        catch (Exception e) {
                            l.err("Charge5.PatternNames: \n{0}", e.ToString());
                        }
                    }

                    if (fxe.Operation.StartsWith("Charge5.SavePatternResp")) {
                        l.msg(fxe.ToString());
                        var patternList = new List<string>();
                        try {
                            if (Pointer.PPatternEditor != null) {
                                Pointer.PPatternEditor.Dispatcher.Invoke(new Action(delegate() {
                                                                                        Pointer.PPatternEditor.
                                                                                            ConsolePush(fxe.ToString());
                                                                                        if (
                                                                                            (bool)
                                                                                            fxe.Arguments["Saved"]) {
                                                                                            Pointer.PPatternEditor.
                                                                                                StatusChange(
                                                                                                    "Паттер успешно сохранен");
                                                                                            Requester.ReqPatternNames(
                                                                                                Requester.MainGate);
                                                                                            Pointer.PPatternEditor.
                                                                                                ConsolePush(
                                                                                                    "Обновление списка паттернов...");
                                                                                        }
                                                                                        else {
                                                                                            Pointer.PPatternEditor.
                                                                                                StatusChange(
                                                                                                    "Ошбка сохранения паттерна");
                                                                                            Requester.ReqPatternNames(
                                                                                                Requester.MainGate);
                                                                                            Pointer.PPatternEditor.
                                                                                                ConsolePush(
                                                                                                    "Обновление списка паттернов...");
                                                                                        }
                                                                                    }));
                            }
                        }
                        catch (Exception e) {
                            l.err("Charge5.PatternNames: \n{0}", e.ToString());
                        }
                    }

                    if (fxe.Operation.StartsWith("Charge5.RemoovePatternResp")) {
                        l.msg(fxe.ToString());
                        var patternList = new List<string>();
                        try {
                            if (Pointer.PPatternEditor != null) {
                                Pointer.PPatternEditor.Dispatcher.Invoke(new Action(delegate() {
                                                                                        Pointer.PPatternEditor.
                                                                                            ConsolePush(fxe.ToString());
                                                                                        if (
                                                                                            (bool)
                                                                                            fxe.Arguments["Remooved"]) {
                                                                                            Pointer.PPatternEditor.
                                                                                                StatusChange(
                                                                                                    "Паттер успешно удален");
                                                                                            Requester.ReqPatternNames(
                                                                                                Requester.MainGate);
                                                                                            Pointer.PPatternEditor.
                                                                                                ConsolePush(
                                                                                                    "Обновление списка паттернов...");
                                                                                        }
                                                                                        else {
                                                                                            Pointer.PPatternEditor.
                                                                                                StatusChange(
                                                                                                    "Ошбка удаления паттерна");
                                                                                            Requester.ReqPatternNames(
                                                                                                Requester.MainGate);
                                                                                            Pointer.PPatternEditor.
                                                                                                ConsolePush(
                                                                                                    "Обновление списка паттернов...");
                                                                                        }
                                                                                    }));
                            }
                        }
                        catch (Exception e) {
                            l.err("Charge5.PatternNames: \n{0}", e.ToString());
                        }
                    }
                }
            }
        }
        public static void Iterate(HeatData heatData)
        {
            using (var l = new Logger("Iterate")) {
                var calculatedCarboneEvent = new CalculatedCarboneEvent();
                if (!TotalCarbonMassCalculated) {
                    if (
                        (heatData.IronMass > 0) &&
                        (heatData.IronCarbonPercent > 0) &&
                        (heatData.ScrapMass > 0) &&
                        (heatData.ScrapCarbonPercent > 0) &&
                        (heatData.SteelCarbonPercent > 0)
                        ) {
                        TotalCarbonMass = Decarbonater.HeatCarbonMass(
                            heatData.IronMass,
                            heatData.IronCarbonPercent,
                            heatData.ScrapMass,
                            heatData.ScrapCarbonPercent,
                            heatData.SteelCarbonPercent
                            );
                        RemainCarbonMass = TotalCarbonMass;
                        RemainCarbonPercent = GetCarbonPercent(RemainCarbonMass, heatData.IronMass,
                                                               heatData.IronCarbonPercent,
                                                               heatData.ScrapMass, heatData.ScrapCarbonPercent);
                        if ((TotalCarbonMass > 0) && (heatData.OxygenVolumeRate > 0) && HeatIsStarted) { // start heat
                            TotalCarbonMassCalculated = true;
                            l.msg("##### [TotalCarbonMassCalculated: {0}][RemainCarbonPercent]", TotalCarbonMass,
                                  RemainCarbonPercent);
                        }
                        else
                            l.msg("HeatCarbonMass returned bad result: {0}", TotalCarbonMass);
                    }
                    else {
                        l.err(
                            "bad data for HeatCarbonMass [IronMass: {0}][IronCarbonPercent: {1}][ScrapMass: {2}][ScrapCarbonPercent: {3}][SteelCarbonPercent: {4}]",
                            heatData.IronMass,
                            heatData.IronCarbonPercent,
                            heatData.ScrapMass,
                            heatData.ScrapCarbonPercent,
                            heatData.SteelCarbonPercent
                            );
                    }
                }
                else // if (!GasCarbonMassFinished)
                {
                    heatData.DeltaT = m_sw.ElapsedMilliseconds*0.001;
                    m_sw.Restart();

                    if (
                        (heatData.CarbonMonoxideVolumePercent > 0) &&
                        (heatData.OffgasVolumeRate > 0) &&
                        (heatData.DeltaT > 0) &&
                        (heatData.Kgasan > 0)
                        ) {
                        double GCMResult = Decarbonater.GasanCarbonMass(
                            heatData.CarbonMonoxideVolumePercent,
                            heatData.OffgasVolumeRate,
                            heatData.DeltaT,
                            heatData.Kgasan
                            );
                        if (GCMResult >= 0) {
                            if (heatData.OxygenVolumeRate > 0)
                                RemainCarbonMass -= GCMResult; //////////////////////////////
                        }
                        else
                            l.err("GasanCarbonMass return bad result: {0}", GCMResult);
                        if (
                            (RemainCarbonMass > 0) &&
                            (heatData.IronMass > 0) &&
                            (heatData.IronCarbonPercent > 0) &&
                            (heatData.ScrapMass > 0) &&
                            (heatData.ScrapCarbonPercent > 0)
                            ) {
                            RemainCarbonPercent = GetCarbonPercent(
                                RemainCarbonMass,
                                heatData.IronMass,
                                heatData.IronCarbonPercent,
                                heatData.ScrapMass,
                                heatData.ScrapCarbonPercent
                                );
                        }
                        else {
                            l.err(
                                "bad data for GetCarbonPercent [RemainCarbonMass: {0}][IronMass: {1}][IronCarbonPercent: {2}][ScrapMass: {3}][ScrapCarbonPercent: {4}]",
                                RemainCarbonMass,
                                heatData.IronMass,
                                heatData.IronCarbonPercent,
                                heatData.ScrapMass,
                                heatData.ScrapCarbonPercent
                                );
                        }
                    }
                    else {
                        l.err(
                            "bad data for GasanCarbonMass [CarbonMonoxideVolumePercent: {0}][OffgasVolumeRate: {1}][DeltaT: {2}][Kgasan: {3}]",
                            heatData.CarbonMonoxideVolumePercent,
                            heatData.OffgasVolumeRate,
                            heatData.DeltaT,
                            heatData.Kgasan
                            );
                    }
                }
                const double carbonTreshold = 0.095;
                RemainCarbonPercent = RemainCarbonPercent < carbonTreshold ? carbonTreshold : RemainCarbonPercent;
                    // ограничение углерода

                var fex2 = new ConnectionProvider.FlexHelper("OffGasDecarbonater.Result");
                fex2.AddArg("C", RemainCarbonPercent);
                fex2.Fire(Program.PushGate);
                //////////////////////////////////////////////////////////////////////
            }
        }
        public static void SaveMatrix(string path)
        {
            using (var l = new Logger("SaveMatrix")) {
                string[] strings = new string[ResultList.Count + 1];

                strings[0] = String.Format("{1}{0}{2}{0}{3}{0}{4}{0}{5}{0}{6}{0}{7}",
                                           Separator,
                                           "BeginTime",
                                           "FieredEvents",
                                           "ReceivedEvents",
                                           "LostEvents",
                                           "MaxDelayMs",
                                           "AverageDelayMs",
                                           "TotalDelayMs"
                    );

                for (int dataCnt = 0; dataCnt < ResultList.Count; dataCnt++) {
                    strings[dataCnt + 1] = String.Format("{1}{0}{2}{0}{3}{0}{4}{0}{5}{0}{6}{0}{7}",
                                                         Separator,
                                                         ResultList[dataCnt].Time,
                                                         ResultList[dataCnt].FieredEvents,
                                                         ResultList[dataCnt].ReceivedEvents,
                                                         ResultList[dataCnt].LostEvents,
                                                         ResultList[dataCnt].MaxDelayMs,
                                                         ResultList[dataCnt].AverageDelayMs,
                                                         ResultList[dataCnt].TotalDelayMs
                        );
                }
                try {
                    File.WriteAllLines(path, strings);
                }
                catch (Exception e) {
                    l.err("Cannot write the file: {0}, call exeption: {1}", path, e.ToString());
                    return;
                    //throw;
                }
            }
        }
        public OpcConnector(string progId, string opcDestination, string opcAddressFmt, int opcConvSchema = 0,
            int reqUpdateRate_ms = 500)
        {
            using (Logger l = new Logger("OpcConnector")) {
                string plcName = "NO-PLC";
                m_The_srv = new OpcServer();
                m_The_srv.Connect(progId);
                Thread.Sleep(500); // we are faster then some servers!

                // add our only working group
                m_The_grp = m_The_srv.AddGroup(opcDestination + "-items", false, reqUpdateRate_ms);

                // add all the items and save server handles
                int itemCounter = 0;

                EventsList = BaseEvent.GetEvents();
                for (int eventCounter = 0; eventCounter < EventsList.Length; eventCounter++) {
                    var heatEvent = EventsList[eventCounter];
                    l.msg(heatEvent.Name); // название события
                    EventStore.Add((CommonTypes.BaseEvent) Activator.CreateInstance(heatEvent));
                    // создаем экземпляр события
                    int plcpIndex = -1;
                    bool opcRelated = false;
                    for (int i = 0; i < heatEvent.GetCustomAttributes(false).Length; i++) {
                        object x = heatEvent.GetCustomAttributes(false)[i];
                        if (x.GetType().Name == "PLCGroup") {
                            PLCGroup p = (PLCGroup) x;
                            if (p.Destination == opcDestination) {
                                plcName = p.Location;
                                l.msg("     {0} ==>> {1}", p.Location, p.Destination);
                                opcRelated = true;
                                break;
                            }
                        }
                    }
                    if (!opcRelated) continue;
                    for (int propertyCounter = 0; propertyCounter < heatEvent.GetProperties().Length; propertyCounter++) {
                        var prop = heatEvent.GetProperties()[propertyCounter];
                        object first = null;
                        for (int index = 0; index < prop.GetCustomAttributes(false).Length; index++) {
                            object x = prop.GetCustomAttributes(false)[index];
                            if (x.GetType().Name == "PLCPoint") {
                                plcpIndex = index;
                                first = x;
                                break;
                            }
                        }
                        var plcp = (PLCPoint) first;
                        if (plcp == null) continue;
                        string s = string.Format(opcAddressFmt, plcName, cnv(plcp.Location, opcConvSchema));
                        // add new OPC Item using itemCounter as client handle
                        m_Item_defs.Add(new OPCItemDef(s, true, itemCounter, VarEnum.VT_EMPTY));
                        m_Item_props.Add(new FledgedItemDef(eventCounter, propertyCounter, plcpIndex));
                        l.msg("{0}:  {1}", itemCounter, s);
                        itemCounter++;
                    }
                    if (itemCounter >= maxItemCount) break;
                }
                l.msg("Counter is {0}", itemCounter);
                if (itemCounter == 0) throw new Exception("No items found");
                // Validate Items (ignoring BLOBs
                OPCItemResult[] rItm;
                m_The_grp.ValidateItems(m_Item_defs.ToArray(), false, out rItm);
                if (rItm == null) throw new Exception("OPC ValidateItems: -- system error: arrRes is null");
                List<int> itemExclude = new List<int>();
                for (int i = 0; i < itemCounter; i++) {
                    if (HRESULTS.Failed(rItm[i].Error)) {
                        l.err(
                            "Error 0x{1:x} while adding item {0} -- item EXCLUDED from monitoring",
                            i, rItm[i].Error);
                        itemExclude.Add(i);
                    }
                }
                if (itemCounter == itemExclude.Count) throw new Exception("No items passed validation");
                // Exclude invalid items
                // Add Items
                m_The_grp.AddItems(m_Item_defs.ToArray(), out rItm);
                if (rItm == null) return;
                for (int i = 0; i < itemCounter; i++) {
                    if (HRESULTS.Failed(rItm[i].Error))
                        rItm[i].HandleServer = -1;
                }

                m_Handles_srv = new int[itemCounter];
                for (int i = 0; i < itemCounter; i++)
                    m_Handles_srv[i] = rItm[i].HandleServer;
                //m_The_grp.WriteCompleted += TheGrpWriteComplete;

                int cancelId;
                int[] aE;
                //  l.msg("start read");
                m_The_grp.SetEnable(true);
                m_The_grp.Active = true;
                m_The_grp.DataChanged += new DataChangeEventHandler(this.TheGrpDataChange);
                m_The_grp.ReadCompleted += new ReadCompleteEventHandler(this.TheGrpReadComplete);
                //m_The_grp.Read(m_Handles_srv, 55667788, out cancelId, out aE);

                //Thread.Sleep(500);
                // l.msg("end read");
            }
        }
        public void OnEvent(BaseEvent newEvent)
        {
            // InstantLogger.log(newEvent.ToString(), "Received", InstantLogger.TypeMessage.error);
            using (var l = new Logger("Listener")) {
                if (newEvent is FlexEvent) {
                    var fxe = newEvent as FlexEvent;
                    if (fxe.Operation.StartsWith("PipeCatcher.Call.PCK_DATA.PGET_WGHIRON1")) {
                        if ((string) fxe.Arguments["SHEATNO"] ==
                            Convert.ToString(HeatNumberToLong(CIterator.CurrentHeatResult.NumberHeat))) {
                            l.msg("Iron Correction from Pipe: {0}\n", fxe.Arguments["NWGH_NETTO"]);
                            m_lastHotIronMass = Convert.ToDouble(fxe.Arguments["NWGH_NETTO"])*1000;
                        }
                        else {
                            l.msg(
                                "Iron Correction from Pipe: wrong heat number - expected {0} found {1}\n",
                                CIterator.CurrentHeatResult.NumberHeat, fxe.Arguments["SHEATNO"]
                                );
                        }
                    }
                }

                if (newEvent is HeatChangeEvent) {
                    var heatChangeEvent = newEvent as HeatChangeEvent;

                    if (CIterator.FirstHeating) {
                        CIterator.Reset();
                        l.msg("Start First Heating\n");
                    }
                    else {
                        CIterator.Reset();
                        l.msg("Reset Heating\n");
                    }

                    CIterator.CurrentHeatResult.NumberHeat = heatChangeEvent.HeatNumber;
                    l.msg("Number Heat: {0}\n", CIterator.CurrentHeatResult.NumberHeat);
                }
                if (newEvent is visSpectrluksEvent) // углерод со спектролюкса
                {
                    var vse = newEvent as visSpectrluksEvent;
                    CIterator.AddCarbonToQueue(HeatNumberToShort(vse.HeatNumber), vse.C);
                }
                if (newEvent is ScrapEvent) {
                    var scrapEvent = newEvent as ScrapEvent;
                    if (scrapEvent.ConverterNumber == Program.ConverterNumber) {
                        CIterator.DataCurrentHeat.ScrapMass = scrapEvent.TotalWeight;
                        m_lastScrapMass = scrapEvent.TotalWeight;
                        l.msg("Scrap mass: {0}\n", CIterator.DataCurrentHeat.ScrapMass);
                    }
                }
                if (newEvent is MixerAnalysisEvent) {
                    var mixerAnalysisEvent = newEvent as MixerAnalysisEvent;
                    CIterator.DataCurrentHeat.IronCarbonPercent = mixerAnalysisEvent.C;
                    l.msg("Iron carbon Percent: {0}\n", CIterator.DataCurrentHeat.IronCarbonPercent);
                    if (CIterator.DataCurrentHeat.IronCarbonPercent <= 0) {
                        CIterator.DataCurrentHeat.IronCarbonPercent = 4.1133;
                        l.err("Iron carbon Percent is bad, default value: {0}\n",
                              CIterator.DataCurrentHeat.IronCarbonPercent);
                    }
                }
                if (newEvent is HotMetalLadleEvent) {
                    var hotMetalLadleEvent = newEvent as HotMetalLadleEvent;
                    if (hotMetalLadleEvent.ConverterNumber == Program.ConverterNumber) {
                        CIterator.DataCurrentHeat.IronMass = hotMetalLadleEvent.HotMetalTotalWeight;
                        l.msg("Iron mass: {0}\n", CIterator.DataCurrentHeat.IronMass);
                        if (CIterator.DataCurrentHeat.IronMass <= 0) {
                            CIterator.DataCurrentHeat.IronMass = 300000.1133;
                            l.err("Iron mass is bad, default value: {0}\n", CIterator.DataCurrentHeat.IronMass);
                        }
                    }
                }
                if (newEvent is LanceEvent) {
                    var lanceEvent = newEvent as LanceEvent;
                    CIterator.DataSmoothCurrent.OxygenVolumeRate.Add(lanceEvent.O2Flow);
                    //l.msg("Oxygen volume rate: {0}", lanceEvent.O2Flow);
                    CIterator.DataSmoothCurrent.OxygenVolumeCurrent.Add(lanceEvent.O2TotalVol);
                    //l.msg("Oxygen volume current: {0}", lanceEvent.O2TotalVol);
                    CIterator.DataSmoothCurrent.HeightLanceCentimeters.Add((double) lanceEvent.LanceHeight);
                    CIterator.CalculateLanceSpeed(lanceEvent.LanceHeight);
                        // фиксация данных по скорости и положению фурмы для старта многофакторной модели
                    //l.msg("Height lance: {0}", lanceEvent.LanceHeight);

                    if (m_lanceHeigth != lanceEvent.LanceHeight) {
                        CIterator.Iterate(CIterator.DataCurrentHeat);
                        m_lanceHeigth = lanceEvent.LanceHeight;
                    }
                }
                if (newEvent is OffGasAnalysisEvent) {
                    var offGasAnalysisEvent = newEvent as OffGasAnalysisEvent;
                    CIterator.DataSmoothCurrent.CarbonMonoxideVolumePercentPrevious.Add(
                        m_carbonMonoxideVolumePercentPrevious);
                    m_carbonMonoxideVolumePercentPrevious = offGasAnalysisEvent.CO;
                    CIterator.DataSmoothCurrent.CarbonOxideVolumePercentPrevious.Add(m_carbonOxideVolumePercentPrevious);
                    m_carbonOxideVolumePercentPrevious = offGasAnalysisEvent.CO2;
                    CIterator.DataSmoothCurrent.CarbonMonoxideVolumePercent.Add(offGasAnalysisEvent.CO);
                    CIterator.DataSmoothCurrent.CarbonOxideVolumePercent.Add(offGasAnalysisEvent.CO2);
                }
                if (newEvent is OffGasEvent) {
                    var offGasEvent = newEvent as OffGasEvent;
                    CIterator.DataSmoothCurrent.OffgasVolumeRate.Add(offGasEvent.OffGasFlow);
                    CIterator.DataCurrentHeat = CIterator.DataSmoothCurrent.GetHeatData(CIterator.DataCurrentHeat,
                                                                                        CIterator.PeriodSec);
                    CIterator.DataCurrentHeat.IronMass = m_lastHotIronMass;
                    CIterator.DataCurrentHeat.ScrapMass = m_lastScrapMass;
                    //CIterator.Iterate(CIterator.DataCurrentHeat);
                    //l.msg("Iterate");
                    /*l.msg("[Heat number: {0}][Carbone calculation percent: {1}][Carbone calculation mass: {2}]",
                        CIterator.CurrentHeatResult.NumberHeat,
                        CIterator.RemainCarbonPercent,
                        CIterator.RemainCarbonMass
                        );*/
                }
                if (newEvent is BlowingEvent) {
                    //var blowingEvent = newEvent as BlowingEvent;
                    //CIterator.Iterate(CIterator.DataCurrentHeat);
                    //l.msg("Iterate");
                    //l.msg("[Heat number: {0}][Carbone calculation percent: {1}][Carbone calculation mass: {2}]",
                    //    CIterator.CurrentHeatResult.NumberHeat,
                    //    CIterator.RemainCarbonPercent,
                    //    CIterator.RemainCarbonMass
                    //    );
                }
            }
        }
        public void OnEvent(BaseEvent evt)
        {
            using (var l = new Logger("SublanceGenerator Listener")) {
                if (evt is LanceEvent) {
                    var le = evt as LanceEvent;
                    Iterator.Oxigen.Add(le.O2TotalVol);
                    Iterator.Iterate();
                }
                if (evt is OffGasAnalysisEvent) {
                    var ogae = evt as OffGasAnalysisEvent;
                    Iterator.CarbonMonoxide.Add(ogae.CO);
                    Iterator.Iterate();
                }
                if (evt is HeatChangeEvent) {
                    var hce = evt as HeatChangeEvent;
                    if (Iterator.HeatNumber != hce.HeatNumber) {
                        l.msg("Heat Changed. New Heat ID: {0}", hce.HeatNumber);
                        Iterator.Renit();
                        Iterator.HeatNumber = hce.HeatNumber;
                    }
                    else
                        l.msg("Heat No Changed. Heat ID: {0}", hce.HeatNumber);
                }
                if (evt is CalculatedCarboneEvent) {
                    var cce = evt as CalculatedCarboneEvent;
                    //if (Iterator.Ck != cce.CarbonePercent)
                    //{
                    //    //Console.WriteLine("Ck = " + Iterator.Ck);
                    //    Iterator.Ck = cce.CarbonePercent;
                    //    Iterator.Iterate(); ///!!!
                    //}
                }
                if (evt is ModeLanceEvent) {
                    var mle = evt as ModeLanceEvent;
                    l.msg("Lance mode changed {0}, O2 mode {1}", mle.LanceMode, mle.O2FlowMode);
                    if (mle.LanceMode == mle.O2FlowMode)
                        Iterator.LanceMod = mle.LanceMode;
                    else
                        Iterator.LanceMod = -1;
                }
                if (evt is SublanceStartEvent) {
                    var sse = evt as SublanceStartEvent;
                    if (sse.SublanceStartFlag == 1)
                        l.msg("Sublance begin metering");
                    if (sse.SublanceStartFlag == 0) {
                        var str = String.Format("Receive end metering signal\n");

                        if (Iterator.IsBeganMetering) {
                            //Iterator.EndMetering();
                            //Iterator.BlowingEndRequest();
                            Iterator.EndMeteringAlow = true;
                            if (Iterator.EndMeteringAccept) {
                                Iterator.EndMetering();

                                str += String.Format("Sublance end metering");
                            }
                        }
                        l.msg(str);
                    }
                }
                //if (evt is MeteringCounterEvent)
                //{
                //    var mce = evt as MeteringCounterEvent;
                //    if (mce.Cnt != Iterator.MeteringCounter)
                //    {
                //        Iterator.MeteringCounter = mce.Cnt;
                //        var str = String.Format("Metering counter changed");
                //        if (Iterator.IsBeganMetering)
                //        {
                //            Iterator.EndMetering();
                //            str += String.Format("Sublance end metering of Metering counter");
                //        }
                //        l.msg(str);
                //    }
                //}
                if (evt is FlexEvent) {
                    var fxe = evt as FlexEvent;
                    if (fxe.Operation.StartsWith("PipeCatcher.Call.PCK_DATA.PGET_WGHIRON1")) {
                        if ((string) fxe.Arguments["SHEATNO"] == Convert.ToString(HeatNumberToLong(Iterator.HeatNumber))) {
                            l.msg(fxe.ToString());
                            //l.msg("Iron Correction from Pipe: {0}\n", fxe.Arguments["NWGH_NETTO"]);
                            Iterator.HotMetallMass = Convert.ToDouble(fxe.Arguments["NWGH_NETTO"]);
                        }
                        else {
                            l.msg(
                                "Iron Correction from Pipe: wrong heat number - expected {0} found {1}",
                                HeatNumberToLong(Iterator.HeatNumber), fxe.Arguments["SHEATNO"]
                                );
                        }
                    }
                    if (fxe.Operation.StartsWith("PipeCatcher.Call.PCK_DATA.PGET_XIMIRON")) {
                        if ((string) fxe.Arguments["HEAT_NO"] == Convert.ToString(HeatNumberToLong(Iterator.HeatNumber))) {
                            l.msg(fxe.ToString());
                            Iterator.HotMetallMass = Convert.ToDouble(fxe.Arguments["HM_WEIGHT"])*0.001;
                        }
                        else {
                            l.msg(
                                "Iron Correction from Pipe: wrong heat number - expected {0} found {1}",
                                HeatNumberToLong(Iterator.HeatNumber), fxe.Arguments["HEAT_NO"]
                                );
                        }
                    }
                    if (fxe.Operation.StartsWith("ConverterUI.TargetValues")) {
                        var key = "C";
                        l.msg(fxe.ToString());
                        if (fxe.Arguments.ContainsKey(key)) {
                            try {
                                Iterator.TargetCk = (double) fxe.Arguments[key];
                            }
                            catch (Exception e) {
                                l.err("ConverterUI.TargetValues - {1} : \n{0}", e.ToString(), key);
                            }
                        }
                        key = "Cu";
                        if (fxe.Arguments.ContainsKey(key)) {
                            try {
                                Iterator.TargetCku = (double) fxe.Arguments[key];
                            }
                            catch (Exception e) {
                                l.err("ConverterUI.TargetValues - {1} : \n{0}", e.ToString(), key);
                            }
                        }
                    }
                    if (fxe.Operation.StartsWith("ConverterUI.ZondAccept")) {
                        //var key = "SId";
                        l.msg(fxe.ToString());
                        try {
                            //if (Iterator.SIdK == (Guid)fxe.Arguments[key])
                            //{
                            Iterator.BeginMetering();
                            //}
                        }
                        catch (Exception e) {
                            l.err("ConverterUI.ZondAccept - {0}", e.ToString());
                        }
                    }
                    if (fxe.Operation.StartsWith("CorrectionCT.EndMeteringAccept")) {
                        l.msg(fxe.ToString());
                        Iterator.EndMeteringAccept = true;
                    }
                    if (fxe.Operation.StartsWith("OPC.SublanceHeigth")) {
                        var key = "Heigth";
                        //l.msg(fxe.ToString());
                        try {
                            var sublanceHeigthNow = (Int16) fxe.Arguments[key];
                            var derivative = sublanceHeigthNow - Iterator.SublanceHeigth;
                            Iterator.SublanceHeigth = (Int16) fxe.Arguments[key];
                            var sublanceRaised = Iterator.SublanceRaised(derivative, sublanceHeigthNow,
                                                                         Iterator.SublanceTreshold);
                            l.msg(
                                "derivative = {0}; sublanceHeigthNow = {1}; SublanceTreshold = {2}; sublanceRaised = {3}; EndMeteringAccept = {4}",
                                derivative, sublanceHeigthNow, Iterator.SublanceTreshold, sublanceRaised,
                                Iterator.EndMeteringAccept);

                            if (sublanceRaised) {
                                Iterator.EndMeteringAlow = true;
                                if (Iterator.EndMeteringAccept) {
                                    Iterator.EndMetering();
                                    l.msg("Sublance end metering");
                                }
                            }
                        }
                        catch (Exception e) {
                            l.err("OPC.SublanceHeigth - {1} : \n{0}", e.ToString(), key);
                        }
                    }

                    if (fxe.Operation.StartsWith("CarbonSwitcher.Result")) {
                        var key = "C";
                        //InstantLogger.msg(fxe.ToString());
                        try {
                            //Carbon = (double)fxe.Arguments[key];
                            if (Iterator.Ck != (double) fxe.Arguments[key]) {
                                //Console.WriteLine("Ck = " + Iterator.Ck);
                                Iterator.Ck = (double) fxe.Arguments[key];
                                key = "PeriodlNumber";
                                Iterator.PeriodNumber = (int) fxe.Arguments[key];
                                Iterator.Iterate(); ///!!!
                            }
                        }
                        catch (Exception e) {
                            InstantLogger.err("CarbonSwitcher.Result - {1} : \n{0}", e.ToString(), key);
                        }
                    }

                    //if (fxe.Operation.StartsWith("ConverterUI.BlowingEndResponce"))
                    //{
                    //    var key = "SId";
                    //    l.msg(fxe.ToString());
                    //    try
                    //    {
                    //        if (Iterator.SIdK == (Guid)fxe.Arguments[key])
                    //        {
                    //            //Iterator.BeginMetering();
                    //            key = "EndNow";
                    //            if ((bool)fxe.Arguments[key])
                    //            {
                    //                Iterator.DoStopBlow();
                    //                Iterator.EndMetering();
                    //            }
                    //            else
                    //            {
                    //                Iterator.EndMetering();
                    //            }
                    //        }
                    //    }
                    //    catch (Exception e)
                    //    {
                    //        l.err("ConverterUI.BlowingEndResponce - {1} : \n{0}", e.ToString(), key);
                    //    }
                    //}
                }
            }
        }
        public void OnEvent(BaseEvent newEvent)
        {
            using (var l = new Logger("FlexEventSaver")) {
                if (newEvent is LanceEvent) {
                    var lanceEvent = newEvent as LanceEvent;
                    Program.SDS.LanceHeigth.Add(lanceEvent.LanceHeight);
                    Program.SDS.OxygenRate.Add(lanceEvent.O2Flow);
                    Program.OxygenRate.Add(lanceEvent.O2Flow);
                }
                //if (newEvent is OffGasAnalysisEvent)
                //{
                //    var offGasAnalysisEvent = newEvent as OffGasAnalysisEvent;
                //    Program.SDS.H2Perc.Add(offGasAnalysisEvent.H2);
                //    Program.SDS.O2Perc.Add(offGasAnalysisEvent.O2);
                //    Program.SDS.COPerc.Add(offGasAnalysisEvent.CO);
                //    Program.SDS.CO2Perc.Add(offGasAnalysisEvent.CO2);
                //    Program.SDS.N2Perc.Add(offGasAnalysisEvent.N2);
                //    Program.SDS.ArPerc.Add(offGasAnalysisEvent.Ar);
                //}
                if (newEvent is OffGasEvent) {
                    var offGasEvent = newEvent as OffGasEvent;
                    Program.SDS.VGas.Add(offGasEvent.OffGasFlow);
                    Program.SDS.TGas.Add(offGasEvent.OffGasTemp);
                }
                if (newEvent is CalculatedCarboneEvent) {
                    var cCarbon = newEvent as CalculatedCarboneEvent;
                    //Program.SDS.CCalc.Add(cCarbon.CarbonePercent);
                }
                if (newEvent is SublanceCEvent) {
                    var sublanceCEvent = newEvent as SublanceCEvent;
                    Program.SDS.CSubLance = sublanceCEvent.C;
                }
                if (newEvent is IgnitionEvent) {
                    var ign = newEvent as IgnitionEvent;
                    Program.SDS.Ignition = ign.FusionIgnition;
                }
                if (newEvent is DecompressionOffGasEvent) {
                    var doge = newEvent as DecompressionOffGasEvent;
                    Program.SDS.Decompression.Add(doge.Decompression);
                }
                if (newEvent is O2Event) {
                    var o2e = newEvent as O2Event;
                    if (o2e.RightLanceIsSelected && !o2e.LeftLanceIsSelected) {
                        Program.SDS.QOxygenCL.Add(o2e.QOxygenRight);
                        Program.SDS.POxygenCL.Add(o2e.POxygenRight);
                        Program.SDS.TOxygenCL.Add(o2e.TOxygenRight);
                        Program.SDS.DPOxygenCL.Add(o2e.DPOxygenRight);
                    }
                    else {
                        Program.SDS.QOxygenCL.Add(o2e.QOxygenLeft);
                        Program.SDS.POxygenCL.Add(o2e.POxygenLeft);
                        Program.SDS.TOxygenCL.Add(o2e.TOxygenLeft);
                        Program.SDS.DPOxygenCL.Add(o2e.DPOxygenLeft);
                    }
                }
                if (newEvent is N2Event) {
                    var n2e = newEvent as N2Event;
                    Program.SDS.QNitrogenLanceWindow.Add(n2e.QNitrogenLanceWindow);
                    Program.SDS.QNitrogenBoiler.Add(n2e.QNitrogenBoiler);
                }
                if (newEvent is visAdditionTotalEvent) {
                    var vate = newEvent as visAdditionTotalEvent;
                    Program.SDS.RB5 = vate.RB5TotalWeight;
                    Program.SDS.RB6 = vate.RB6TotalWeight;
                    Program.SDS.RB7 = vate.RB7TotalWeight;
                    Program.SDS.RB8 = vate.RB8TotalWeight;
                    Program.SDS.RB9 = vate.RB9TotalWeight;
                    Program.SDS.RB10 = vate.RB10TotalWeight;
                    Program.SDS.RB11 = vate.RB11TotalWeight;
                    Program.SDS.RB12 = vate.RB12TotalWeight;
                }
                if (newEvent is HeatChangeEvent) {
                    var heatChangeEvent = newEvent as HeatChangeEvent;
                    if (m_lasIdHeat != heatChangeEvent.HeatNumber) {
                        Program.SaverData(Program.SDList, m_lasIdHeat);
                        m_lasIdHeat = heatChangeEvent.HeatNumber;
                        Program.Init();
                    }
                }
                if (newEvent is FlexEvent) {
                    var fxe = newEvent as FlexEvent;
                    if (fxe.Operation.StartsWith("NeuralProcessorC.Calc")) {
                        var key = "C";
                        //l.msg(fxe.ToString());
                        if (fxe.Arguments.ContainsKey(key)) {
                            try {
                                Program.SDS.NeuralC.Add((double) fxe.Arguments[key]);
                            }
                            catch (Exception e) {
                                l.err("NeuralProcessorC.Calc - {1} : \n{0}", e.ToString(), key);
                            }
                        }
                    }

                    if (fxe.Operation.StartsWith("CarbonSwitcher.Result")) {
                        var key = "C";
                        //InstantLogger.msg(fxe.ToString());
                        try {
                            //Carbon = (double)fxe.Arguments[key];
                            //Program.CurrentCalcCarbone = (double)fxe.Arguments[key];
                            Program.SDS.CCalc.Add((double) fxe.Arguments[key]);
                        }
                        catch (Exception e) {
                            InstantLogger.err("CarbonSwitcher.Result - {1} : \n{0}", e.ToString(), key);
                        }
                    }

                    if (fxe.Operation.StartsWith("UDP.OffGasAnalysisEvent")) {
                        var key = "H2";
                        try {
                            Program.SDS.H2Perc.Add((double) fxe.Arguments[key]);
                            key = "O2";
                            Program.SDS.O2Perc.Add((double) fxe.Arguments[key]);
                            key = "CO";
                            Program.SDS.COPerc.Add((double) fxe.Arguments[key]);
                            key = "CO2";
                            Program.SDS.CO2Perc.Add((double) fxe.Arguments[key]);
                            key = "N2";
                            Program.SDS.N2Perc.Add((double) fxe.Arguments[key]);
                            key = "Ar";
                            Program.SDS.ArPerc.Add((double) fxe.Arguments[key]);
                        }
                        catch (Exception e) {
                            InstantLogger.err("UDP.OffGasAnalysisEvent - {1} : \n{0}", e.ToString(), key);
                        }
                    }

                    if (fxe.Operation.StartsWith("UniversalCPlus.Result")) {
                        var fex = new FlexHelper(fxe);
                        Program.SDS.UniversalC = fex.GetDbl("C");
                    }
                }
            }
        }
Пример #18
0
        private void SendingThread()
        {
            using (var l = new Logger("ConnectionProvider.SendingThread")) {
                BaseEvent evt = null;
                var prevState = m_MainGateClient.State;
                var currState = prevState;
                while (true) {
                    bool doSleep = true;
                    if (prevState != currState) {
                        l.msg("Connection state is \"{0}\"", currState);
                        prevState = currState;
                        doSleep = false;
                    }

                    if (currState <= CommunicationState.Opened) {
                        try {
                            lock (eventsQueue) {
                                evt = eventsQueue.Count > 0 ? eventsQueue.Dequeue() : null;
                            }
                            if (evt != null) {
                                m_MainGateClient.PushEvent(evt);
                                doSleep = false;
                            }
                        }
                        catch (Exception e) {
                            l.err("proc {2} event fail\n{0}\n while processing event\n{1}", e.Message, evt,
                                  e.TargetSite.Name);
                        }
                    }
                    if (doSleep) Thread.Sleep(THREAD_SLEEP);
                    currState = m_MainGateClient.State;
                }
            }
        }
        public void OnEvent(BaseEvent newEvent)
        {
            // InstantLogger.log(newEvent.ToString(), "Received", InstantLogger.TypeMessage.error);
            using (var l = new Logger("Listener")) {
                if (newEvent is HeatChangeEvent) {
                    var heatChangeEvent = newEvent as HeatChangeEvent;

                    if (CIterator.FirstHeating) {
                        CIterator.Reset();
                        l.msg("Start First Heating");
                    }
                    else {
                        //CIterator.ResetHeating(CIterator.CurrentHeatResult); // y
                        CIterator.Reset();
                        l.msg("Reset Heating");
                    }

                    CIterator.CurrentHeatResult.NumberHeat = heatChangeEvent.HeatNumber;
                    l.msg("Number Heat: {0}", CIterator.CurrentHeatResult.NumberHeat);
                }
                //if (newEvent is SublanceCEvent) // на будущее из другого места брать углерод
                //{
                //    var sublanceCEvent = newEvent as SublanceCEvent;
                //    CIterator.CurrentHeatResult.SteelCarbonPercent = sublanceCEvent.C;
                //    l.msg("Steel carbone percent: {0}", CIterator.CurrentHeatResult.SteelCarbonPercent);
                //}
                if (newEvent is visSpectrluksEvent) // углерод со спектролюкса
                {
                    var vse = newEvent as visSpectrluksEvent;
                    CIterator.AddCarbonToQueue(HeatNumberRemooveAxcess(vse.HeatNumber), vse.C);
                }
                if (newEvent is ScrapEvent) {
                    var scrapEvent = newEvent as ScrapEvent;
                    if (scrapEvent.ConverterNumber == Program.ConverterNumber) {
                        CIterator.DataCurrentHeat.ScrapMass = scrapEvent.TotalWeight;
                        l.msg("Scrap mass: {0}", CIterator.DataCurrentHeat.ScrapMass);
                    }
                }
                if (newEvent is MixerAnalysisEvent) {
                    var mixerAnalysisEvent = newEvent as MixerAnalysisEvent;
                    CIterator.DataCurrentHeat.IronCarbonPercent = mixerAnalysisEvent.C;
                    l.msg("Iron carbon Percent: {0}", CIterator.DataCurrentHeat.IronCarbonPercent);
                    if (CIterator.DataCurrentHeat.IronCarbonPercent <= 0) {
                        CIterator.DataCurrentHeat.IronCarbonPercent = 5.1133;
                        l.err("Iron carbon Percent is bad, default value: {0}",
                              CIterator.DataCurrentHeat.IronCarbonPercent);
                    }
                }
                if (newEvent is HotMetalLadleEvent) {
                    var hotMetalLadleEvent = newEvent as HotMetalLadleEvent;
                    if (hotMetalLadleEvent.ConverterNumber == Program.ConverterNumber) {
                        CIterator.DataCurrentHeat.IronMass = hotMetalLadleEvent.HotMetalTotalWeight;
                        l.msg("Iron mass: {0}", CIterator.DataCurrentHeat.IronMass);
                        if (CIterator.DataCurrentHeat.IronMass <= 0) {
                            CIterator.DataCurrentHeat.IronMass = 300000.1133;
                            l.err("Iron mass is bad, default value: {0}", CIterator.DataCurrentHeat.IronMass);
                        }
                    }
                }
                if (newEvent is LanceEvent) {
                    var lanceEvent = newEvent as LanceEvent;
                    //CIterator.DataCurrentHeat.OxygenVolumeRate = lanceEvent.O2Flow;
                    CIterator.DataSmoothCurrent.OxygenVolumeRate.Add(lanceEvent.O2Flow);
                    l.msg("Oxygen volume rate: {0}", lanceEvent.O2Flow);
                    //CIterator.DataCurrentHeat.OxygenVolumeCurrent = lanceEvent.O2TotalVol;
                    CIterator.DataSmoothCurrent.OxygenVolumeCurrent.Add(lanceEvent.O2TotalVol);
                    l.msg("Oxygen volume current: {0}", lanceEvent.O2TotalVol);
                    //CIterator.DataCurrentHeat.HeightLanceCentimeters = lanceEvent.LanceHeight;
                    CIterator.DataSmoothCurrent.HeightLanceCentimeters.Add((double) lanceEvent.LanceHeight);
                    //CIterator.SetMaxDownLancePosition(lanceEvent.LanceHeight); // самое низкое положение за плавку для старта многофакторной модели
                    //CIterator.SmoothSecondLancePosition.Add((double)lanceEvent.LanceHeight);
                    CIterator.CalculateLanceSpeed(lanceEvent.LanceHeight);
                        // фиксация данных по скорости и положению фурмы для старта многофакторной модели
                    l.msg("Height lance: {0}", lanceEvent.LanceHeight);
                    //CIterator.MomentFixDataForMFactorModel();
                }
                if (newEvent is OffGasAnalysisEvent) {
                    var offGasAnalysisEvent = newEvent as OffGasAnalysisEvent;
                    //CIterator.DataCurrentHeat.CarbonMonoxideVolumePercentPrevious =
                    //    CIterator.DataCurrentHeat.CarbonMonoxideVolumePercent;
                    CIterator.DataSmoothCurrent.CarbonMonoxideVolumePercentPrevious.Add(
                        m_carbonMonoxideVolumePercentPrevious);
                    m_carbonMonoxideVolumePercentPrevious = offGasAnalysisEvent.CO;
                    //CIterator.DataCurrentHeat.CarbonOxideVolumePercentPrevious =
                    //    CIterator.DataCurrentHeat.CarbonOxideVolumePercent;
                    CIterator.DataSmoothCurrent.CarbonOxideVolumePercentPrevious.Add(m_carbonOxideVolumePercentPrevious);
                    m_carbonOxideVolumePercentPrevious = offGasAnalysisEvent.CO2;
                    //CIterator.DataCurrentHeat.CarbonMonoxideVolumePercent = offGasAnalysisEvent.CO;
                    CIterator.DataSmoothCurrent.CarbonMonoxideVolumePercent.Add(offGasAnalysisEvent.CO);
                    //CIterator.DataCurrentHeat.CarbonOxideVolumePercent = offGasAnalysisEvent.CO2;
                    CIterator.DataSmoothCurrent.CarbonOxideVolumePercent.Add(offGasAnalysisEvent.CO2);
                }
                if (newEvent is OffGasEvent) {
                    var offGasEvent = newEvent as OffGasEvent;
                    //CIterator.DataCurrentHeat.OffgasVolumeRate = offGasEvent.OffGasFlow;
                    CIterator.DataSmoothCurrent.OffgasVolumeRate.Add(offGasEvent.OffGasFlow);
                    CIterator.DataCurrentHeat = CIterator.DataSmoothCurrent.GetHeatData(CIterator.DataCurrentHeat,
                                                                                        CIterator.PeriodSec);
                    CIterator.Iterate(CIterator.DataCurrentHeat);
                    l.msg("Iterate");
                    l.msg("[Heat number: {0}][Carbone calculation percent: {1}][Carbone calculation mass: {2}]",
                          CIterator.CurrentHeatResult.NumberHeat,
                          CIterator.RemainCarbonPercent,
                          CIterator.RemainCarbonMass
                        );
                }
                if (newEvent is BlowingEvent) {
                    //var blowingEvent = newEvent as BlowingEvent;
                    //CIterator.Iterate(CIterator.DataCurrentHeat);
                    //l.msg("Iterate");
                    //l.msg("[Heat number: {0}][Carbone calculation percent: {1}][Carbone calculation mass: {2}]",
                    //    CIterator.CurrentHeatResult.NumberHeat,
                    //    CIterator.RemainCarbonPercent,
                    //    CIterator.RemainCarbonMass
                    //    );
                }
            }
        }
        public void CoreEventGenerator(object sender, EventArgs oEvent)
        {
            using (Logger l = new Logger("OnDataChange", ref locker)) {
                int transactionID;
                int groupHandleClient;
                int masterQuality;
                int masterError;
                OPCItemState[] sts;
                if (oEvent is DataChangeEventArgs) {
                    var dataE = oEvent as DataChangeEventArgs;
                    transactionID = dataE.transactionID;
                    groupHandleClient = dataE.groupHandleClient;
                    masterQuality = dataE.masterQuality;
                    masterError = dataE.masterError;
                    sts = dataE.sts;
                }
                else if (oEvent is ReadCompleteEventArgs) {
                    var dataE = oEvent as ReadCompleteEventArgs;
                    transactionID = dataE.transactionID;
                    groupHandleClient = dataE.groupHandleClient;
                    masterQuality = dataE.masterQuality;
                    masterError = dataE.masterError;
                    sts = dataE.sts;
                }
                else {
                    l.err("oEvent is neither DataChangeEventArgs nor ReadCompleteEventArgs");
                    return;
                }
                l.msg("gh={0} id={1} me={2} mq={3}", groupHandleClient, transactionID, masterError, masterQuality);
                List<int> relatedEventsIdList = new List<int>();
                foreach (OPCItemState s in sts) {
                    if (HRESULTS.Succeeded(s.Error)) {
                        l.msg(" ih={0} ItemID={2} >> value={1}", s.HandleClient, s.DataValue,
                              m_Item_defs.ElementAt(s.HandleClient).ItemID);
                        var _p_ = EventsList[m_Item_props[s.HandleClient].eventId].GetProperties()[
                            m_Item_props[s.HandleClient].eventPropId];
                        bool presenceFlag = false;
                        foreach (int evid in relatedEventsIdList) {
                            if (evid == m_Item_props[s.HandleClient].eventId)
                                presenceFlag = true;
                        }
                        if (!presenceFlag)
                            relatedEventsIdList.Add(m_Item_props[s.HandleClient].eventId);
                        //l.msg(_p_.PropertyType.ToString() + " --- " + s.DataValue.GetType().ToString());
                        if (_p_.PropertyType == (typeof (System.Boolean))) {
                            l.msg("boolean type");
                            var _nb_ =
                                ((PLCPoint) _p_.GetCustomAttributes(false)[m_Item_props[s.HandleClient].eventPlcpId]).
                                    BitNumber;
                            _p_.SetValue(EventStore[m_Item_props[s.HandleClient].eventId],
                                         BoolExpressions.GetBit(Convert.ToByte(s.DataValue), _nb_), null);
                            var itemID = m_Item_defs.ElementAt(s.HandleClient).ItemID;
                            if (FlagStore.ContainsKey(itemID)) FlagStore[itemID] = Convert.ToByte(s.DataValue);
                            else FlagStore.Add(itemID, Convert.ToByte(s.DataValue));
                        }
                        else if (_p_.PropertyType == (typeof (System.Int32))) {
                            l.msg("int32 type {0}", s.DataValue.GetType().ToString());
                            if (s.DataValue.GetType() == (typeof (System.Int16)))
                                _p_.SetValue(EventStore[m_Item_props[s.HandleClient].eventId],
                                             Convert.ToInt32(s.DataValue), null);
                            else {
                                Int64 itmp = Convert.ToInt64(s.DataValue);
                                UInt64 tmp = (UInt64) itmp;
                                if (itmp != -1) {
                                    if (tmp > 0xffffffff)
                                        tmp = 32000;
                                    if (tmp >= 0x7ffffff)
                                        tmp = 31999;
                                    _p_.SetValue(EventStore[m_Item_props[s.HandleClient].eventId], Convert.ToInt32(tmp),
                                                 null);
                                }
                                else
                                    _p_.SetValue(EventStore[m_Item_props[s.HandleClient].eventId], -1, null);
                            }
                        }
                        else if (_p_.PropertyType == (typeof (System.Double))) {
                            l.msg("double type");
                            _p_.SetValue(EventStore[m_Item_props[s.HandleClient].eventId], Convert.ToDouble(s.DataValue),
                                         null);
                        }
                        else if (_p_.PropertyType == (typeof (System.Char[]))) {
                            l.msg("char[]");
                            _p_.SetValue(EventStore[m_Item_props[s.HandleClient].eventId], conv(s.DataValue), null);
                        }
                        else if (_p_.PropertyType == (typeof (System.String))) {
                            l.msg("string");
                            try {
                                _p_.SetValue(EventStore[m_Item_props[s.HandleClient].eventId],
                                             convBack((byte[]) s.DataValue), null);
                            }
                            catch (Exception) {
                                _p_.SetValue(EventStore[m_Item_props[s.HandleClient].eventId], "err", null);
                                //throw;
                            }
                        }
                        else {
                            l.msg("any type");
                            try {
                                _p_.SetValue(EventStore[m_Item_props[s.HandleClient].eventId], s.DataValue, null);
                            }
                            catch (Exception) {
                                l.msg("receive data type not support", "OPCConnector function TheGrpDataChange",
                                      InstantLogger.TypeMessage.death);
                                _p_.SetValue(EventStore[m_Item_props[s.HandleClient].eventId], 0, null);
                                throw;
                            }
                        }
                    }
                    else
                        l.msg(String.Format(" ih={0}    ERROR=0x{1:x} !", s.HandleClient, s.Error));
                }
                foreach (var idReceiveEvent in relatedEventsIdList) {
                    bool isWriteble = false;
                    foreach (var prop in EventStore[idReceiveEvent].GetType().GetProperties()) {
                        foreach (object x in prop.GetCustomAttributes(false)) {
                            if (x.GetType().Name == "PLCPoint") {
                                // InstantLogger.log(prop.GetCustomAttributesData()[1].ToString());
                                if (((PLCPoint) x).IsWritable)
                                    isWriteble = true;
                            }
                        }
                    }

                    if (isWriteble) {
                        l.msg("Event: " + EventStore[idReceiveEvent].GetType().Name + "isWriteble",
                              "OPCConnectore function TheGrpDataChange",
                              InstantLogger.TypeMessage.unimportant);
                    }
                    else {
                        l.msg(EventStore[idReceiveEvent].ToString(),
                              "OPCConnectore function TheGrpDataChange",
                              InstantLogger.TypeMessage.unimportant);
                        Program.m_pushGate.PushEvent(EventStore[idReceiveEvent]);
                    }
                }
            }
        }
        public static void Save()
        {
            Directory.CreateDirectory(Dir);
            using (Logger l = new Logger("Save")) {
                var strings = new List<string>();
                strings.Add(String.Format("{1}{0}{2}{0}{3}{0}{4}{0}{5}{0}{6}{0}{7}{0}{8}",
                                          Separator,
                                          "Operation",
                                          "Count",
                                          "CountDayAverage",
                                          "LastCaptureTime",
                                          "ArgumentKey",
                                          "ArgumentType",
                                          "ExampleValue",
                                          "Comment"
                                ));

                foreach (var capturedEvent in CapturedEvents) {
                    strings.Add(String.Format("{1}{0}{2}{0}{3}{0}{4}{0}{5}{0}{6}{0}{7}{0}{8}",
                                              Separator,
                                              capturedEvent.Operation,
                                              capturedEvent.CountTotal,
                                              capturedEvent.CountDayAverage,
                                              capturedEvent.CaptureTime,
                                              "",
                                              "",
                                              "",
                                              capturedEvent.Comment
                                    ));
                    foreach (var att in capturedEvent.AttList) {
                        strings.Add(String.Format("{1}{0}{2}{0}{3}{0}{4}{0}{5}{0}{6}{0}{7}{0}{8}",
                                                  Separator,
                                                  "",
                                                  "",
                                                  "",
                                                  "",
                                                  att.Key,
                                                  att.Type,
                                                  att.ExampleValue,
                                                  att.Comment
                                        ));
                    }
                }
                try {
                    File.WriteAllLines(Patch, strings);
                    //l.msg("Data saved");
                }
                catch (Exception e) {
                    l.err("Cannot write the file: {0}, call exeption: {1}", Patch, e.ToString());
                    return;
                    //throw;
                }
            }
        }
        public void OnEvent(BaseEvent newEvent)
        {
            using (var log = new Logger("DBWriterTT"))
            {
                try
                {
                    var evtFlex = newEvent as FlexEvent;
                    if (evtFlex != null)
                    {
                        try
                        {
                            if (DbLayerTrends.Instance.Insert(evtFlex, _unitNumber))
                            {
                                log.msg(string.Format("{0}: inserted trends for {1} from {2}", newEvent.Time, newEvent.GetType().Name, _unitNumber));
                            }
                        }
                        catch (OracleException exception)
                        {
                            log.msg(string.Format("{0}: Can't inserted trends for {1}  from {2}", newEvent.Time, newEvent.GetType().Name, _unitNumber));
                            log.err(exception.ToString());
                        }
                    }
                    else
                    {

                        var evt = (ConverterBaseEvent) newEvent;
                        evt.iCnvNr = _unitNumber;
                        if ((evt is LanceEvent) ||
                            (evt is OffGasAnalysisEvent) ||
                            (evt is OffGasEvent) ||
                            (evt is BoilerWaterCoolingEvent) ||
                            (evt is SlagOutburstEvent) ||
                            (evt is IgnitionEvent) ||
                            (evt is ModeLanceEvent) ||
                            (evt is ModeVerticalPathEvent) ||
                            (evt is CalculatedCarboneEvent) ||
                            (evt is ConverterAngleEvent))
                        {

                            try
                            {
                                if (DbLayerTrends.Instance.Insert(evt))
                                {
                                    log.msg(string.Format("{0}: inserted trends for {1} from {2}", evt.Time, evt.GetType().Name, evt.iCnvNr));
                                }
                            }
                            catch (OracleException exception)
                            {
                                log.msg(string.Format("{0}: Can't inserted trends for {1}  from {2}", evt.Time,
                                                      evt.GetType().Name, evt.iCnvNr));
                                log.err(exception.ToString());
                            }
                        }

                        if ((evt is AdditionsEvent) ||
                            (evt is BlowingEvent) ||
                            (evt is ReBlowingEvent) ||
                            (evt is DeslaggingEvent) ||
                            (evt is HeatChangeEvent) ||
                            (evt is HeatingScrapEvent) ||
                            (evt is HotMetalLadleEvent) ||
                            (evt is HotMetalPouringEvent) ||
                            (evt is IgnitionEvent) ||
                            (evt is ResetO2TotalVolEvent) ||
                            (evt is ScrapChargingEvent) ||
                            (evt is ScrapEvent) ||
                            (evt is SlagBlowingEvent) ||
                            (evt is SublanceStartEvent) ||
                            (evt is SublanceCEvent) ||
                            (evt is SublanceOxidationEvent) ||
                            (evt is SublanceTemperatureEvent) ||
                            (evt is TappingEvent))
                        {
                            try
                            {
                                if (DbLayerTelegrams.Instance.Insert(evt))
                                {
                                    log.msg(string.Format("{0}: inserted telergams for {1} from {2}", evt.Time,
                                                          evt.GetType().Name, evt.iCnvNr));
                                }
                            }
                            catch (OracleException exception)
                            {
                                log.msg(string.Format("{0}: Can't inserted telergams trends for {1}  from {2}", evt.Time,
                                                      evt.GetType().Name, evt.iCnvNr));
                                log.err(exception.ToString());
                            }
                        }

                    }
                }
                catch(Exception ex)
                {
                    log.err(ex.ToString());
                }
            }
        }
        public void OnEvent(BaseEvent newEvent)
        {
            using (Logger l = new Logger("OnEvent")) {
                if (cTime.Day != DateTime.Now.Day) {
                    cTime = DateTime.Now;
                    InstantLogger.log("", "To be continued...", InstantLogger.TypeMessage.important);
                    InstantLogger.LogFileInit();
                    InstantLogger.log("", "...Continuing", InstantLogger.TypeMessage.important);
                }
                l.msg(newEvent.GetType().FullName);
                if (newEvent is OPCDirectReadEvent) {
                    OpcConnector.ProcessEvent(newEvent as OPCDirectReadEvent);
                    return;
                }
                var plcg = new PLCGroup();
                bool found = false;
                foreach (object x in newEvent.GetType().GetCustomAttributes(false)) {
                    if (x.GetType().Name == "PLCGroup") {
                        plcg = (PLCGroup) x;
                        if (plcg.Destination == opcDestination_) {
                            l.msg("    " + plcg.Location + " -- " + plcg.Destination);
                            found = true;
                            break;
                        }
                    }
                }
                if (!found) return;
                List<int> arrSrvH = new List<int>();
                List<object> arrItmV = new List<object>();

                var plcp = new PLCPoint();
                foreach (var prop in newEvent.GetType().GetProperties()) {
                    foreach (object x in prop.GetCustomAttributes(false)) {
                        if (x.GetType().Name == "PLCPoint") {
                            // InstantLogger.log(prop.GetCustomAttributesData()[1].ToString());
                            if (((PLCPoint) x).IsWritable) {
                                plcp = (PLCPoint) x;
                                var s = string.Format(opcAddressFmt_, plcg.Location,
                                                      OPCFledged.OpcConnector.cnv(plcp.Location));
                                var sb = new StringBuilder();
                                sb.AppendFormat("        " + prop.Name + " = " +
                                                prop.GetValue(newEvent, null).ToString());
                                sb.AppendFormat("\n            IsWritable = " + plcp.IsWritable.ToString());
                                sb.AppendFormat("\n            " + plcp.Location + " % " + s);
                                sb.AppendFormat("\n            " + newEvent.GetType());
                                l.msg(sb.ToString());
                                int index = 0;
                                bool eureka = false;
                                while (index < OpcConnector.m_Item_defs.Count) {
                                    OPCItemDef v = OpcConnector.m_Item_defs[index];
                                    //InstantLogger.msg("comparing <{0}> == <{1}>", v.ItemID, s);
                                    if (v.ItemID == s) {
                                        if (!v.Active)
                                            l.err("Item <{0}> is excluded from monitoring", v.ItemID);
                                        else {
                                            arrSrvH.Add(OpcConnector.m_Handles_srv[index]);
                                            l.msg("+++++ {0}", prop.PropertyType.ToString());
                                            if (prop.PropertyType == (typeof (System.String))) {
                                                string w = prop.GetValue(newEvent, null).ToString();
                                                List<byte> wb = new List<byte>();
                                                for (int i = 0; i < w.Length; i++) {
                                                    UInt16 b = (UInt16) w.ElementAt(i);
                                                    if (b > 900) b -= 848;
                                                    wb.Add((byte) b);
                                                }
                                                arrItmV.Add(wb.ToArray());
                                            }
                                            else if (prop.PropertyType == (typeof (System.Boolean))) {
                                                if (!OpcConnector.FlagStore.ContainsKey(v.ItemID)) {
                                                    l.err("First reference to <{0}> found on writing!!!", v.ItemID);
                                                    OpcConnector.FlagStore.Add(v.ItemID, 0);
                                                }
                                                arrItmV.Add(BoolExpressions.SetBit(OpcConnector.FlagStore[v.ItemID],
                                                                                   plcp.BitNumber,
                                                                                   Convert.ToBoolean(
                                                                                       prop.GetValue(newEvent, null))));
                                            }
                                            else arrItmV.Add(prop.GetValue(newEvent, null));
                                        }
                                        eureka = true;
                                        break;
                                    }
                                    index++;
                                }
                                if (!eureka) l.err("Item <{0}> is unknown to OPC Fledged", s);
                            }
                        }
                    }
                }
                int count = arrItmV.Count;
                if (count > 0) {
                    int[] aE;
                    if (OpcConnector.m_The_grp.Write(arrSrvH.ToArray(), arrItmV.ToArray(), out aE))
                        l.msg("Done processing event -- true");
                    else {
                        for (int i = 0; i < aE.Length; i++) {
                            if (HRESULTS.Failed(aE[i])) {
                                l.err("Item srvH={0} failed with HRESULT=0x{1:x} -- value {2}",
                                      arrSrvH[i],
                                      aE[i],
                                      arrItmV[i]
                                    );
                            }
                            else
                                l.msg("Item srvH={0} succseeded -- value {1}", arrSrvH[i], arrItmV[i]);
                        }
                    }
                }
                l.msg("Done processing event");
            }
        }
 public static void SaveMatrix(string path, List<MFCPData> matrixStateDataFull)
 {
     using (Logger l = new Logger("SaveMatrix")) {
         string[] strings = new string[matrixStateDataFull.Count];
         for (int dataCnt = 0; dataCnt < matrixStateDataFull.Count; dataCnt++) {
             strings[dataCnt] = String.Format("{1}{0}{2}{0}{3}{0}{4}{0}{5}{0}{6}{0}{7}{0}{8}",
                                              Separator,
                                              matrixStateDataFull[dataCnt].HeatNumber,
                                              matrixStateDataFull[dataCnt].TimeFromX,
                                              matrixStateDataFull[dataCnt].CarbonOxideIVP,
                                              matrixStateDataFull[dataCnt].CarbonMonoxideVP,
                                              matrixStateDataFull[dataCnt].CarbonOxideVP,
                                              matrixStateDataFull[dataCnt].SteelCarbonPercent,
                                              matrixStateDataFull[dataCnt].SteelCarbonPercentCalculated,
                                              matrixStateDataFull[dataCnt].HightQualityHeat
                 );
         }
         try {
             File.WriteAllLines(path, strings);
         }
         catch (Exception e) {
             l.err("Cannot write the file: {0}, call exeption: {1}", path, e.ToString());
             return;
             //throw;
         }
     }
 }
        public static void Iterate(HeatData heatData)
        {
            using (var l = new Logger("Iterate")) {
                var calculatedCarboneEvent = new CalculatedCarboneEvent();
                if (!TotalCarbonMassCalculated) {
                    if (
                        (heatData.IronMass > 0) &&
                        (heatData.IronCarbonPercent > 0) &&
                        (heatData.ScrapMass > 0) &&
                        (heatData.ScrapCarbonPercent > 0) &&
                        (heatData.SteelCarbonPercent > 0)
                        ) {
                        TotalCarbonMass = Decarbonater.HeatCarbonMass(
                            heatData.IronMass,
                            heatData.IronCarbonPercent,
                            heatData.ScrapMass,
                            heatData.ScrapCarbonPercent,
                            heatData.SteelCarbonPercent
                            );
                        RemainCarbonMass = TotalCarbonMass;
                        RemainCarbonPercent = GetCarbonPercent(RemainCarbonMass, heatData.IronMass,
                                                               heatData.IronCarbonPercent,
                                                               heatData.ScrapMass, heatData.ScrapCarbonPercent);
                        if (TotalCarbonMass > 0 && heatData.OxygenVolumeRate > 0) {
                            TotalCarbonMassCalculated = true;
                            l.msg("##### [TotalCarbonMassCalculated: {0}][RemainCarbonPercent]", TotalCarbonMass,
                                  RemainCarbonPercent);
                        }
                        else
                            l.msg("HeatCarbonMass returned bad result: {0}", TotalCarbonMass);
                    }
                    else {
                        l.err(
                            "bad data for HeatCarbonMass [IronMass: {0}][IronCarbonPercent: {1}][ScrapMass: {2}][ScrapCarbonPercent: {3}][SteelCarbonPercent: {4}]",
                            heatData.IronMass,
                            heatData.IronCarbonPercent,
                            heatData.ScrapMass,
                            heatData.ScrapCarbonPercent,
                            heatData.SteelCarbonPercent
                            );
                    }
                }
                else if (!GasCarbonMassFinished) {
                    heatData.DeltaT = m_sw.ElapsedMilliseconds*0.001;
                    m_sw.Restart();

                    if (
                        (heatData.CarbonMonoxideVolumePercent > 0) &&
                        (heatData.OffgasVolumeRate > 0) &&
                        (heatData.DeltaT > 0) &&
                        (heatData.Kgasan > 0)
                        ) {
                        double GCMResult = Decarbonater.GasanCarbonMass(
                            heatData.CarbonMonoxideVolumePercent,
                            heatData.OffgasVolumeRate,
                            heatData.DeltaT,
                            heatData.Kgasan
                            );
                        if (GCMResult >= 0) {
                            if (heatData.OxygenVolumeRate > 0)
                                RemainCarbonMass -= GCMResult; //////////////////////////////
                        }
                        else
                            l.err("GasanCarbonMass return bad result: {0}", GCMResult);
                        if (
                            (RemainCarbonMass > 0) &&
                            (heatData.IronMass > 0) &&
                            (heatData.IronCarbonPercent > 0) &&
                            (heatData.ScrapMass > 0) &&
                            (heatData.ScrapCarbonPercent > 0)
                            ) {
                            RemainCarbonPercent = GetCarbonPercent(
                                RemainCarbonMass,
                                heatData.IronMass,
                                heatData.IronCarbonPercent,
                                heatData.ScrapMass,
                                heatData.ScrapCarbonPercent
                                );
                        }
                        else {
                            l.err(
                                "bad data for GetCarbonPercent [RemainCarbonMass: {0}][IronMass: {1}][IronCarbonPercent: {2}][ScrapMass: {3}][ScrapCarbonPercent: {4}]",
                                RemainCarbonMass,
                                heatData.IronMass,
                                heatData.IronCarbonPercent,
                                heatData.ScrapMass,
                                heatData.ScrapCarbonPercent
                                );
                        }

                        GasCarbonMassFinished = VerifyGasCarbonFinished(
                            heatData.OxygenVolumeTotal,
                            heatData.OxygenVolumeCurrent,
                            TotalCarbonMass, RemainCarbonMass,
                            heatData.CarbonMonoxideVolumePercent,
                            heatData.CarbonMonoxideVolumePercentPrevious,
                            heatData.CarbonOxideVolumePercent,
                            heatData.CarbonOxideVolumePercentPrevious
                            );
                    }
                    else {
                        l.err(
                            "bad data for GasanCarbonMass [CarbonMonoxideVolumePercent: {0}][OffgasVolumeRate: {1}][DeltaT: {2}][Kgasan: {3}]",
                            heatData.CarbonMonoxideVolumePercent,
                            heatData.OffgasVolumeRate,
                            heatData.DeltaT,
                            heatData.Kgasan
                            );
                    }
                }
                else {
                    var currentStateData = new MFCMData {
                                                            CarbonMonoxideVolumePercent =
                                                                heatData.CarbonMonoxideVolumePercent,
                                                            CarbonOxideVolumePercent = heatData.CarbonOxideVolumePercent,
                                                            HeightLanceCentimeters = heatData.HeightLanceCentimeters,
                                                            OxygenVolumeRate = heatData.OxygenVolumeRate
                                                        };
                    //MFMChooser
                    //var CMCarbon = Decarbonater.MultiFactorCarbonMass(heatData.MatrixStateData, currentStateData);
                    m_currentMatrix = MFMChooser(heatData);
                    var matrixStateData =
                        Program.MFCMDataGenerate(Program.MatrixStateDataFull[m_currentMatrix].MatrixList);
                    var CMCarbon = Decarbonater.MultiFactorCarbonMass(matrixStateData, currentStateData);
                    //if (CMCarbon < RemainCarbonPercent) RemainCarbonPercent = CMCarbon;
                    RemainCarbonPercent = CMCarbon;

                    if (MomentFixDataForMFactorModel(heatData.CarbonMonoxideVolumePercent,
                                                     heatData.CarbonOxideVolumePercent)) // фиксируем для обучения
                    {
                        if (m_noFixData) {
                            CurrentHeatResult.OxygenVolumeRate = heatData.OxygenVolumeRate;
                            CurrentHeatResult.SteelCarbonCalculationPercent = RemainCarbonPercent;
                            CurrentHeatResult.CarbonMonoxideVolumePercent = heatData.CarbonMonoxideVolumePercent;
                            CurrentHeatResult.CarbonOxideVolumePercent = heatData.CarbonOxideVolumePercent;
                            CurrentHeatResult.HeightLanceCentimeters = heatData.HeightLanceCentimeters;
                            CurrentHeatResult.MFMEquationId = m_currentMatrix; // фиксируем матрицу по которой учим
                            EnqueueWaitC(CurrentHeatResult); // ставим в очередь ожидания углерода
                            Program.PushGate.PushEvent(new FixDataMfactorModelEvent());

                            // временная мера для перехода на старый углерод
                            var fex = new ConnectionProvider.FlexHelper("CPlusProcessor.DataFix");
                            fex.Fire(Program.PushGate);
                            Console.WriteLine(fex.evt + "\n");
                            //////////////////////////////////////////////////////////////////////

                            m_noFixData = false;
                        }
                    }
                }
                DataArchSec.SD.Add(new SecondData()); // заполняем для статистики во время плавки
                DataArchSec.SD[DataArchSec.SD.Count - 1].CarboneCalc = RemainCarbonPercent;
                DataArchSec.SD[DataArchSec.SD.Count - 1].Time = DateTime.Now.ToString();
                DataArchSec.SD[DataArchSec.SD.Count - 1].CarboneMonoxide = heatData.CarbonMonoxideVolumePercent;
                DataArchSec.SD[DataArchSec.SD.Count - 1].CarboneOxide = heatData.CarbonOxideVolumePercent;
                DataArchSec.SD[DataArchSec.SD.Count - 1].HeightLance = heatData.HeightLanceCentimeters;
                DataArchSec.SD[DataArchSec.SD.Count - 1].OxygenVolumeCurrent = heatData.OxygenVolumeCurrent;
                //
                if (!GasCarbonMassFinished) {
                    DataArchSec.SD[DataArchSec.SD.Count - 1].Model = "Gas Analise Mono factor Model";
                    l.msg("Gas Analise Mono factor Model");
                }
                else {
                    DataArchSec.SD[DataArchSec.SD.Count - 1].Model = "Multi Factor Model";
                    l.msg("Multi Factor Model № {0}", m_currentMatrix);
                }
                calculatedCarboneEvent.CarbonePercent = RemainCarbonPercent;
                calculatedCarboneEvent.CarboneMass = RemainCarbonMass;
                calculatedCarboneEvent.model = DataArchSec.SD[DataArchSec.SD.Count - 1].Model;
                Program.PushGate.PushEvent(calculatedCarboneEvent);
                //Program.PushGate.PushEvent(new CalculatedCarboneEvent());

                // временная мера для перехода на старый углерод
                var fex2 = new ConnectionProvider.FlexHelper("CPlusProcessor.Result");
                fex2.AddArg("C", RemainCarbonPercent);
                fex2.Fire(Program.PushGate);
                //////////////////////////////////////////////////////////////////////
            }
        }
 public static void SaveMatrix(string path, char separator, List<MFCMDataFull> matrixStateDataFull)
 {
     using (Logger l = new Logger("SaveMatrix")) {
         string[] strings = new string[matrixStateDataFull.Count];
         for (int dataCnt = 0; dataCnt < matrixStateDataFull.Count; dataCnt++) {
             strings[dataCnt] = String.Format("{1}{0}{2}{0}{3}{0}{4}{0}{5}{0}{6}{0}{7}{0}{8}{0}{9}",
                                              separator,
                                              matrixStateDataFull[dataCnt].IdHeat,
                                              matrixStateDataFull[dataCnt].NumberHeat,
                                              matrixStateDataFull[dataCnt].CarbonMonoxideVolumePercent,
                                              matrixStateDataFull[dataCnt].CarbonOxideVolumePercent,
                                              matrixStateDataFull[dataCnt].HeightLanceCentimeters,
                                              matrixStateDataFull[dataCnt].OxygenVolumeRate,
                                              matrixStateDataFull[dataCnt].SteelCarbonPercent,
                                              matrixStateDataFull[dataCnt].SteelCarbonCalculationPercent,
                                              matrixStateDataFull[dataCnt].MFMEquationId
                 );
         }
         try {
             File.WriteAllLines(path, strings);
         }
         catch (Exception e) {
             l.err("Cannot write the file: {0}, call exeption: {1}", path, e.ToString());
             return;
             //throw;
         }
     }
 }
        public void OnEvent(BaseEvent evt)
        {
            using (var l = new Logger("Listener")) {
                #region сбор данных для автоматического режима не FlexEvent

                if (evt is HeatChangeEvent) {
                    var hce = evt as HeatChangeEvent;
                    if (CHeatNumber != hce.HeatNumber) {
                        CHeatNumber = hce.HeatNumber;
                        Program.Reset();
                        l.msg("Heat Changed. New Heat ID: {0}\n", CHeatNumber);
                        Program.Saver.HeatNumber = CHeatNumber;
                    }
                    else
                        l.msg("Heat No Changed. Heat ID: {0}\n", hce.HeatNumber);
                }

                if (evt is ScrapEvent) {
                    var scrapEvent = evt as ScrapEvent;
                    if (scrapEvent.ConverterNumber == Program.ConverterNumber) {
                        Program.AutoInData.MSc = scrapEvent.TotalWeight;
                        l.msg("Scrap mass: {0}", Program.AutoInData.MSc);
                        Program.IsRefrashData = true;
                    }
                }

                #endregion

                if (evt is FlexEvent) {
                    #region интерфейс для визухи

                    var fxe = evt as FlexEvent;
                    if (fxe.Operation.StartsWith("UI.GetNamePatterns")) {
                        l.msg(fxe.ToString());
                        Program.TablePaths = Program.ScanStore(Program.StorePath);
                        var names = Program.GetNamesFromAddress(Program.TablePaths);
                        var fex = new FlexHelper("Charge5.PatternNames");
                        for (int i = 0; i < names.Count; i++)
                            fex.AddArg(i.ToString(), names[i]);
                        fex.Fire(Program.MainGate);
                    }

                    if (fxe.Operation.StartsWith("UI.LoadPattern")) {
                        l.msg(fxe.ToString());
                        try {
                            Program.Tables = Program.LoadTables((string) fxe.Arguments["Name"], ref Program.InitTbl);
                        }
                        catch (Exception e) {
                            l.err("UI.LoadPattern: \n{0}", e.ToString());
                        }

                        var fex = new FlexHelper("Charge5.RespLoadPattern");
                        if (Program.Tables == null) {
                            l.err("pattern not loaded");
                            fex.AddArg("Loaded", false);
                        }
                        else
                            fex.AddArg("Loaded", true);
                        fex.Fire(Program.MainGate);
                    }

                    if (fxe.Operation.StartsWith("UI.Calc")) {
                        var inData = new InData();
                        var outData = new OutData();

                        l.msg(fxe.ToString());
                        try {
                            inData.SteelType = (int) fxe.Arguments["SteelType"]; //

                            inData.MHi = (int) fxe.Arguments["MHi"];
                            inData.MSc = (int) fxe.Arguments["MSc"];
                            inData.SiHi = (double) fxe.Arguments["SiHi"];
                            inData.THi = (int) fxe.Arguments["THi"];

                            inData.IsProcessingUVS = (bool) fxe.Arguments["IsProcessingUVS"]; //
                            var table = Program.Tables[inData.SteelType];
                            Program.Alg(table, inData, out outData);
                            Program.SendResultCalc(outData);
                        }
                        catch (Exception e) {
                            l.err("UI.Calc: \n{0}", e.ToString());
                        }
                    }

                    if (fxe.Operation.StartsWith("UI.GetPattern")) {
                        l.msg(fxe.ToString());
                        try {
                            var name = (string) fxe.Arguments["Name"];
                            Program.LoadTables(name, ref Program.InitTbl);
                            CSVTP_FlexEventConverter.AppName = "Charge5";
                            var flex = CSVTP_FlexEventConverter.PackToFlex(name, Program.InitTbl, Program.Tables);
                            var fex = new FlexHelper(flex.Operation);
                            fex.evt.Arguments = flex.Arguments;
                            fex.Fire(Program.MainGate);
                        }
                        catch (Exception e) {
                            l.err("UI.GetPattern: \n{0}", e.ToString());
                        }
                    }

                    if (fxe.Operation.StartsWith("UI.Tables")) {
                        var fex = new FlexHelper("Charge5.SavePatternResp");
                        l.msg(fxe.ToString());
                        try {
                            var patternName = "";
                            Charge5Classes.CSVTP_FlexEventConverter.UnpackFromFlex(
                                fxe,
                                ref Program.InitTbl,
                                ref Program.Tables,
                                ref patternName
                                );
                            Program.SaveTables(patternName, Program.InitTbl, Program.Tables);
                            fex.AddArg("Saved", true);
                        }
                        catch (Exception e) {
                            l.err("UI.GetPattern: \n{0}", e.ToString());
                            fex.AddArg("Saved", false);
                        }
                        fex.Fire(Program.MainGate);
                    }

                    if (fxe.Operation.StartsWith("UI.RemoovePattern")) {
                        var fex = new FlexHelper("Charge5.RemoovePatternResp");
                        l.msg(fxe.ToString());
                        try {
                            Program.RemooveTables((string) fxe.Arguments["Name"]);
                            fex.AddArg("Remooved", true);
                        }
                        catch (Exception e) {
                            l.err("UI.RemoovePattern: \n{0}", e.ToString());
                            fex.AddArg("Remooved", false);
                        }
                        fex.Fire(Program.MainGate);
                    }

                    #endregion

                    #region интерфейс для визухи в автоматическом режиме

                    if (fxe.Operation.StartsWith("UI.ModeCalc")) {
                        l.msg(fxe.ToString());
                        try {
                            Program.CalcModeIsAutomatic = (bool) fxe.Arguments["IsAutomatic"];
                            Program.IsRefrashData = true;
                        }
                        catch (Exception e) {
                            l.err("UI.CalcMode: \n{0}", e.ToString());
                        }
                    }

                    if (fxe.Operation.StartsWith("UI.DataCalc")) {
                        l.msg(fxe.ToString());
                        try {
                            var steelType = (int) fxe.Arguments["SteelType"];
                            if ((steelType >= 0) && (steelType <= 6)) // имеем только 7 типов стали
                            {
                                Program.AutoInData.SteelType = steelType;
                                Program.IsRefrashData = true;
                            }
                            else
                                throw new Exception("Не верное значение типа стали, >7 или <0");
                            Program.AutoInData.IsProcessingUVS = (bool) fxe.Arguments["IsProcessingUVS"];
                        }
                        catch (Exception e) {
                            l.err("UI.CalcData: \n{0}", e.ToString());
                        }
                    }

                    #endregion

                    #region сбор данных для автоматического режима FlexEvent

                    if (fxe.Operation.StartsWith("PipeCatcher.Call.PCK_DATA.PGET_WGHIRON1")) {
                        if ((string) fxe.Arguments["SHEATNO"] == Convert.ToString(HeatNumberToLong(CHeatNumber))) {
                            l.msg("Iron Correction from Pipe: {0}\n", fxe.Arguments["NWGH_NETTO"]);
                            Program.AutoInData.MHi =
                                (int) Math.Round(Convert.ToDouble(fxe.Arguments["NWGH_NETTO"])*1000);
                            Program.IsRefrashData = true;
                        }
                        else {
                            l.msg(
                                "Iron Correction from Pipe: wrong heat number - expected {0} found {1}",
                                CHeatNumber, fxe.Arguments["SHEATNO"]
                                );
                        }
                    }

                    if (fxe.Operation.StartsWith("PipeCatcher.Call.PCK_DATA.PGET_XIMIRON")) {
                        if ((string) fxe.Arguments["HEAT_NO"] == Convert.ToString(HeatNumberToLong(CHeatNumber))) {
                            l.msg("Xim Iron from Pipe: T = {0}, Si = {1}\n", fxe.Arguments["HM_TEMP"],
                                  fxe.Arguments["ANA_SI"]);
                            Program.AutoInData.SiHi = Convert.ToDouble(fxe.Arguments["ANA_SI"]);
                            Program.AutoInData.THi = Convert.ToInt32(fxe.Arguments["HM_TEMP"]);
                            Program.IsRefrashData = true;
                        }
                        else {
                            l.msg(
                                "Xim Iron from Pipe: wrong heat number - expected {0} found {1}",
                                CHeatNumber, fxe.Arguments["HEAT_NO"]
                                );
                        }
                    }

                    #endregion
                }
            }
        }