KNDManager.cs 22.1 KB
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 169 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 608
using log4net;
using URSoldering.Common; 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using URSoldering.LoadCSVLibrary;


namespace URSoldering.DeviceLibrary
{
    /// <summary>
    /// 康奈德IO控制模块
    /// </summary>
   public class KNDManager
   {
       public static ushort DIStartAddress = 200;
       public static ushort DoStartAddress = 100;
       public static ushort DefaultDILength = 16;
       public static ushort DefaultDOLength = 16;
       private static byte DefualtSlaveID = 255;
       public static readonly ILog LOGGER = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
       public static Dictionary<string, MasterTcpClient> mastMap = new Dictionary<string, MasterTcpClient>();
       public static Dictionary<string, List<KNDIO>> DIValueMap = new Dictionary<string, List<KNDIO>>();
       public static Dictionary<string, List<KNDIO>> DOValueMap = new Dictionary<string, List<KNDIO>>();
       private static object DIMapLock = "";
       private static object DOMapLock = "";
       public static System.Timers.Timer timer = null;
       private static  ushort port = 502;
       public static void ConnectionIP(string ioIp )
       {
           if (timer == null)
           {
               timer = new System.Timers.Timer();
               timer.Interval = 1000;
               timer.AutoReset = true;
               timer.Elapsed += timer_Elapsed;
               timer.Enabled = true;
           }
           MasterTcpClient MBmaster = null;
           if (mastMap.ContainsKey(ioIp))
           {
               MBmaster = mastMap[ioIp];
                
               if (null != MBmaster)
               {
                   MBmaster.disconnect();
                   MBmaster.Dispose();
                   MBmaster = null;
                   lock (DIMapLock)
                   {
                       if (DIValueMap.ContainsKey(ioIp))
                       {
                           DIValueMap.Remove(ioIp);
                       }
                   }

                   lock (DOMapLock)
                   {
                       if (DOValueMap.ContainsKey(ioIp))
                       {
                           DOValueMap.Remove(ioIp);
                       }
                   }
               }
               mastMap.Remove(ioIp);
           }
           try
           {
               // Create new modbus master and add event functions
               MBmaster = new MasterTcpClient(ioIp,port);
               MBmaster.OnResponseData += new MasterTcpClient.ResponseData(MBmaster_OnResponseData);
               MBmaster.OnException += new MasterTcpClient.ExceptionData(MBmaster_OnException); 
               MBmaster.autoConnectOfBreak = false;
               mastMap.Add(ioIp, MBmaster);

               Thread.Sleep(10);

               //读取所有的DO
               ReadMultipleDO(ioIp, DefualtSlaveID, DoStartAddress, DefaultDOLength);
                
           }
           catch (Exception error)
           {
               LogUtil.error(LOGGER,"连接IO模块[" + ioIp + "]出错:"+error.ToString());
           }
       }
       /// <summary>
       /// 判断Io模块是否连接
       /// </summary> 
       public static bool IsConnection(string ip)
       {
           try
           {
               List<string> list = new List<string>(mastMap.Keys);
               foreach (string io in list)
               {
                   if (io.Equals(ip))
                   {
                       //判断是否连接,如果没有连接自动重连
                       MasterTcpClient clinet = mastMap[io];

                       if (clinet.ISConnection())
                       {
                           return true;
                       }
                   }
               }
           }
           catch (Exception ex)
           {
               LogUtil.error(LOGGER, "出错啦:" + ex.ToString());
           } return false;
       }
       private static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
       {
           try
           {

               List<string> list = new List<string>(mastMap.Keys);
               foreach (string io in list) 
               {
                   //判断是否连接,如果没有连接自动重连
                   MasterTcpClient clinet = mastMap[io];

                   if (clinet.ISConnection())
                   {
                       //ReadMultipleDI(io, DefualtSlaveID, DIStartAddress, DefualtLength);
                   }
                   else
                   {
                       ConnectionIP(io);
                       LogUtil.error(LOGGER, io + "当前没有连上,重连" + io);
                   }
               }
               
           }
           catch (Exception ex)
           {
               LogUtil.error(LOGGER, "出错啦:"+ex.ToString());
           }
           Thread.Sleep(1);
       }

