OPCImplement.cs 15.9 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
using Hh.Mes.Common.Json;
using Hh.Mes.POJO.BllModel;
using Hh.Mes.POJO.Entity;
using HHECS.Model.PLCHelper.Interfaces;
using HHECS.Model.PLCHelper.PLCComponent;
using OPCAutomation;
using System;
using System.Collections.Generic;
using System.Linq;

namespace HHECS.Model.PLCHelper.Implement
{
    /// <summary>
    /// 封装OPC
    /// 使用此类,请先行传递OPCIP并赋值完整Equipments,然后使用连接函数
    /// </summary>
    public class OPCImplement : IPLC
    {
        public string OPCIP { get; set; }
        public OPCServer s7 = new OPCServer();
        public OPCGroup s7Group;

        /// <summary>
        /// 需要在连接前事先完整设置
        /// </summary>
        public List<base_equipment> Equipments { get; set; }
        public string Name { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
        public string IP { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
        public PLCType PLCType { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }

        public OPCImplement(string IP)
        {
            OPCIP = IP;
        }

        /// <summary>
        /// 创建组
        /// </summary>
        public bool CreateGroup(string name)
        {
            try
            {
                s7Group = s7.OPCGroups.Add(name);
                SetGroupProperty();
            }
            catch (Exception)
            {
                //MessageBox.Show("创建组出现错误:" + err.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 设置组属性
        /// </summary>
        private void SetGroupProperty()
        {
            s7.OPCGroups.DefaultGroupIsActive = true;
            s7.OPCGroups.DefaultGroupDeadband = 0;
            s7Group.UpdateRate = 100;// 刷新率 ms  ,原为250,更改为100
            s7Group.IsActive = true;  //设置该组为激活状态
            s7Group.IsSubscribed = false;//设置该组数据为后台刷新
        }

        public BllResult Connect()
        {
            try
            {
                s7.Connect("OPC.SimaticNET", OPCIP);
                if (s7.ServerState == (int)OPCServerState.OPCRunning)
                {
                    //注册地址
                    Equipments.SelectMany(t => t.EquipmentProps).ToList().ForEach(t =>
                    {
                        t.Equipment = Equipments.FirstOrDefault(i => i.id == t.equipmentId);
                        //组合地址
                        if (!t.address.StartsWith("S7"))
                        {
                            t.address = $"S7:[{t.Equipment.connectName}]{t.address}";
                        }
                    });
                    CreateGroup("group1");
                    AddOPCItems(Equipments.SelectMany(t => t.EquipmentProps).ToList());
                    return BllResultFactory.Success();
                }
                else
                {
                    return BllResultFactory.Error();
                }
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error(ex.Message);
            }
        }

        /// <summary>
        /// 添加地址
        /// </summary>
        /// <param name="props"></param>
        public void AddOPCItems(List<base_equipment_prop> props)
        {
            string[] ids = new string[props.Count() + 1];
            int[] clients = new int[props.Count() + 1];
            ids[0] = "";
            clients[0] = 0;
            for (int i = 1; i < ids.Length; i++)
            {
                ids[i] = props[i - 1].address;
                clients[i] = i;
            }
            Array clientsIds = (Array)clients;
            Array itemsIds = (Array)ids;
            Array serverHandls;
            Array errors;
            s7Group.OPCItems.AddItems(props.Count(), ref itemsIds, ref clientsIds, out serverHandls, out errors);
            for (int i = 0; i < props.Count(); i++)
            {
                props[i].serverHandle = Convert.ToInt32(serverHandls.GetValue(i + 1));
            }

        }

        public BllResult DisConnect()
        {
            try
            {
                s7.Disconnect();
                if (s7.ServerState == (int)OPCServerState.OPCDisconnected)
                {
                    return BllResultFactory.Success();
                }
                else
                {
                    return BllResultFactory.Error();
                }
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error(ex.Message);
            }
        }

        /// <summary>
        /// 连接,指定IP,使用OPC则指定对OPC服务的连接
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public BllResult Connect(string ip)
        {
            return Connect();
        }

        /// <summary>
        /// 断开连接,指定IP,使用OPC则指定对OPC服务的断开连接
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public BllResult DisConnect(string ip)
        {
            return DisConnect();
        }

        public BllResult GetConnectStatus()
        {
            if (s7.ServerState == (int)OPCServerState.OPCRunning)
            {
                return BllResultFactory.Success();
            }
            else
            {
                return BllResultFactory.Error();
            }
        }

        public BllResult GetConnectStatus(string plcIp)
        {
            if (s7.ServerState == (int)OPCServerState.OPCRunning)
            {
                return BllResultFactory.Success();
            }
            else
            {
                return BllResultFactory.Error();
            }
        }

        public BllResult Read(base_equipment_prop equipmentProp)
        {
            return Reads(new List<base_equipment_prop>() { equipmentProp });
        }

        public BllResult Reads(List<base_equipment_prop> equipmentProps)
        {
            if (equipmentProps == null || equipmentProps.Count == 0)
            {
                return BllResultFactory.Error("无地址传入");
            }
            if (this == null || this.GetConnectStatus().Success == false)
            {
                return BllResultFactory.Error("地址读取失败,请检查通讯连接");
            }

            int[] handles = equipmentProps.Select(t => t.serverHandle).ToArray();
            return this.ReadData(handles, equipmentProps);
        }

        /// <summary>
        /// 读取数据,成功返回值,失败返回null
        /// 按照 OPC 规范,数组始终以索引 1 开始。
        /// </summary>
        public BllResult ReadData(int[] handle, List<base_equipment_prop> equipmentProps)
        {
            try
            {
                int count = handle.Length;
                int[] temp = new int[count + 1];
                temp[0] = 0;
                for (int i = 1; i < temp.Length; i++)
                {
                    temp[i] = handle[i - 1];
                }
                Array serverHandles = (Array)temp;
                Array values;
                Array Errors;
                object Qualities;
                object TimeStamps;
                //OPCAutomation.OPCDataSource.OPCCache;
                s7Group.SyncRead(1, count, ref serverHandles, out values, out Errors, out Qualities, out TimeStamps);
                var a = (Array)Qualities;
                for (int i = 1; i < serverHandles.Length; i++)
                {
                    var prop = equipmentProps.Find(t => t.serverHandle == (int)serverHandles.GetValue(i));
                    if ((Int16)a.GetValue(i) == 0)
                    {
                        //读取失败,获取默认值
                        prop.value = GetDefaultValue(prop);

                    }
                    else
                    {
                        //读取成功
                        if (!Enum.TryParse(prop.EquipmentTypePropTemplate.dataType, out PLCDataType dataType))
                        {
                            return BllResultFactory.Error($"未识别的数据类型:{prop.EquipmentTypePropTemplate.dataType}");
                        }
                        else
                        {
                            var result = TransforAddressDataToWCSData(dataType, values.GetValue(i));
                            if (!result.Success)
                            {
                                return BllResultFactory.Error($"读取PLC地址时:属性{prop.EquipmentTypePropTemplate.code};错误消息:{result.Msg}");
                            }
                            prop.value = result.Data;
                        }
                    }
                }
                return BllResultFactory.Success();
            }
            catch (Exception err)
            {
                return BllResultFactory.Error(err.Message);
            }
        }

        public BllResult Write(base_equipment_prop equipmentProp)
        {
            return Writes(new List<base_equipment_prop>() { equipmentProp });
        }

        public BllResult Writes(List<base_equipment_prop> equipmentProps)
        {
            if (equipmentProps == null || equipmentProps.Count == 0)
            {
                return BllResultFactory.Error("无地址传入");
            }
            if (this == null || GetConnectStatus().Success == false)
            {
                return BllResultFactory.Error("地址读取失败,请检查通讯连接");
            }
            var serverHandel = equipmentProps.Select(t => t.serverHandle).ToArray();
            object[] values = new object[serverHandel.Count()];
            for (int i = 0; i < equipmentProps.Count; i++)
            {
                if (!Enum.TryParse(equipmentProps[i].EquipmentTypePropTemplate.dataType, out PLCDataType dataType))
                {
                    return BllResultFactory.Error($"未识别的数据类型:{equipmentProps[i].EquipmentTypePropTemplate.dataType}");
                }
                else
                {
                    var result = TansforWCSDataToAddressData(dataType, equipmentProps[i].value);
                    if (!result.Success)
                    {
                        return BllResultFactory.Error("转换WCS数据到PLC类型错误,值:" + equipmentProps[i].value + " 类型:" + equipmentProps[i].EquipmentTypePropTemplate.dataType);
                    }
                    values[i] = result.Data;
                }

            }
            if (this.WriteData(serverHandel, values))
            {
                return BllResultFactory.Success("成功");
            }
            else
            {
                return BllResultFactory.Error("写入失败!");
            }
        }

        /// <summary>
        /// 获取默认值,注意,当获取失败时会返回error
        /// </summary>
        /// <param name="prop"></param>
        /// <returns></returns>
        private string GetDefaultValue(base_equipment_prop prop)
        {
            string str = "";
            if (!Enum.TryParse(prop.EquipmentTypePropTemplate.dataType, out PLCDataType dataType))
            {
                return "Error";
            }
            switch (dataType)
            {
                case PLCDataType.BYTE:
                case PLCDataType.DWORD:
                case PLCDataType.WORD:
                case PLCDataType.INT:
                case PLCDataType.DINT:
                    str = "0"; break;
                case PLCDataType.BOOL:
                    str = "False"; break;
                case PLCDataType.CHAR:
                default:
                    str = "";
                    break;
            }
            return str;
        }

        /// <summary>
        /// 写入数据,handle,索引值数组,value对应值数组
        /// 按照 OPC 规范,数组始终以索引 1 开始。
        /// </summary>
        public bool WriteData(int[] handle, object[] value)
        {
            try
            {
                int[] temp = new int[handle.Length + 1];
                temp[0] = 0;
                object[] temp1 = new object[handle.Length + 1];
                temp1[0] = "";
                for (int i = 1; i < temp.Length; i++)
                {
                    temp[i] = handle[i - 1];
                    temp1[i] = value[i - 1];
                }
                Array serverHandles = (Array)temp;
                Array values = (Array)temp1;
                Array Errors;
                //OPCAutomation.OPCDataSource.OPCCache;
                s7Group.SyncWrite(handle.Length, ref serverHandles, ref values, out Errors);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 数据类型转换WCS-->PLC
        /// </summary>
        /// <param name="type"></param>
        /// <param name="v"></param>
        /// <returns></returns>
        private BllResult<object> TansforWCSDataToAddressData(PLCDataType type, string data)
        {
            try
            {
                object obj = null;
                switch (type)
                {
                    case PLCDataType.BYTE:
                        obj = Convert.ToInt32(data); break;
                    case PLCDataType.BOOL:
                        obj = Convert.ToBoolean(data); break;
                    case PLCDataType.DWORD:
                        obj = Convert.ToUInt32(data); break;
                    case PLCDataType.WORD:
                        obj = Convert.ToUInt16(data); break;
                    case PLCDataType.INT:
                        obj = Convert.ToInt16(data); break;
                    case PLCDataType.DINT:
                        obj = Convert.ToInt32(data); break;
                    case PLCDataType.CHAR:
                        obj = ConverHelper.StringToASCII(data); break;
                    default:
                        obj = data;
                        break;
                }
                return BllResultFactory.Success(obj, "成功");
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error<object>(null, "WCS到PLC数据转换出现异常,值:" + data + " 目标类型:" + type + " 异常:" + ex.ToString());
            }
        }

        /// <summary>
        /// 数据类型转换PLC-->WCS
        /// </summary>
        /// <param name="type"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        private BllResult<string> TransforAddressDataToWCSData(PLCDataType type, object data)
        {
            string str;
            try
            {
                switch (type)
                {
                    case PLCDataType.BYTE:
                        int i = Convert.ToInt32(data);
                        str = i.ToString();
                        break;
                    case PLCDataType.BOOL:
                    case PLCDataType.DWORD:
                    case PLCDataType.WORD:
                    case PLCDataType.INT:
                    case PLCDataType.DINT:
                        str = data.ToString(); break;
                    case PLCDataType.CHAR:
                        str = ConverHelper.ASCIIToString((short[])data).Trim().Replace("$03", "").Replace("\u0003", "").Replace("\0", ""); break;
                    default:
                        str = data.ToString();
                        break;
                }

                return BllResultFactory.Success(str, "成功");
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error(default(string), "PLC到WCS数据转换出现异常,值:" + data + " 目标类型:" + type + " 异常:" + ex.ToString());
            }
        }
    }
}