WeightSystem.cs 21.9 KB
Newer Older
潘栩锋's avatar
潘栩锋 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FLY.Modbus;
using System.Xml;
using System.ComponentModel;
using System.Net;
using FLY.Thick.RemoteHistory;
using FLY.Weight.Common;
using FLY.Weight.IService;
using System.Diagnostics;
using FLY.OBJComponents.Server;
using FLY.OBJComponents.IService;
using System.Text.RegularExpressions;
using FLY.OBJComponents.Common;
using FObjBase;
using System.Collections.ObjectModel;

namespace FLY.Weight.Server
{
    public class WeightSystem: IWeightSystemService, Misc.ISaveToXml,IPropertyOpt
    {
        #region 延时推送 MARKNO
        const int MARKNO_SAVE = 1;
        const int MARKNO_DELAY_ISCONNECTED = 4;
        #endregion

        Dictionary<WeighterC, float> LastCumulativeProductions = new Dictionary<WeighterC, float>();
        #region IWeightSystemService 接口

        public ObservableCollection<WeighterC> Items { get; } = new ObservableCollection<WeighterC>();

        public WeighterAccessory Accessory { get; } = new WeighterAccessory();

        private PLCProxySystem plcos = new PLCProxySystem();
        /// <summary>
        /// PLC代理系统
        /// </summary>
        public IPLCProxySystemService PLCos { get { return plcos; } }


        /// <summary>
        /// 流量记录周期,单位s
        /// </summary>
        public int FlowInterval { get; set; } = 10;

        /// <summary>
        /// 流量列表长度,单位个
        /// </summary>
        public int FlowListSize { get; set; } = 10000;
        
        /// <summary>
        /// 层数
        /// </summary>
        public int ItemsCnt { get; private set; } = 3;

        /// <summary>
        /// 每层仓数
        /// </summary>
        public int[] BinCnts { get; private set; } = new int[] { 4, 4, 4 };
        #endregion

        #region 记录集
        /// <summary>
        /// 流量记录
        /// </summary>
        public BufferStorage<FlyData_Flow> FlowList;

        /// <summary>
        /// 每次配料记录
        /// </summary>
        public Dictionary<WeighterC, BufferStorage<FlyData_Mix>> MixBuffer = new Dictionary<WeighterC, BufferStorage<FlyData_Mix>>();
        /// <summary>
        /// 下辊时,总配料比例记录
        /// </summary>
        public Dictionary<WeighterC, BufferStorage<FlyData_Mix>> RollMixBuffer = new Dictionary<WeighterC, BufferStorage<FlyData_Mix>>();
        #endregion

        /// <summary>
        /// 报警系统
        /// </summary>
        public WarningSystem mWarning;

        public WeightSystem()
        {
            Load();
            
            mWarning = new WarningSystem();

            AddConfigFile("WS.xml");


            //--------------------------------------------------------------------------------
            //报警配置
            InitError();

            FObjBase.PollModule.Current.Poll_Config(
                FObjBase.PollModule.POLL_CONFIG.ADD, OnPoll, TimeSpan.FromSeconds(1));


            //--------------------------------------------------------------------------------
            //添加任务
            Misc.BindingOperations.SetBinding(PLCos, "IsConnectedWithPLC", () =>
            {
                if (PLCos.IsConnectedWithPLC)
                {
                    for (int i = 0; i < Items.Count(); i++)
                    {
                        List<string> props = new List<string>();
                        props.Add("BucketValveIsOpen");
                        for (int j = 0; j < Items[i].BinCnt; j++)
                        {
                            int no = j + 1;
                            props.Add("MixDisp_"+no);
                            props.Add("MixPDisp_" + no);
                        }

                        props.Add("CumulativeProduction");

                        props.Add("CurrentFlow");
                        props.Add("ScrewPDisp");
                        props.Add("ScrewMotorFreq");
                        
                        PLCos.SetPlan("Items[" + i + "]", props, 0);
                    }
                    PLCos.SetPlan("Accessory",new string[] { "TotalFlow"}, 0);
                }
            });

            //--------------------------------------------------------------------------------
            //报警
            Misc.BindingOperations.SetBinding(Items[0], "AlarmIsOn", () =>
            {
                mWarning.Enable = !Items[0].AlarmIsOn;
            });
            Misc.BindingOperations.SetBinding(mWarning, "Enable", () =>
            {
                for (int i = 0; i < ItemsCnt; i++)
                {
                    Items[i].AlarmIsOn = !mWarning.Enable;
                }
            });
            
            mWarning.ResetEvent = () =>//复位事件
            {
                for (int i = 0; i < ItemsCnt; i++)
                {
                    Items[i].IsAlarmReseted = false;
                }
            };

            //--------------------------------------------------------------------------------
            //流量记录
            FlowList = new BufferStorage<FlyData_Flow>("flowlist.csv", 5, FlowListSize);

            Misc.BindingOperations.SetBinding(this, "FlowListSize", FlowList, "Capacity");

            //--------------------------------------------------------------------------------
            //配料记录
            foreach (WeighterC w in Items)
            {
                LastCumulativeProductions.Add(w, w.CumulativeProduction);
                w.PropertyChanged += WeightSystem_MBServer_PropertyChanged;
                MixBuffer.Add(w, new BufferStorage<FlyData_Mix>(w.Number + "_mixbuffer.csv", 5, 2000));
                RollMixBuffer.Add(w, new BufferStorage<FlyData_Mix>(w.Number + "_rollmixbuffer.csv", 1, 400));
            }
            //--------------------------------------------------------------------------------
潘栩锋's avatar
1  
潘栩锋 committed
169
            //Test();
潘栩锋's avatar
潘栩锋 committed
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607

            plcos.Init();

            this.PropertyChanged += WeightSystem_PropertyChanged;
        }