       public static void ConnectionKND(List<string> DIONameList)
       { 
           foreach (string ip in DIONameList)
           {
               //if (ip.Equals("192.168.10.10"))
               //{
               //    continue;
               //}
               ConnectionIP(ip);
           }
       }

       public static void ReadMultipleDI(string ioIp, byte slaveId, ushort StartAddress, ushort length)
       { 
           ushort ID = 2;
           MasterTcpClient MBmaster = null;
           if (mastMap.ContainsKey(ioIp))
           {
               MBmaster = mastMap[ioIp]; 
               MBmaster.ReadDiscreteInputs(ID, StartAddress, length, slaveId);	 
           }
           else
           {
               LogUtil.error(LOGGER, "ReadSingleDO出错没有连接IO模块:" + ioIp);
           } 
       }
       public static void ReadMultipleDO(string ioIp, byte slaveId, ushort StartAddress, ushort length)
       { 
           ushort ID = 1;
           MasterTcpClient MBmaster = null;
           if (mastMap.ContainsKey(ioIp))
           {
               MBmaster = mastMap[ioIp];
               MBmaster.ReadCoils(ID, StartAddress, length, slaveId);
           }
           else
           {
               LogUtil.error(LOGGER,"ReadSingleDO出错没有连接IO模块:" + ioIp);
           } 
       }
       //关闭所有的DO
       public static void CloseAllDO()
       {
            List<string> keyList = new List<string>(mastMap.Keys);
           foreach (string key in keyList)
           {
               byte[] data = new byte[] { 0,0};
               WriteMultipleDO(key, DefualtSlaveID, DoStartAddress, DefaultDOLength, data);
           } 
       }
         
       public static void CloseAllConnection()
       {
          
           foreach (MasterTcpClient tcp in mastMap.Values)
           {
               tcp.disconnect();

           } mastMap.Clear();

       }
        public static void CloseAllDO(string ioIp, byte slaveId)
        {
            ushort length= DefaultDOLength;
            byte[] bytes = new byte[length];
            for (int i= 0; i < length; i++){
                bytes[i] = 0;
            }
            WriteMultipleDO(ioIp, slaveId, DoStartAddress, length, bytes);
        }
       public static void WriteMultipleDO(string ioIp, byte slaveId, ushort StartAddress, ushort length, byte[] bytes)
       { 
           ushort ID = 6;
           MasterTcpClient MBmaster = null;
           if (mastMap.ContainsKey(ioIp))
           {
               MBmaster = mastMap[ioIp];
               MBmaster.WriteMultipleCoils(ID, StartAddress, length, bytes, slaveId);
           }
           else
           {
               LogUtil.error(LOGGER, "ReadSingleDO出错没有连接IO模块:" + ioIp);
           } 
       }
       public static void WriteSingleDO(string ioIp, byte slaveId, ushort StartAddress, IO_VALUE onOff)
       { 
           ushort ID = 5;
           MasterTcpClient MBmaster = null;
           if (mastMap.ContainsKey(ioIp))
           {
               MBmaster = mastMap[ioIp];
               MBmaster.WriteSingleCoils(ID, StartAddress, onOff, slaveId);

               KNDIO io = new KNDIO(ioIp, slaveId, StartAddress, onOff);
               SaveDOValue(io, ioIp);
           }
           else
           {
               LogUtil.error(LOGGER, "ReadSingleDO出错没有连接IO模块:" + ioIp);
           }
            
       }
       public static void WriteSingleDO(string ioIp, byte slaveId, ushort StartAddress, IO_VALUE onOff, int mSeconds)
       { 
           ushort ID = 5;
           MasterTcpClient MBmaster = null;
           if (mastMap.ContainsKey(ioIp))
           {
               MBmaster = mastMap[ioIp];
               MBmaster.WriteSingleCoils(ID, StartAddress, onOff, slaveId);

               KNDIO io = new KNDIO(ioIp, slaveId, StartAddress, onOff);
               SaveDOValue(io, ioIp);

               //写入之后,等待指定间隔后回写
               System.Timers.Timer mytimer = new System.Timers.Timer(mSeconds);
               mytimer.Elapsed += (o1, e1) =>
               {
                   try
                   {
                       IO_VALUE newValue = IO_VALUE.LOW;
                       if (onOff.Equals(IO_VALUE.LOW))
                       {
                           newValue = IO_VALUE.HIGH;
                       }
                       MBmaster.WriteSingleCoils(ID, StartAddress, newValue, slaveId);
                       KNDIO newIo = new KNDIO(ioIp, slaveId, StartAddress, newValue);
                       SaveDOValue(newIo, ioIp);
                       LogUtil.info(LOGGER, " 定时回写IO【" + ioIp + "," + StartAddress + ",值" + onOff + "】");
                   }
                   catch (Exception ex)
                   {
                       LogUtil.error(LOGGER, " 定时回写出错:" + ex.StackTrace);
                   }
               };
               mytimer.AutoReset = false;//设置是否自动重启,即自动执行多次;
               mytimer.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件mytask;
           }
           else
           {
               LogUtil.error(LOGGER, "ReadSingleDO出错没有连接IO模块:" + ioIp);
           }  
       }

