KNDAIManager.cs 16.6 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
using log4net;
using OnlineStore.Common;
using OnlineStore.LoadCSVLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
//using FuBaRobot.LoadCSVLibrary;


namespace OnlineStore.DeviceLibrary
{
    /// <summary>
    /// 康奈德IO控制模块
    /// </summary>
    public class KNDAIManager : AIManager
    {

        public ushort DefaultAILength = 8;
        public byte DefualtSlaveID = 255;
        private string AIStartAddress = "0258";
        public Dictionary<string, AITcpClient> mastMap = new Dictionary<string, AITcpClient>();
        public Dictionary<string, List<KNDAI>> AIValueMap = new Dictionary<string, List<KNDAI>>();
        private object AIMapLock = "";

        public System.Timers.Timer timer = null;
        private ushort port = 502;

        //public static bool IsNeedReadAI = true;
        public override void StartConnect(params string[] ioIps)
        {
            if (timer == null)
            {
                timer = new System.Timers.Timer();
                timer.Interval = 300;
                timer.AutoReset = true;
                timer.Elapsed += timer_Elapsed;
                timer.Enabled = true;
            }
            AITcpClient MBmaster = null;
            foreach (string ioIp in ioIps)
            {
                if (mastMap.ContainsKey(ioIp))
                {
                    MBmaster = mastMap[ioIp];

                    if (null != MBmaster)
                    {
                        MBmaster.disconnect();
                        MBmaster.Dispose();
                        MBmaster = null;
                        lock (AIMapLock)
                        {
                            if (AIValueMap.ContainsKey(ioIp))
                            {
                                AIValueMap.Remove(ioIp);
                            }
                        }
                    }
                    mastMap.Remove(ioIp);
                }
                try
                {
                    // Create new modbus master and add event functions
                    MBmaster = new AITcpClient(ioIp, port);
                    MBmaster.OnResponseData += new AITcpClient.ResponseData(MBmaster_OnResponseData);
                    MBmaster.OnException += new AITcpClient.ExceptionData(MBmaster_OnException);
                    MBmaster.autoConnectOfBreak = false;
                    mastMap.Add(ioIp, MBmaster);
                    LogUtil.info("连接AI模块[" + ioIp + "]成功");
                    Thread.Sleep(10);
                    WriteAIScope(ioIp, 1);
                    Thread.Sleep(10);
                    ReadAll(ioIp);
                }

                catch (Exception error)
                {
                    LogUtil.error("连接AI模块[" + ioIp + "]出错:" + error.ToString());
                }
            }
        }

        private void ReadAll(string ioIp)
        {
            //读取所有的DO
            ReadMultipleAI(ioIp, DefualtSlaveID, AIStartAddress, DefaultAILength);
        }

