public static int CalcC(CSVTableParser matrixC, Estimates data)
        {
            using (var l = new Logger("CalcC")) {
                if (
                    (data.CurrentC == 0) &&
                    (data.TargetC == 0)
                    )
                    return 0;
                foreach (var row in matrixC.Rows) {
                    if ((double) (row.Cell["CMin"]) <= data.CurrentC && data.CurrentC < (double) (row.Cell["CMax"])) {
                        l.msg("C item found --- CMin {0}; CMax {1}", row.Cell["CMin"], row.Cell["CMax"]);

                        var differenceC = data.TargetC - data.CurrentC;
                        if (differenceC < 0) {
                            differenceC = Math.Abs(differenceC);
                            var oxygenOnCarbon = (int) (row.Cell["OxygenOnCarbon"]);
                            const double carbonConsumption = 0.01;
                            double correctionOxy = (oxygenOnCarbon/carbonConsumption)*differenceC;
                            l.msg("Correction Oxygen C = {0}", correctionOxy);
                            return (int) Math.Round(correctionOxy);
                        }
                        else
                            return 0;
                    }
                }
            }
            return 0;
        }
        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 void OnEvent(BaseEvent evt)
        {
            using (var l = new Logger("SublanceGenerator Listener")) {
                if (evt is HeatChangeEvent) {
                    var hce = evt as HeatChangeEvent;
                    if (HeatNumber != hce.HeatNumber) {
                        l.msg("Heat Changed. New Heat ID: {0}\n", hce.HeatNumber);
                        HeatNumber = hce.HeatNumber;
                        Program.Reset();
                    }
                    else
                        l.msg("Heat No Changed. Heat ID: {0}\n", hce.HeatNumber);
                }

                if (evt is FlexEvent) {
                    var fxe = evt as FlexEvent;

                    CarbonEventHandler(fxe, 0, "OffGasDecarbonater");
                    CarbonEventHandler(fxe, 1, "SMFCarbon");
                    CarbonEventHandler(fxe, 2, "CPlusProcessor");
                    CarbonEventHandler(fxe, 3, "NeuralProcessorC");
                    CarbonEventHandler(fxe, 4, "CorrectionCT");
                }
            }
        }
 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);
                }
            }
        }
 //public Listener()
 //{
 //}
 public void OnEvent(BaseEvent evt)
 {
     using (var l = new Logger("FlexEventSaver"))
     {
         if (evt is FlexEvent)
         {
             var fxe = evt as FlexEvent;
             if (fxe.Operation.StartsWith(Program.m_startsWith))
             {
                 l.msg(fxe.ToString());
             //    string str = "\n================================================";
             //    foreach(String key in fxe.Arguments.Keys)
             //    {
             //        str += String.Format("\n{0}\t:{1}", key, fxe.Arguments[key]);
             //    }
             //    l.msg(str);
             //}
             //else
             //{
             //    string s = String.Format("Id={0} Time={1}\nOperation={2}\nFlags={3}\nArguments:", fxe.Id, fxe.Time, fxe.Operation, fxe.Flags);
             //    s = fxe.Arguments.Keys.Aggregate(s, (current, key) => current + String.Format("\n\t{0}\t:{1}", key, fxe.Arguments[key]));
             //    l.msg("{0}\n==============================\n", s);
             }
         }
     }
 }
 public CoreListener(string opcAddressFmt, string opcDestination)
 {
     using (Logger l = new Logger("CoreListener")) {
         opcAddressFmt_ = opcAddressFmt;
         opcDestination_ = opcDestination;
         l.msg("Started", "Listener", InstantLogger.TypeMessage.unimportant);
     }
 }
 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 DBReader(String ConnStr_, String PipeName_)
 {
     using (Logger l = new Logger("PipeCatcher"))
     {
         ConnStr = ConnStr_;
         PipeName = PipeName_;
         OraConn = new OracleConnection(ConnStr);
         OraCmd = OraConn.CreateCommand();
         l.msg("A new DBReader created ConnStr={0} PipeName={1}", ConnStr, PipeName);
     }
 }
 public String GetNews()
 {
     using (Logger l = new Logger("PipeCatcher"))
     {
         HeatNo = Convert.ToString(OraCmd.Parameters["SHEATNO"].Value);
         ProcName = Convert.ToString(OraCmd.Parameters["SNAME_PROC"].Value);
         var str = Convert.ToString(OraCmd.Parameters["NRECID"].Value);
         RecId = Convert.ToDecimal(str);
         str = String.Format("\nSHEATNO = {0} SNAME_PROC = {1} NRECID = {2}", HeatNo, ProcName, RecId);
         l.msg(str);
         return str;
     }
 }
        public void OnEvent(BaseEvent evt)
        {
            using (Logger l = new Logger("OnEvent"))
            {
                if (evt is FlexEvent)
                {
                    var fex = new FlexHelper(evt as FlexEvent);
                    if (fex.evt.Operation.StartsWith("OPC.HM-Chemistry.Event."))
                    {
                        lock (mixers)
                        {
                            mixers.Enqueue(fex);
                            mixerTimer.Interval = 1000;
                        }
                    }
                    else if (fex.evt.Operation.StartsWith("Model.Shixta-I"))
                    {
                        l.msg("{0}", fex.evt);
                    }
                }
                else if (evt is HeatChangeEvent)
                {
                    var hce = evt as HeatChangeEvent;
                    if (HeatNumber == hce.HeatNumber) return;
                    Int64 rem;
                    Int64 res = Math.DivRem(hce.HeatNumber, 10000, out rem);
                    var newHeatNumber = res * 100000 + rem;
                    HeatNumber = newHeatNumber;
                    Program.face.Invoke(new MethodInvoker(delegate()
                    {
                        Program.face.txbHeatNum.Text = Convert.ToString(HeatNumber);
                        Program.face.lblTitleHeading.Text
                            += Program.face.txbHeatNum.Text.Substring(0, 1);
                        Program.face.txbSteelTemp.Text = "1650";
                        Program.face.txbCarbonPercent.Text = "0,03";
                        Program.face.txbMgO.Text = "10";
                        Program.face.txbFeO.Text = "27";
                        Program.face.txbBasiticy.Text = "2,7";
                        Program.face.txbIronTask.Text = "300";
                        Program.face.txbIronTemp.Text = "1380";

                    }));
                }
            }
        }
 public void OnEvent(BaseEvent evt)
 {
     using (Logger l = new Logger("Corelistener.OnEvent")) {
         if (evt is FlexEvent) {
             var fex = new FlexHelper(evt as FlexEvent);
             if (fex.evt.Operation.StartsWith("OPC.HM-Chemistry.Event.")) {
                 lock (mixers) {
                     mixers.Enqueue(fex);
                     mixerTimer.Interval = 1000;
                     ClientFace.ironTable.dgw.RowCount = 0;
                 }
             }
             else if (fex.evt.Operation.StartsWith("Model.Shixta-I")) {
                 l.msg("{0}", fex.evt);
             }
         }
         else if (evt is HeatChangeEvent) {
             var hce = evt as HeatChangeEvent;
             Int64 rem;
             Int64 res = Math.DivRem(hce.HeatNumber, 10000, out rem);
             var newHeatNumber = res*100000 + rem;
             HeatNumber = newHeatNumber;
             ClientFace.Invoke(new MethodInvoker(delegate() {
                 ClientFace.txbHeatNum.Text = Convert.ToString(HeatNumber + 1);
                 if (ClientFace.m_cn !=
                     ClientFace.txbHeatNum.Text.Substring(0, 1)) {
                     ClientFace.m_cn = ClientFace.txbHeatNum.Text.Substring(
                         0, 1);
                     ClientFace.lblTitleHeading.Text =
                         ClientFace.lblTitleHeading.Text.Replace("X",
                                                                 ClientFace.
                                                                     m_cn);
                 }
                 ClientFace.lblTitleHeading.Text =
                     ClientFace.lblTitleHeading.Text.Replace(WhatToFind,
                                                             Convert.ToString
                                                                 (HeatNumber));
                 WhatToFind = Convert.ToString(HeatNumber);
             }));
         }
     }
 }
        public void OnEvent(BaseEvent evt)
        {
            using (var l = new Logger("Listener")) {
                if (evt is LanceEvent) {
                    var le = evt as LanceEvent;
                    Iterator.Receiver.LanceHeight = le.LanceHeight;
                    Iterator.Receiver.QO2 = le.O2Flow;
                    Iterator.Receiver.QO2I = le.O2TotalVol;
                }
                if (evt is BlowingEvent) {
                    var be = evt as BlowingEvent;
                    Iterator.Receiver.HeatIsStarted = be.BlowingFlag == 1;
                }

                if (evt is OffGasEvent) {
                    var oge = evt as OffGasEvent;
                    Iterator.Receiver.OffGasV.Add(oge.OffGasFlow);
                    Iterator.Receiver.OffGasT.Add(oge.OffGasTemp);
                }
                if (evt is DecompressionOffGasEvent) {
                    var doge = evt as DecompressionOffGasEvent;
                    Iterator.Receiver.OffGasDecompression.Add(doge.Decompression);
                }
                if (evt is HeatChangeEvent) {
                    var hce = evt as HeatChangeEvent;
                    if (CHeatNumber != hce.HeatNumber) {
                        CHeatNumber = hce.HeatNumber;
                        Iterator.Reset();
                        Iterator.CurrentState.HeatNumber = hce.HeatNumber;
                        Iterator.ArchFileGen();
                        l.msg("Heat Changed. New Heat ID: {0}\n", Iterator.CurrentState.HeatNumber);
                    }
                    else
                        l.msg("Heat No Changed. Heat ID: {0}\n", hce.HeatNumber);
                }

                if (evt is SublanceStartEvent) {
                    var sse = evt as SublanceStartEvent;
                    if (sse.SublanceStartFlag == 1) {}
                    if (sse.SublanceStartFlag == 0) {
                        //
                    }
                }

                if (evt is visSpectrluksEvent) // углерод со спектролюкса
                {
                    var vse = evt as visSpectrluksEvent;
                    //Iterator.FindAndDequeue(vse.C, HeatNumberToShort(vse.HeatNumber));
                }

                if (evt is ScrapEvent) {
                    var se = evt as ScrapEvent;
                    if (se.ConverterNumber == Program.ConverterNumber) {
                        Iterator.CurrentState.MSc = se.TotalWeight;
                        l.msg("Scrap mass: {0}", Iterator.CurrentState.MSc);
                    }
                }
                if (evt is BoundNameMaterialsEvent) {
                    var bnme = evt as BoundNameMaterialsEvent;
                    BoundMaterials = new List<string>();
                    BoundMaterials.Add(bnme.Bunker5MaterialName);
                    BoundMaterials.Add(bnme.Bunker6MaterialName);
                    BoundMaterials.Add(bnme.Bunker7MaterialName);
                    BoundMaterials.Add(bnme.Bunker8MaterialName);
                    BoundMaterials.Add(bnme.Bunker9MaterialName);
                    BoundMaterials.Add(bnme.Bunker10MaterialName);
                    BoundMaterials.Add(bnme.Bunker11MaterialName);
                    BoundMaterials.Add(bnme.Bunker12MaterialName);
                }

                if (evt is visAdditionTotalEvent) {
                    var vate = evt as visAdditionTotalEvent;
                    WeightMaterials = new List<double>();
                    WeightMaterials.Add(vate.RB5TotalWeight);
                    WeightMaterials.Add(vate.RB6TotalWeight);
                    WeightMaterials.Add(vate.RB7TotalWeight);
                    WeightMaterials.Add(vate.RB8TotalWeight);
                    WeightMaterials.Add(vate.RB9TotalWeight);
                    WeightMaterials.Add(vate.RB10TotalWeight);
                    WeightMaterials.Add(vate.RB11TotalWeight);
                    WeightMaterials.Add(vate.RB12TotalWeight);

                    //BoundMaterials = new List<string>(); // на время отладки на эмуляторе
                    //BoundMaterials.Add("ДОЛОМС");
                    //BoundMaterials.Add("ALKонц");
                    //BoundMaterials.Add("KOKS  ");
                    //BoundMaterials.Add("ИЗВЕСТ");
                    //BoundMaterials.Add("ИЗВЕСТ");
                    //BoundMaterials.Add("ДОЛМИТ");
                    //BoundMaterials.Add("ДОЛОМС");
                    //BoundMaterials.Add("ФОМ   ");

                    var bunkerCnt = BoundMaterials.Count;
                    for (int i = 0; i < bunkerCnt; i++) {
                        var wgh = WeightMaterials[i];
                        var name = BoundMaterials[i];
                        for (int j = 0; j < bunkerCnt; j++) {
                            if ((i != j) && (name == BoundMaterials[j]))
                                wgh += WeightMaterials[j];
                        }

                        if (!Iterator.Receiver.HeatIsStarted) // все что отдали до продувки не считаем
                        {
                            Iterator.MaterialsZeroLevel.SetTotalWeight(Encoder(name), wgh, false);

                            //Iterator.MaterialsZeroLevel.SetTotalWeight(name, wgh, false); // временно для отладки
                        }
                        else
                        {
                            var wghZlevel = Iterator.MaterialsZeroLevel.GetTotalWeight(Encoder(name), false);
                            Iterator.CurrentState.Materials.SetTotalWeight(Encoder(name), wgh - wghZlevel, false);

                            //var wghZlevel = Iterator.MaterialsZeroLevel.GetTotalWeight(name, false); // временно для отладки
                            //Iterator.CurrentState.Materials.SetTotalWeight(name, wghZlevel - wgh, false); // временно для отладки
                        }

                        //Iterator.CurrentState.Materials.SetTotalWeight(Encoder(name), wgh, false);
                        //Iterator.CurrentState.Materials.SetTotalWeight(name, wgh, false); // временно для отладки
                    }
                }

                if (evt is FlexEvent) {
                    var fxe = evt as FlexEvent;
                    if (fxe.Operation.StartsWith("UDP.OffGasAnalysisEvent")) {
                        var fxh = new FlexHelper(fxe);

                        Iterator.Receiver.H2.Add(fxh.GetDbl("H2"));
                        Iterator.Receiver.O2.Add(fxh.GetDbl("O2"));
                        Iterator.Receiver.CO.Add(fxh.GetDbl("CO"));
                        Iterator.Receiver.CO2.Add(fxh.GetDbl("CO2"));
                        Iterator.Receiver.N2.Add(fxh.GetDbl("N2"));
                        Iterator.Receiver.Ar.Add(fxh.GetDbl("Ar"));

                        if (fxh.GetDbl("Branch") == 1)
                            Iterator.CurrentState.OffGasTransportDelay = (int) Math.Round(fxh.GetDbl("TransportDelay1"));
                        else if (fxh.GetDbl("Branch") == 2)
                            Iterator.CurrentState.OffGasTransportDelay = (int) Math.Round(fxh.GetDbl("TransportDelay2"));
                    }

                    if (fxe.Operation.StartsWith("PipeCatcher.Call.PCK_DATA.PGET_WGHIRON1")) {
                        if ((string) fxe.Arguments["SHEATNO"] ==
                            Convert.ToString(HeatNumberToLong(Iterator.CurrentState.HeatNumber))) {
                            l.msg("Iron Correction from Pipe: {0}\n", fxe.Arguments["NWGH_NETTO"]);
                            var hotIronMass = Convert.ToDouble(fxe.Arguments["NWGH_NETTO"])*1000;
                            Iterator.CurrentState.MHi = hotIronMass;
                        }
                        else {
                            l.msg(
                                "Iron Correction from Pipe: wrong heat number - expected {0} found {1}",
                                Iterator.CurrentState.HeatNumber, fxe.Arguments["SHEATNO"]
                                );
                        }
                    }

                    if (fxe.Operation.StartsWith("PipeCatcher.Call.PCK_DATA.PGET_XIMIRON")) {
                        if ((string) fxe.Arguments["HEAT_NO"] ==
                            Convert.ToString(HeatNumberToLong(Iterator.CurrentState.HeatNumber))) {
                            l.msg(fxe.ToString());
                            var hotIronMass = Convert.ToDouble(fxe.Arguments["HM_WEIGHT"]);
                            var hotIronCarbon = Convert.ToDouble(fxe.Arguments["ANA_C"]);
                            Iterator.CurrentState.MHi = hotIronMass;
                            Iterator.CurrentState.PCHi = hotIronCarbon;
                        }
                        else {
                            l.msg(
                                "Iron Correction from Pipe: wrong heat number - expected {0} found {1}",
                                HeatNumberToLong(Iterator.CurrentState.HeatNumber), fxe.Arguments["HEAT_NO"]
                                );
                        }
                    }
                }
            }
        }
        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)
        {
            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 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 void TheGrpWriteComplete(object sender, WriteCompleteEventArgs e)
 {
     using (Logger l = new Logger("OnWriteComplete", ref locker)) {
         l.msg("WriteComplete event: gh={0} id={1} me={2}", e.groupHandleClient, e.transactionID,
               e.masterError);
         foreach (OPCWriteResult r in e.res) {
             if (HRESULTS.Succeeded(r.Error))
                 l.msg(" ih={0} e={1}", r.HandleClient, r.Error);
             else
                 l.msg(" ih={0} ERROR=0x{1:x} !", r.HandleClient, r.Error);
         }
     }
 }
        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 String ProcessNews()
 {
     using (Logger l = new Logger("PipeCatcher"))
     {
         OraCmd.CommandText = ProcName;
         OraCmd.CommandType = System.Data.CommandType.StoredProcedure;
         OraCmd.Parameters.Clear();
         //OraCmd.Parameters.Add(new OracleParameter("NRECID", OracleDbType.Decimal, System.Data.ParameterDirection.Input)).Value = RecId;
         OraCmd.Parameters.Add(new OracleParameter("REFCURSOR", OracleDbType.RefCursor, System.Data.ParameterDirection.Output));
         if (OraCmd.Connection.State != System.Data.ConnectionState.Closed)
         {
             OraCmd.Connection.Close();
         }
         OraCmd.Connection.Open();
         OraReader = OraCmd.ExecuteReader();
         var str = String.Format("\nCALL {0}", ProcName);
     //                var mainevt = new FlexEvent("PipeCatcher.Call." + ProcName);
     //                mainevt.Arguments.Add("@ProcName", ProcName);
         if (OraReader.HasRows)
         {
             var iRow = 0;
             FlexEvent evt = new FlexEvent("PipeCatcher.Call." + ProcName + ".Row." + (++iRow));
             str += "+++";
             while (OraReader.Read())
             {
                 for (int i = 0; i < OraReader.FieldCount; i++)
                 {
                     evt.Arguments.Add(OraReader.GetName(i), OraReader[i]);
                     str += "\n" + OraReader.GetName(i) + "\t: " + OraReader[i];
                 }
                 str += "\n********************";
     //                        mainevt.Arguments.Add(String.Format("Row{0}", ++iRow), evt);
                 Program.CoreGate.PushEvent(evt);
                 evt.Arguments.Clear();
             }
     //                    Program.CoreGate.PushEvent(mainevt);
         }
         else
         {
             str += "---";
         }
         OraReader.Close();
         l.msg(str);
         return str;
     }
 }
        public static void Iterate(HeatData heatData)
        {
            using (var l = new Logger("Iterate")) {
                if (ModelIsStarted) {
                    var currentStateData = new MFCMData {
                                                            CarbonMonoxideVolumePercent =
                                                                heatData.CarbonMonoxideVolumePercent,
                                                            CarbonOxideVolumePercent = heatData.CarbonOxideVolumePercent,
                                                            HeightLanceCentimeters = heatData.HeightLanceCentimeters,
                                                            OxygenVolumeRate = heatData.OxygenVolumeRate
                                                        };

                    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;

                    var fex2 = new ConnectionProvider.FlexHelper("SMFCarbon.Result");
                    fex2.AddArg("C", RemainCarbonPercent);
                    fex2.Fire(Program.PushGate);

                    Console.CursorTop = Console.CursorTop - 1;
                    Console.WriteLine("                                                   ");
                    Console.CursorTop = Console.CursorTop - 1;
                    Console.WriteLine("Carbon = " + RemainCarbonPercent + "%");

                    if (MomentFixDataForMFactorModel(heatData.CarbonMonoxideVolumePercent,
                                                     heatData.CarbonOxideVolumePercent)) // фиксируем для обучения
                    {
                        if (!m_dataIsFixed) {
                            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); // ставим в очередь ожидания углерода

                            var fex = new ConnectionProvider.FlexHelper("SMFCarbon.DataFix");
                            fex.AddArg("C", RemainCarbonPercent);
                            fex.Fire(Program.PushGate);
                            l.msg(fex.evt + "\n");

                            m_dataIsFixed = true;
                        }
                    }
                }
                else {
                    ModelIsStarted = ModelVerifiForStart(
                        heatData.OxygenVolumeTotal,
                        heatData.OxygenVolumeCurrent,
                        heatData.CarbonMonoxideVolumePercent,
                        heatData.CarbonMonoxideVolumePercentPrevious,
                        heatData.CarbonOxideVolumePercent,
                        heatData.CarbonOxideVolumePercentPrevious
                        );
                    if (ModelIsStarted) {
                        var fex = new ConnectionProvider.FlexHelper("SMFCarbon.ModelIsStarted");
                        fex.Fire(Program.PushGate);
                        l.msg(fex.evt + "\n");
                    }
                    Console.Write(".");
                }
            }
        }
 public CoreListener()
 {
     using (Logger l = new Logger("CoreListener"))
         l.msg("Started", "Listener", InstantLogger.TypeMessage.unimportant);
 }
        public void OnEvent(BaseEvent evt)
        {
            using (var l = new Logger("Listener")) {
                if (evt is LanceEvent) {
                    var le = evt as LanceEvent;

                    Iterator.HDSmoother.Oxygen = le.O2TotalVol;
                    Iterator.HDSmoother.LanceHeigth = le.LanceHeight;
                    Iterator.HDSmoother.LanceHeigthPrevious = LanceHeithPrevious;

                    LanceHeithPrevious = le.LanceHeight;
                }
                if (evt is BlowingEvent) {
                    var be = evt as BlowingEvent;
                    Iterator.HDSmoother.HeatIsStarted = be.BlowingFlag == 1;
                }
                if (evt is OffGasAnalysisEvent) {
                    var ogae = evt as OffGasAnalysisEvent;
                    Iterator.HDSmoother.CO.Add(ogae.CO);
                    Iterator.HDSmoother.CO2.Add(ogae.CO2);
                    if ((Iterator.HDSmoother.Oxygen > 0) && Iterator.HeatIsStarted) {
                        Iterator.IntegralCO += Double.IsNaN(ogae.CO) ? 0 : ogae.CO;
                        Iterator.IntegralCO2 += Double.IsNaN(ogae.CO2) ? 0 : ogae.CO2;
                    }
                }
                if (evt is BlowingEvent) {
                    var be = evt as BlowingEvent;
                    Iterator.HeatIsStarted = be.BlowingFlag == 1;
                }
                if (evt is OffGasEvent) {
                    var oge = evt as OffGasEvent;
                    Iterator.OffGasV = oge.OffGasFlow;
                }
                if (evt is HeatChangeEvent) {
                    var hce = evt as HeatChangeEvent;
                    if (CHeatNumber != hce.HeatNumber) {
                        CHeatNumber = hce.HeatNumber;
                        Iterator.Reset();
                        Iterator.CurrentState.HeatNumber = hce.HeatNumber;
                        l.msg("Heat Changed. New Heat ID: {0}\n", Iterator.CurrentState.HeatNumber);
                    }
                    else
                        l.msg("Heat No Changed. Heat ID: {0}\n", hce.HeatNumber);
                }

                if (evt is SublanceStartEvent) {
                    var sse = evt as SublanceStartEvent;
                    if (sse.SublanceStartFlag == 1)
                        l.msg("Sublance begin metering");
                    if (sse.SublanceStartFlag == 0) {
                        //
                    }
                }

                if (evt is visSpectrluksEvent) // углерод со спектролюкса
                {
                    var vse = evt as visSpectrluksEvent;
                    l.msg("Spectroluks C = {0}; HN = {1}", vse.C, HeatNumberToShort(vse.HeatNumber));
                    Iterator.AddCarbonToQueue(HeatNumberToShort(vse.HeatNumber), vse.C);
                }
            }
        }
        public static double CalcNewCarbon(CSVTableParser matrixC, Estimates data, int OxyAfterMetering)
        {
            using (var l = new Logger("CalcC")) {
                if (data.CurrentC == 0) return 0;

                foreach (var row in matrixC.Rows) {
                    if ((double) (row.Cell["CMin"]) <= data.CurrentC && data.CurrentC < (double) (row.Cell["CMax"])) {
                        l.msg("C item found --- CMin {0}; CMax {1}", row.Cell["CMin"], row.Cell["CMax"]);

                        var oxygenOnCarbon = (int) (row.Cell["OxygenOnCarbon"]);
                        return data.CurrentC - ((OxyAfterMetering/oxygenOnCarbon)*0.01);
                    }
                }
            }
            return 0;
        }
        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 int CalcT(CSVTableParser matrixT, Estimates data)
        {
            if (matrixT.Rows == null) {
                InstantLogger.err("matrixT.Rows == null");
                return 0;
            }
            using (var l = new Logger("CalcT")) {
                if ((data.CurrentT == 0)
                    || (data.TargetT == 0)
                    || (data.TargetTuMin == 0)
                    || (data.TargetTuMax == 0)
                    || (data.CurrentC == 0)
                    )
                    return 0;
                foreach (var row in matrixT.Rows) {
                    if ((double) (row.Cell["CMin"]) <= data.CurrentC && data.CurrentC < (double) (row.Cell["CMax"])) {
                        l.msg("T item found --- CMin {0}; CMax {1}", row.Cell["CMin"], row.Cell["CMax"]);

                        //var differenceT = data.TargetT - data.CurrentT;
                        double differenceT = (double)(((data.TargetT + (data.TargetT - data.TargetTuMin)) * 0.5) - data.CurrentT); // до середины между целевым и минимальным целевым
                        if (differenceT > 0)
                        {
                            var oxygenOnHeating = (int)(row.Cell["OxygenOnHeating"]);
                            var heating = (int)(row.Cell["Heating"]);
                            double correctionOxy = (double)((((double)oxygenOnHeating) / ((double)heating)) * differenceT);
                            l.msg("Correction Oxygen T = {0}", correctionOxy);
                            return (int)Math.Round(correctionOxy);
                        }
                        else {
                            l.msg("recomend end blow? code:-3");
                            return -3; // рекомендуется закончить продувку

                        }
                    }
                }
            }
            return 0;
        }
        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 static void Iterate()
 {
     using (var l = new Logger("Iterate")) {
         var oxy = Oxigen.Average(SmoothInterval);
         var co = CarbonMonoxide.Average(SmoothInterval);
         if (VerificateB(oxy, co, HotMetallMass) && m_isNotfiredB) // рекомендация кислорода на продувку
         {
             var fex = new ConnectionProvider.FlexHelper("SublanceGenerator.RecommendMetering.B");
             fex.AddArg("OxygenStartValue", m_oxygenStartValue);
             fex.AddArg("CurrentOxygen", oxy);
             fex.AddArg("CurrentCo", co);
             fex.AddArg("CurrentHotMetallMass", HotMetallMass);
             fex.Fire(Program.MainGate);
             string msg = String.Format("SublanceStart fired: \n{0}", fex.evt.ToString());
             l.msg(msg);
             m_isNotfiredB = false;
         }
         if (VerificateK(TargetCk, TargetCku, Ck) && (PeriodNumber == 2) && m_isNotfiredK)
             // команда на старт зонда по углероду и предуставке
         {
             var fex = new ConnectionProvider.FlexHelper("SublanceGenerator.RecommendMetering.K");
             fex.AddArg("TargetCk", TargetCk);
             fex.AddArg("TargetCku", TargetCku);
             fex.AddArg("Ck", Ck);
             fex.AddArg("CurrentOxygen", oxy);
             fex.AddArg("SId", SIdK);
             fex.Fire(Program.MainGate);
             string msg = String.Format("RecommendMetering.K fired: \n{0}", fex.evt.ToString());
             l.msg(msg);
             m_isNotfiredK = false;
         }
         //PeriodNumber = 2;
         if ((PeriodNumber == 2) && m_isNotfiredPrognosis) // начинаем по старту многофакторной
         {
             if (VerificatePrognosis(TargetCk, ReactionTime, Ck)) // команда на старт зонда по прогнозу
             {
                 var fex = new ConnectionProvider.FlexHelper("SublanceGenerator.RecommendMetering.Prognosis");
                 fex.AddArg("TargetCk", TargetCk);
                 fex.AddArg("Ck", Ck);
                 fex.AddArg("CurrentOxygen", oxy);
                 fex.Fire(Program.MainGate);
                 string msg = String.Format("RecommendMetering.Prognosis fired: \n{0}", fex.evt.ToString());
                 l.msg(msg);
                 m_isNotfiredPrognosis = false;
             }
         }
         if (EndMeteringAccept && EndMeteringAlow) {
             EndMetering();
             EndMeteringAccept = false;
             EndMeteringAlow = false;
             l.msg("End metering by iterator");
         }
     }
 }
        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 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);
                    //    }
                    //}
                }
            }
        }