       private static void SaveDOValue(KNDIO io, string ioIp)
       {
           try
           {
               lock (DOMapLock)
               {
                   if (!DOValueMap.ContainsKey(ioIp))
                   {
                       DOValueMap.Add(ioIp, new List<KNDIO>());
                       DOValueMap[ioIp].Add(io);
                   }
                   else
                   {
                       List<KNDIO> ios = DOValueMap[ioIp];
                       List<KNDIO> list = (from m in ios where m.SlaveId.Equals(io.SlaveId) && m.IOAddress.Equals(io.IOAddress) select m).ToList<KNDIO>();
                       if (list.Count > 0)
                       {
                           DOValueMap[ioIp].Remove(list[0]);
                           DOValueMap[ioIp].Add(io);
                       }
                       else
                       {
                           DOValueMap[ioIp].Add(io);
                       }
                   }
               }
           }
           catch (Exception ex)
           {
              LogUtil.error(LOGGER,"SaveDOValue出错:"+ex.ToString());
           }
       }
       public static IO_VALUE GetDOValue(string ioIP, byte slaveId, ushort StartAddress)
       {
           IO_VALUE value = IO_VALUE.LOW;
            
           if (DOValueMap.ContainsKey(ioIP))
           {
               List<KNDIO> allIo = new List<KNDIO>(DOValueMap[ioIP]); 
               List<KNDIO> list = (from m in allIo where m.SlaveId.Equals(slaveId) && m.IOAddress.Equals(StartAddress) select m).ToList<KNDIO>();
               if (list.Count > 0)
               {
                   value = list[0].IoValue;
               }
           } 
           return value;
       }