        /// <summary>
        /// 判断Io模块是否连接
        /// </summary> 
        public bool IsConnection(string ip)
        {
            try
            {
                List<string> list = new List<string>(mastMap.Keys);
                foreach (string io in list)
                {
                    if (io.Equals(ip))
                    {
                        //判断是否连接,如果没有连接自动重连
                        AITcpClient clinet = mastMap[io];

                        if (clinet.ISConnection())
                        {
                            return true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtil.error("出错啦:" + ex.ToString());
            }
            return false;
        }
        private DateTime PreCheckTime = DateTime.Now;
        private bool isProcess = false;
       
        private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (isProcess)
            {
                return;
            }
            try
            {
                isProcess = true;
                bool IsNeedReadAI = IOManager.IOValue(IO_Type.TrayCheck_Door).Equals(IO_VALUE.HIGH) || NeedShow;
                TimeSpan span = DateTime.Now - PreCheckTime;
                List<string> list = new List<string>(mastMap.Keys);
                foreach (string IP in list)
                {
                    //判断是否连接,如果没有连接自动重连
                    AITcpClient clinet = mastMap[IP];
                    if (!IsNeedReadAI)
                    {
                        ClearAIData(IP);
                        continue;
                    }

                    if (clinet.ISConnection())
                    {
                        ReadAll(clinet.IP);
                    }
                    else if (span.TotalSeconds > 3)
                    {
                        LogUtil.error("AI模块" + IP + "当前没有连上,重连" + IP);
                        StartConnect(IP);
                        PreCheckTime = DateTime.Now;
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtil.error("出错啦:" + ex.ToString());
            }
            Thread.Sleep(2);
            isProcess = false;
        }

        private void WriteAIScope(string ioIp, int value)
        {
            // 0 表示 0 - 10V, 1 表示 0 - 5V
            WriteAIScope(ioIp, DefualtSlaveID, "03EA", value);
        }
        private void WriteAIScope(string ioIp, byte slaveId, string Adress, int value)
        {
            //     写 AI 模块采样范围,可以往寄存器里面写入 0 或 1。 0 表示 0 - 10V, 1 表示 0 - 5V。默
            //认 0,写 AI 模块采样范围为 0 - 5V
            ushort ID = 1;
            AITcpClient MBmaster = null;
            if (mastMap.ContainsKey(ioIp))
            {
                MBmaster = mastMap[ioIp];
                MBmaster.WriteAIScope(ID, slaveId, Adress, value);
            }
            else
            {
                LogUtil.error("WriteAIScope出错没有连接AI模块:" + ioIp);
            }
        }
        private void ReadMultipleAI(string ioIp, byte slaveId, string StartAddress, int length)
        {
            ushort ID = 1;
            AITcpClient MBmaster = null;
            if (mastMap.ContainsKey(ioIp))
            {
                MBmaster = mastMap[ioIp];
                MBmaster.ReadAllAI(ID, StartAddress, length * 2, slaveId);
            }
            else
            {
                LogUtil.error("ReadMultipleAI出错没有连接AI模块:" + ioIp);
            }
        }
        public override void CloseConnect()
        {
            List<AITcpClient> list = new List<AITcpClient>();
            foreach (AITcpClient tcp in list)
            {
                tcp.disconnect();
            }
            mastMap.Clear();
        }
     
        public override double GetAIValue(string ioiP, int index)
        {
            double aiValue = GetAIValue(ioiP, DefualtSlaveID, index - 1); 
            return Math.Round(aiValue, 2);
        }

        public double GetAIValue(string ioIP, byte slaveId, int index)
        {
            double value = 0;
            try
            {
                lock (AIMapLock)
                {
                    if (AIValueMap.ContainsKey(ioIP))
                    {
                        List<KNDAI> allIo = new List<KNDAI>(AIValueMap[ioIP]);
                        List<KNDAI> list = (from m in allIo where m.SlaveId.Equals(slaveId) && m.AIIndex.Equals(index) select m).ToList<KNDAI>();
                        if (list.Count > 0)
                        {
                            value = list[0].AIValue;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtil.error("GetAIValue  出错了 :ioIP[" + ioIP + "]index[" + index + "]:" + ex);
            }
            return value;
        }
        private void ClearAIData(string ioIp)
        {
            byte[] datas = new byte[32];
            for (int i = 0; i < datas.Length; i++)
            {
                datas[i] = 0;
            }
            SaveAIData(ioIp, 3, datas);
        }
        private void SaveAIData(string ioIp, ushort ID, byte[] values)
        {
            try
            {
                if (values.Length.Equals(DefaultAILength * 4))
                {
                    List<KNDAI> kndList = new List<KNDAI>();

                    string strFromat = "{0:X2}";

                    string msg = "";
                    for (int index = 0; index < DefaultAILength; index++)
                    {
                        string str1 = String.Format(strFromat, values[index * 4 + 2]) + String.Format(strFromat, values[index * 4 + 3])
                            + String.Format(strFromat, values[index * 4 + 1]) + String.Format(strFromat, values[index * 4]);

                        double value = BitToFloat(str1);
                        KNDAI io = new KNDAI(ioIp, (byte)DefualtSlaveID, index, value);
                        if (value > 0)
                        {
                            Console.WriteLine(str1 + " float convert = {0}", value);
                        }
                        msg += "【" + index + "=" + value + "】";
                        kndList.Add(io);
                    }
                    //LogUtil.info(msg);
                    lock (AIMapLock)
                    {
                        if (AIValueMap.ContainsKey(ioIp))
                        {
                            AIValueMap.Remove(ioIp);
                        }
                        AIValueMap.Add(ioIp, kndList);
                    }
                    try
                    {
                        if (StoreManager.Store != null && IOManager.IOValue(IO_Type.TrayCheck_Door).Equals(IO_VALUE.HIGH))
                        {
                            if (StoreManager.Config.AIDI1_Addr > 0 && StoreManager.Config.AIDI2_Addr > 0)
                            {    //每次上传后验证下
                                int v1 = (int)GetAIValue(ioIp, StoreManager.Config.AIDI1_Addr);
                                int v2 = (int)GetAIValue(ioIp, StoreManager.Config.AIDI2_Addr);
                                if (v1.Equals(0) && v2.Equals(0))
                                {
                                    LogUtil.info(msg);
                                    string value = AcSerialBean.ByteToString(values);
                                    LogUtil.error("收到【" + ioIp + "】的数据【" + value + "】,2个高度都为0");
                                    // ConnectionIP(ioIp);
                                }
                            }
                            else if (StoreManager.Config.AIDI3_Addr > 0 && StoreManager.Config.AIDI4_Addr > 0)
                            {    //每次上传后验证下
                                int v1 = (int)GetAIValue(ioIp, StoreManager.Config.AIDI3_Addr);
                                int v2 = (int)GetAIValue(ioIp, StoreManager.Config.AIDI4_Addr);
                                if (v1.Equals(0) && v2.Equals(0))
                                {
                                    LogUtil.info(msg);
                                    string value = AcSerialBean.ByteToString(values);
                                    LogUtil.error("收到【" + ioIp + "】的数据【" + value + "】,2个高度都为0");
                                    // ConnectionIP(ioIp);
                                }
                            }
                        }

                    }
                    catch (Exception ex)
                    {
                        LogUtil.error("验证数据出错:" + ex.StackTrace);
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtil.error("SaveAIData出错:" + ex.ToString());
            }
        }

        private   float BitToFloat(string hexString)
        {
            uint num = uint.Parse(hexString, System.Globalization.NumberStyles.AllowHexSpecifier);
            byte[] floatVals = BitConverter.GetBytes(num);
            float f = BitConverter.ToSingle(floatVals, 0);
            return f;
        }
        private   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 strFromat = "{0:X2}";
                string reviceMsg = "";
                foreach (byte data in reviceData)
                {
                    reviceMsg = reviceMsg + " " + String.Format(strFromat, data);
                    if (reviceMsg.Length > 200)
                    {
                        break;
                    }
                }
                //   LOGGER.Info ("Read data:【" + reviceMsg + "】  ");
                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 (function)
                {
                    case 1:
                        //LOGGER.Info("Read coils end:【" + reviceMsg + "】 ");

                        break;
                    case 2:
                        //LOGGER.Info("Read discrete inputs end:【" + reviceMsg + "】  ");
                        //SaveAIData(ioIp, SlaveId, values);
                        break;
                    case 3:

                        SaveAIData(ioIp, ID, values);
                        break;
                    case 4:
                        //LOGGER.Info("读入(多个)寄存器完成 end:【" + reviceMsg + "】 ");
                        break;
                    case 5:
                        //LOGGER.Info("Write single coil:【" + reviceMsg + "】 ");
                        break;

                }
            }
            catch (Exception ex)
            {
                LogUtil.error("处理接受数据出错:" + ex.ToString());
            }
        }
        private void MBmaster_OnException(string ioIp, ushort id, byte function, byte exception, byte[] reviceData)
        {
            string exc = "Modbus says error: ";
            switch (exception)
            {
                case AITcpClient.excIllegalFunction: exc += "Illegal function!"; break;
                case AITcpClient.excIllegalDataAdr: exc += "Illegal data adress!"; break;
                case AITcpClient.excIllegalDataVal: exc += "Illegal data value!"; break;
                case AITcpClient.excSlaveDeviceFailure: exc += "Slave device failure!"; break;
                case AITcpClient.excAck: exc += "Acknoledge!"; break;
                case AITcpClient.excSlaveIsBusy: exc += "Slave is busy!"; break;
                case AITcpClient.excGatePathUnavailable: exc += "Gateway path unavailbale!"; break;
                case AITcpClient.excExceptionTimeout: exc += "Slave timed out!"; break;
                case AITcpClient.excExceptionConnectionLost: exc += "Connection is lost!"; break;
                case AITcpClient.excExceptionNotConnected: exc += "Not connected!"; break;
                default:
                    break;
            }
            LogUtil.error("接收数据出错:" + exc);
        }
    }

    public class KNDAI
    {

        public KNDAI(string ioIp, byte ID, int index, double value)
        {
            this.IoIP = ioIp;
            this.SlaveId = ID;
            this.AIIndex = index;
            this.AIValue = value;
            UpdateTime = DateTime.Now;
        }
        /// <summary>
        /// AI模块IP
        /// </summary>
        public string IoIP { get; set; }
        /// <summary>
        /// 地址
        /// </summary>
        public byte SlaveId { get; set; }
        /// <summary>
        /// 第几个AI
        /// </summary>
        public int AIIndex { get; set; }
        /// <summary>
        /// 值
        /// </summary>
        public double AIValue { get; set; }
        /// <summary>
        /// 更新时间
        /// </summary>
        public DateTime UpdateTime { get; set; }
    }
}