        private void WeightSystem_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (GetSavePropertyNames().Contains(e.PropertyName))
            {
                Save();
            }
        }

        private void WeightSystem_MBServer_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            WeighterC w = sender as WeighterC;
            if (e.PropertyName == "BucketValveIsOpen")
            {
                if (w.BucketValveIsOpen)
                {
                    //记录
                    FlyData_Mix f = new FlyData_Mix();

                    f.Time = DateTime.Now;
                    f.Total = w.MixDisp;

                    for (int i = 0; i < w.Ingredients.Count; i++)
                    {
                        FlyData_MixItem item = new FlyData_MixItem()
                        {
                            Disp = w.Ingredients[i].MixDisp,
                            PDisp = w.Ingredients[i].MixPDisp
                        };
                        f.Items.Add(item);
                    }

                    MixBuffer[w].Add(f);
                }
            }
            else if (e.PropertyName == "CumulativeProduction")
            {
                //当累计产量变小,肯定是被clear() 需要保存数据
                if (w.CumulativeProduction < LastCumulativeProductions[w])
                {
                    FlyData_Mix f = new FlyData_Mix();

                    f.Time = DateTime.Now;
                    //TODO 可能这里有问题。。。。
                    f.Total = LastCumulativeProductions[w];
                    for (int i = 0; i < w.Ingredients.Count; i++)
                    {
                        FlyData_MixItem item = new FlyData_MixItem()
                        {
                            Disp = w.Ingredients[i].MixDisp,
                            PDisp = w.Ingredients[i].MixPDisp
                        };
                        f.Items.Add(item);
                    }

                    RollMixBuffer[w].Add(f);
                }
                LastCumulativeProductions[w] = w.CumulativeProduction;
            }
        }

        void Test()
        {
            #region 测试
            Items[0].CurrentFlow = 150;
            Items[0].BinWeight = 15;
            Items[0].MixBucketWeight = 4;
            Items[0].MixPSet_1 = 90;
            Items[0].MixPSet_2 = 5;
            Items[0].MixPSet_3 = 5;
            Items[0].MixPSet_4 = 0;

            Items[1].CurrentFlow = 100;
            Items[1].BinWeight = 10;
            Items[1].MixBucketWeight = 4;
            Items[1].MixPSet_1 = 20;
            Items[1].MixPSet_2 = 70;
            Items[1].MixPSet_3 = 5;
            Items[1].MixPSet_4 = 5;

            Items[2].CurrentFlow = 50;
            Items[2].BinWeight = 5;
            Items[2].MixBucketWeight = 4;
            Items[2].MixPSet_1 = 0;
            Items[2].MixPSet_2 = 70;
            Items[2].MixPSet_3 = 30;
            Items[2].MixPSet_4 = 0;

            Items[2].IsErrorOfAdd_1 = true;
            Items[0].IsErrorOfBlender = true;

            Accessory.TotalFlow = Items.Sum((w) => { return w.CurrentFlow; });

            foreach (WeighterC w in Items)
            {
                w.FlowSetting = w.CurrentFlow;
                w.ScrewPDisp = w.CurrentFlow * 100 / Accessory.TotalFlow;
                w.ScrewPSet = w.ScrewPDisp;
                w.ScrewMotorFreq = 100 * w.CurrentFlow / 300;
                w.CumulativeProduction = w.CurrentFlow * 20;

                w.MixPDisp_1 = w.MixPSet_1;
                w.MixPDisp_2 = w.MixPSet_2;
                w.MixPDisp_3 = w.MixPSet_3;
                w.MixPDisp_4 = w.MixPSet_4;

                w.MixCum_1 = (float)(w.CumulativeProduction * w.MixPSet_1 / 100.0);
                w.MixCum_2 = (float)(w.CumulativeProduction * w.MixPSet_2 / 100.0);
                w.MixCum_3 = (float)(w.CumulativeProduction * w.MixPSet_3 / 100.0);
                w.MixCum_4 = (float)(w.CumulativeProduction * w.MixPSet_4 / 100.0);

                w.MixCumPercent_1 = w.MixPSet_1;
                w.MixCumPercent_2 = w.MixPSet_2;
                w.MixCumPercent_3 = w.MixPSet_3;
                w.MixCumPercent_4 = w.MixPSet_4;
            }


            Accessory.TotalProduction = (UInt16)Items.Sum((w) => { return w.CumulativeProduction; });
            Accessory.TotalFlowSetting = Accessory.TotalFlow;


            Random r = new Random();
            FlyData_Flow last_f = null;
            for (int j = 0; j < FlowListSize; j++)
            {
                FlyData_Flow f = new FlyData_Flow();
                f.Time = DateTime.Now - TimeSpan.FromMinutes((FlowListSize - j) * FlowInterval);
                f.Total = Accessory.TotalFlow;
                f.Items = new FlyData_FlowItem[ItemsCnt];
                for (int i = 0; i < Items.Count; i++)
                {
                    f.Items[i] = new FlyData_FlowItem();
                    f.Items[i].Flow = (float)(Items[i].CurrentFlow + r.NextDouble() * 5 - 2.5);
                    f.Items[i].ScrewPDisp = Items[i].ScrewPDisp;
                    f.Items[i].ScrewMotorFreq = Items[i].ScrewMotorFreq;

                    //f.Items[i].CumulativeProduction = (float)(f.Items[i].Flow * FlowInterval / 60);
                    //if (last_f != null)
                    //{
                    //    f.Items[i].CumulativeProduction += last_f.Items[i].CumulativeProduction;
                    //}

                    //f.Items[i].MixCum[0] = (float)(f.Items[i].CumulativeProduction * Items[i].MixPSet_1 / 100.0);
                    //f.Items[i].MixCum[1] = (float)(f.Items[i].CumulativeProduction * Items[i].MixPSet_2 / 100.0);
                    //f.Items[i].MixCum[2] = (float)(f.Items[i].CumulativeProduction * Items[i].MixPSet_3 / 100.0);
                    //f.Items[i].MixCum[3] = (float)(f.Items[i].CumulativeProduction * Items[i].MixPSet_4 / 100.0);


                    //f.Items[i].MixCumPercent[0] = Items[i].MixPSet_1;
                    //f.Items[i].MixCumPercent[1] = Items[i].MixPSet_2;
                    //f.Items[i].MixCumPercent[2] = Items[i].MixPSet_3;
                    //f.Items[i].MixCumPercent[3] = Items[i].MixPSet_4;
                }
                last_f = f;
                FlowList.Add(f);
            }
            #endregion
        }

        Stopwatch stopwatch = new Stopwatch();
        void OnPoll()
        {
            if (!stopwatch.IsRunning)
            {
                stopwatch.Start();
                return;
            }
            else
            {
                if (FlowInterval < 1)
                    FlowInterval = 1;

                if (stopwatch.Elapsed < TimeSpan.FromSeconds(FlowInterval))
                    return;
                else 
                    stopwatch.Restart();
            }

            if (!PLCos.IsConnectedWithPLC)
                return;

            if (Accessory.TotalFlow < 5)//没有生产
                return;

            FlyData_Flow f = new FlyData_Flow();
            f.Time = DateTime.Now;
            f.Total = Accessory.TotalFlow;
            f.Items = new FlyData_FlowItem[Items.Count];

            for (int i = 0; i < Items.Count; i++)
            {
                f.Items[i] = new FlyData_FlowItem();
                 
                f.Items[i].Flow = Items[i].CurrentFlow;
                f.Items[i].ScrewPDisp = Items[i].ScrewPDisp;
                f.Items[i].ScrewMotorFreq = Items[i].ScrewMotorFreq;
            }

            FlowList.Add(f);
        }
        

        #region 报警
        class ErrorAction
        {
            public Dictionary<string, ERRNO> error_property;
            public delegate void ErrorHandler(ref byte errcode, ref string msg,object state);
            public ErrorHandler action;
            public object state;
        }
        Dictionary<INotifyPropertyChanged, ErrorAction> obj_error = new Dictionary<INotifyPropertyChanged, ErrorAction>();

        void InitError()
        {
            Dictionary<string, ERRNO> error_property = new Dictionary<string, ERRNO>();
            error_property = new Dictionary<string, ERRNO>();
            error_property.Add("IsErrorOfLack_1", ERRNOs.WEIGHT_ERRNO_LACK1);
            error_property.Add("IsErrorOfLack_2", ERRNOs.WEIGHT_ERRNO_LACK2);
            error_property.Add("IsErrorOfLack_3", ERRNOs.WEIGHT_ERRNO_LACK3);
            error_property.Add("IsErrorOfLack_4", ERRNOs.WEIGHT_ERRNO_LACK4);
            error_property.Add("IsErrorOfLack_5", ERRNOs.WEIGHT_ERRNO_LACK5);
            error_property.Add("IsErrorOfLack_6", ERRNOs.WEIGHT_ERRNO_LACK6);
            error_property.Add("IsErrorOfAdd_1", ERRNOs.WEIGHT_ERRNO_ADD1);
            error_property.Add("IsErrorOfAdd_2", ERRNOs.WEIGHT_ERRNO_ADD2);
            error_property.Add("IsErrorOfAdd_3", ERRNOs.WEIGHT_ERRNO_ADD3);
            error_property.Add("IsErrorOfAdd_4", ERRNOs.WEIGHT_ERRNO_ADD4);
            error_property.Add("IsErrorOfAdd_5", ERRNOs.WEIGHT_ERRNO_ADD5);
            error_property.Add("IsErrorOfAdd_6", ERRNOs.WEIGHT_ERRNO_ADD6);
            error_property.Add("IsErrorOfScrewLack", ERRNOs.WEIGHT_ERRNO_SCREWLACK);
            error_property.Add("IsErrorOfScrewFlow", ERRNOs.WEIGHT_ERRNO_SCREWFLOW);
            error_property.Add("IsErrorOfBlender", ERRNOs.WEIGHT_ERRNO_BLENDER);
            error_property.Add("IsErrorOfScram", ERRNOs.WEIGHT_ERRNO_SCRAM);
            error_property.Add("IsErrorOfBlender2", ERRNOs.WEIGHT_ERRNO_BLENDER2);
            error_property.Add("IsErrorOfMixerMotor", ERRNOs.WEIGHT_ERRNO_MIXERMOTOR);

            for (int i = 0; i < Items.Count(); i++)
            {
                obj_error.Add(Items[i], new ErrorAction()
                {
                    error_property = error_property,
                    state = i,
                    action = (ref byte code, ref string description, object state) =>
                    {
                        int idx = (int)state;
                        description = Items[idx].Number + "层 "+ description;
                        code += (byte)(idx*25);
                    },
                    
                });
            }

            foreach (var obj in obj_error.Keys)
            {
                obj.PropertyChanged += Obj_PropertyChanged_ForError;
            }

            //--------------------------------------------------------------------------------
            //添加任务
            Misc.BindingOperations.SetBinding(PLCos, "IsConnectedWithPLC", () =>
            {
                if (PLCos.IsConnectedWithPLC)
                {
                    foreach (var kv in obj_error)
                    {
                        string objname = PLCos.ObjNames.First(_kv => _kv.Value == kv.Key).Key;
                        PLCos.SetPlan(objname, kv.Value.error_property.Keys.ToArray(), 0);
                    }
                }
            });

            //--------------------------------------------------------------------------------
            //连接断开事件
            FObjBase.PollModule.Current.Poll_Config(PollModule.POLL_CONFIG.ADD,
                () =>
                {
                    Misc.BindingOperations.SetBinding(plcos, "IsConnectedWithPLC", () =>
                    {
                        bool b = !PLCos.IsConnectedWithPLC;

                        ERR_STATE state = b ? ERR_STATE.ON : ERR_STATE.OFF;

                        ERRNO errno = ERRNOs.ERRNO_PLC_DISCONNECTED;
                        byte errcode = errno.Code;
                        string description = errno.Descrption;
                        mWarning.Add(errcode, description, state);
                    });
                }, TimeSpan.FromSeconds(3), true, false, this, MARKNO_DELAY_ISCONNECTED, true);

        }

        void Obj_PropertyChanged_ForError(object sender, PropertyChangedEventArgs e)
        {
            ErrorAction errorAction = obj_error[sender as INotifyPropertyChanged];

            if (errorAction.error_property.ContainsKey(e.PropertyName))
            {
                bool b = (bool)Misc.PropertiesManager.GetValue(sender, e.PropertyName);

                ERRNO errno = errorAction.error_property[e.PropertyName];
                ERR_STATE state;
                if (!errno.OffIsError)
                    state = b ? ERR_STATE.ON : ERR_STATE.OFF;
                else
                    state = !b ? ERR_STATE.ON : ERR_STATE.OFF;

                byte errcode = errno.Code;
                string description = errno.Descrption;

                errorAction.action?.Invoke(ref errcode, ref description, errorAction.state);

                mWarning.Add(errcode, description, state);
            }
        }
        #endregion


        void AddConfigFile(string configfile)
        {
            PLCGroup plcgroup = new PLCGroup();
            plcgroup.Load(configfile);


            foreach (PLCGroup.PLCDevice device in plcgroup.Devices)
            {
                ModbusMapper_Client plc = new ModbusMapper_Client(new ClientTCP(device.EP));
                plcos.PLCs.Add(plc);
            }

            List<int> bincnts = new List<int>();
            Regex r = new Regex(@"Items\[([0-9])\]");
            Regex r2 = new Regex("MixPSet_([1-9])");
            //统计有多少层
            //统计每层的仓数
            foreach (PLCGroup.PLCVariable var in plcgroup.Variables)
            {
                Match m = r.Match(var.OwnerName);
                if (m.Success)
                {
                    int weighter_idx = int.Parse(m.Groups[1].Value);
                    if (bincnts.Count() <= weighter_idx)
                    {
                        while (bincnts.Count() <= weighter_idx)
                            bincnts.Add(0);
                    }
                    Match m2 = r2.Match(var.PropertyName);
                    if (m2.Success)
                    {
                        int bincnt = int.Parse(m2.Groups[1].Value);
                        if (bincnts[weighter_idx] < bincnt)
                            bincnts[weighter_idx] = bincnt;
                    }
                }
            }
            BinCnts = bincnts.ToArray();
            ItemsCnt = BinCnts.Count();

            for (int i = 0; i < BinCnts.Count(); i++)
            {
                WeighterC w = new WeighterC(((char)('A'+i)).ToString(), BinCnts[i]);
                Items.Add(w);
            }
            
            //objname 转 obj
            PLCos.ObjNames.Add("Accessory", Accessory);
            for (int i = 0; i < ItemsCnt; i++)
            {
                PLCos.ObjNames.Add("Items[" + i +"]", Items[i]);
            }
            

            foreach (PLCGroup.PLCVariable var in plcgroup.Variables)
            {
                if (var.DeviceIndex < 0 || var.DeviceIndex >= plcos.PLCs.Count)
                    continue;

                List<ModbusMapper.DataToRegs> drs = plcos.DRMap;
                ModbusMapper_Client plc = plcos.PLCs[var.DeviceIndex];


                ModbusMapper.DataToRegs dr = plc.MapDataToRegs(
                    ModbusMapper.TranslateToPLCAddressArea(var.Mode),
                    var.Addr,
                    ModbusMapper.TranslateToREG_TYPE(var.Type),
                    var.Scale,
                    PLCos.ObjNames[var.OwnerName],
                    var.PropertyName);
                if (dr != null)
                    drs.Add(dr);
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void Save()
        {
            Misc.SaveToXmlHepler.Save("weightsystem.xml", this);
        }
        public void Load()
        {
            Misc.SaveToXmlHepler.Load("weightsystem.xml", this);
        }
        #region ISaveToXml 成员

        public string[] GetSavePropertyNames()
        {
            return new string[]{
                "FlowListSize",
                "FlowInterval"
            };
        }


        #endregion


        public string[] GetSyncPropNames()
        {
            return new string[]{
                "FlowInterval",
                "FlowListSize",
                "ItemsCnt",
                "BinCnts"
                };
        }

        public string[] GetNoSyncPropNames()
        {
            return null;
        }
    }
    
}