       public static IO_VALUE GetDIValue(string ioIP, byte slaveId, ushort StartAddress)
       {
           IO_VALUE value = IO_VALUE.LOW;            
           if (DIValueMap.ContainsKey(ioIP))
           {
               List<KNDIO> allIo = new List<KNDIO>(DIValueMap[ioIP]);             
               List<KNDIO> list = (from m in allIo where m.SlaveId.Equals(slaveId) && m.IOAddress.Equals(StartAddress) select m).ToList<KNDIO>();
               if (list.Count > 0)
               {
                   value = list[0].IoValue;
               }
           }        
           return value;
       }
       public static IO_VALUE GetIOValue(ConfigIO configIO)
       {
           IO_VALUE value = IO_VALUE.LOW;
           try
           {
               if (configIO.ProType.Equals(ConfigItemType.DI))
               {
                   if (DIValueMap.ContainsKey(configIO.DeviceName))
                   {
                       List<KNDIO> allIo = new List<KNDIO>(DIValueMap[configIO.DeviceName]);
                       List<KNDIO> list = (from m in allIo where m.IOAddress.Equals(configIO.GetIOValue()) select m).ToList<KNDIO>();
                       if (list.Count > 0)
                       {
                           value = list[0].IoValue;
                       }
                   }
               }
               else if (configIO.ProType.Equals(ConfigItemType.DO))
               {
                   if (DOValueMap.ContainsKey(configIO.DeviceName))
                   {
                       List<KNDIO> allIo = new List<KNDIO>(DOValueMap[configIO.DeviceName]);
                       List<KNDIO> list = (from m in allIo where m.SlaveId.Equals(configIO.SlaveID) && m.IOAddress.Equals(configIO.GetIOValue()) select m).ToList<KNDIO>();
                       if (list.Count > 0)
                       {
                           value = list[0].IoValue;
                       }
                   }

               }
           }
           catch (Exception ex)
           {
               LogUtil.error(LOGGER, "获取数据出错:" + ex.ToString());
           }
           return value;
       }
       private static void SaveDIData(string ioIp, ushort ID, byte[] values)
       {
           try
           {
               string finalData = "";
               if (values.Length == 2 && DefaultDILength.Equals(16))
               {
                   string finalData0 = Convert.ToString(values[0], 2).PadLeft(8, '0');
                   string finalData1 = Convert.ToString(values[1], 2).PadLeft(8, '0');
                   finalData = finalData1 + finalData0;
               } 
               else if (values.Length == 1 && DefaultDILength<=8)
               {
                   finalData = Convert.ToString(values[0], 2).PadLeft(DefaultDILength, '0');
               }
               
               if (finalData.Length >= DefaultDILength)
               {
                   List<KNDIO> kndList = new List<KNDIO>();
                   ushort index = (ushort)(DIStartAddress + DefaultDILength - 1);
                   foreach (char str in finalData)
                   {
                       KNDIO io = null;
                       if (str.Equals('1'))
                       {
                           io = new KNDIO(ioIp, (byte)ID, index, IO_VALUE.HIGH);
                       }
                       else
                       {
                           io = new KNDIO(ioIp, (byte)ID, index, IO_VALUE.LOW);
                       }
                       kndList.Add(io);
                       index--;
                   }
                   lock (DIMapLock)
                   {
                       if (DIValueMap.ContainsKey(ioIp))
                       {
                           DIValueMap.Remove(ioIp);
                       }
                       DIValueMap.Add(ioIp, kndList);
                   }
               }
           }
           catch (Exception ex)
           {
               LogUtil.error(LOGGER, "SaveDIData出错:" + ex.ToString());
               //LOGGER.Error("处理接受数据出错:", ex);
           }
       }

       private static void SaveDOData(string ioIp, ushort ID, byte[] values)
       {
           string finalData = "";
           if (values.Length == 2 && DefaultDOLength.Equals(16))
           {
               string finalData0 = Convert.ToString(values[0], 2).PadLeft(8, '0');
               string finalData1 = Convert.ToString(values[1], 2).PadLeft(8, '0');
               finalData = finalData1 + finalData0;
           }
           else if (values.Length == 1 && DefaultDOLength<=8)
           {
               finalData = Convert.ToString(values[0], 2).PadLeft(DefaultDOLength, '0');
           }
           if (finalData.Length >= DefaultDOLength)
           {
               List<KNDIO> kndList = new List<KNDIO>();
               ushort index = (ushort)(DoStartAddress + DefaultDOLength - 1);
               foreach (char str in finalData)
               {
                   KNDIO io = null;
                   if (str.Equals('1'))
                   {
                       io = new KNDIO(ioIp, (byte)ID, index, IO_VALUE.HIGH);
                   }
                   else
                   {
                       io = new KNDIO(ioIp, (byte)ID, index, IO_VALUE.LOW);
                   }
                   kndList.Add(io);
                   index--;
               }
               lock (DOMapLock)
               {
                   if (DOValueMap.ContainsKey(ioIp))
                   {
                       DOValueMap.Remove(ioIp);
                   }
                   DOValueMap.Add(ioIp, kndList);
               }
           }

       }
       // ------------------------------------------------------------------------
       // Event for response data
       // ------------------------------------------------------------------------
       private static void MBmaster_OnResponseData(string ioIp, ushort ID, byte function, byte[] values, byte[] reviceData)
       {
           try
           {
               if (ioIp.IndexOf(":") > 0)
               {
                   ioIp = ioIp.Substring(0, ioIp.IndexOf(":"));
               }
               string reviceMsg = "";
               foreach (byte data in reviceData)
               {
                   reviceMsg = reviceMsg + " " + data;
                   if (reviceMsg.Length > 200)
                   {
                       break;
                   }
               }
               if (ID == 0xFF)
               {
                   return;
               }
               // ------------------------------------------------------------------------
               // Identify requested data
               ushort Func = ID;

               if (Func == 0 && reviceData.Length > 8)
               {
                   Func = reviceData[7];
               }
               byte SlaveId = 0xFF;
               if (reviceData.Length >= 7)
               {
                   SlaveId = reviceData[6];
               }
               switch (Func)
               {
                   case 1:
                       LOGGER.Info("Read coils end:【" + reviceMsg + "】 ");
                       SaveDOData(ioIp, SlaveId, values);
                       break;
                   case 2:
                       //LOGGER.Info("Read discrete inputs end:【" + reviceMsg + "】  ");
                       SaveDIData(ioIp, SlaveId, values);
                       break;
                   case 3:
                       //LOGGER.Info("读入(多个)寄存器完成 end:【" + reviceMsg + "】 ");
                       break;
                   case 4:
                       //LOGGER.Info("读入(多个)寄存器完成 end:【" + reviceMsg + "】 ");
                       break;
                   case 5:
                       //LOGGER.Info("Write single coil:【" + reviceMsg + "】 ");
                       break;

               }
           }
           catch (Exception ex)
           {
               LogUtil.error(LOGGER, "处理接受数据出错:" + ex.ToString());
               //LOGGER.Error("处理接受数据出错:", ex);
           }
       }


       // ------------------------------------------------------------------------
       // Modbus TCP slave exception
       // ------------------------------------------------------------------------
       private static void MBmaster_OnException(string ioIp, ushort id, byte function, byte exception, byte[] reviceData)
       {
           string exc = "Modbus says error: ";
           switch (exception)
           {
               case MasterTcpClient.excIllegalFunction: exc += "Illegal function!"; break;
               case MasterTcpClient.excIllegalDataAdr: exc += "Illegal data adress!"; break;
               case MasterTcpClient.excIllegalDataVal: exc += "Illegal data value!"; break;
               case MasterTcpClient.excSlaveDeviceFailure: exc += "Slave device failure!"; break;
               case MasterTcpClient.excAck: exc += "Acknoledge!"; break;
               case MasterTcpClient.excSlaveIsBusy: exc += "Slave is busy!"; break;
               case MasterTcpClient.excGatePathUnavailable: exc += "Gateway path unavailbale!"; break;
               case MasterTcpClient.excExceptionTimeout: exc += "Slave timed out!"; break;
               case MasterTcpClient.excExceptionConnectionLost: exc += "Connection is lost!"; break;
               case MasterTcpClient.excExceptionNotConnected: exc += "Not connected!"; break;
               default:
                   break;
           }
           LOGGER.Error("接收数据出错:"+ exc);
           //MessageBox.Show(exc, "Modbus slave exception");
       } 
   }

   public class KNDIO
   {

       public KNDIO(string ioIp, byte ID, ushort index, IO_VALUE o_VALUE)
       {
           this.IoIP = ioIp;
           this.SlaveId = ID;
           this.IOAddress = index;
           this.IoValue = o_VALUE;
           UpdateTime = DateTime.Now;
       }
       /// <summary>
       /// IO模块IP
       /// </summary>
       public string IoIP { get; set; }
       /// <summary>
       /// 地址
       /// </summary>
       public byte SlaveId { get; set; }
       /// <summary>
       /// 寄存器地址
       /// </summary>
       public ushort IOAddress { get; set; }
       /// <summary>
       /// 值
       /// </summary>
       public IO_VALUE IoValue { get; set; }
       /// <summary>
       /// 更新时间
       /// </summary>
       public DateTime  UpdateTime { get; set; }
   }
}