ModbusMapper_Client.cs 7.96 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace FLY.Modbus.WithThread
{
    /// <summary>
    /// 使用线程版本
    /// 支持自定义逻辑
    /// </summary>
    public class ModbusMapper_Client : ModbusMapper
    {
        /// <summary>
        /// 更新周期,单位ms,
        /// </summary>
        public int UpdateInterval = 100;

        /// <summary>
        /// 实际更新间隔
        /// </summary>
        public TimeSpan ActUpdateInterval { get; private set; }

        /// <summary>
        /// 工作中
        /// </summary>
        public bool IsRunning { get; private set; }
        /// <summary>
        /// 异常次数
        /// </summary>
        public int ErrorCnt { get; private set; }

        class RegWrite
        {
            public DataToRegs dr;
            public object val;

            public RegWrite(DataToRegs dr, object val)
            {
                this.dr = dr;
                this.val = val;
            }
        }

        List<RegWrite> rws = new List<RegWrite>();

        /// <summary>
        /// tcp client
        /// </summary>
        public ClientTCP Client { get; set; }
        CancellationTokenSource cts;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ep">服务器ep</param>
        public ModbusMapper_Client(IPEndPoint ep)
        {
            Client = new ClientTCP(ep);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return Client.ToString();
        }

        /// <summary>
        /// 启动
        /// </summary>
        public void Start()
        {
            lock (this)
            {
                if (IsRunning)
                    return;
                IsRunning = true;
                cts = new CancellationTokenSource();
                Task.Factory.StartNew(OnPoll_update, cts.Token);
            }
        }
        
        /// <summary>
        /// 停止
        /// </summary>
        public void Stop()
        {
            lock (this)
            {
                if (!IsRunning)
                    return;
                cts.Cancel();
                Client.Close();
            }
        }

        void OnPoll_update()
        {
            Stopwatch stopwatch = new Stopwatch();
107
            Stopwatch stopwatch_act = new Stopwatch();
潘栩锋's avatar
潘栩锋 committed
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
            bool isTimeForRead = true;
        _connect:
            while (true)
            {
                if (cts.IsCancellationRequested)
                    goto _end;
                

                bool isconnected = Client.Connect();

                if (cts.IsCancellationRequested)
                    goto _end;
                

                if (isconnected)
                    break;
                else
                    Thread.Sleep(1000);
            }

            //刚连接成功。

            //从本地PC 属性获取value 更新到 本地PLC 寄存器,
            //目的: 当从PLC读取寄存器值时,能比较不同,产生变化事件
            foreach (var areaManager in mAreaManager)
                areaManager.SetAllIsPlcValueChanged();

            //清空 写缓存
            lock (rws)
            {
                rws.Clear();
            }

            stopwatch.Restart();
            isTimeForRead = true;
            while (true)
            {
                if (cts.IsCancellationRequested)
                    goto _end;

                if (stopwatch.ElapsedMilliseconds >= UpdateInterval)
                {
                    isTimeForRead = true;
                }

                if (isTimeForRead)
                {
                    isTimeForRead = false;
                    stopwatch.Restart();
157 158 159 160 161 162 163 164 165 166


                    if (!stopwatch_act.IsRunning)
                    {
                        stopwatch_act.Restart();
                    }
                    else {
                        ActUpdateInterval = stopwatch_act.Elapsed;
                        stopwatch_act.Restart();
                    }
潘栩锋's avatar
潘栩锋 committed
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
                    if (!UpdateReadData())
                    {
                        if (cts.IsCancellationRequested)//可能是外部强制关闭
                            goto _end;

                        goto _error;//连接断开,终止更新线程
                    }
                }

                //输出写入数据
                if (!UpdateWriteData())
                {
                    if (cts.IsCancellationRequested)//可能是外部强制关闭
                        goto _end;

                    goto _error;//连接断开,终止更新线程
                }

                Thread.Sleep(30);
            }

        _error:
            ErrorCnt++;
            goto _connect;

        _end:
            Client.Close();
            IsRunning = false;
        }

        /// <summary>
        /// 更新一次读全部数据
        /// </summary>
        /// <returns></returns>
        bool UpdateReadData()
        {
            foreach (var areaManager in mAreaManager)
            {
                areaManager.MakePlanReal();
            }

            //int curr_area_idx = 0;
            foreach (var areaManager in mAreaManager)
            {
                foreach(Plan p_doing in areaManager.plan)
                {
                    switch (p_doing.area)
                    {
                        case PLCAddressArea.Coil:
                            {
                                if (!Client.Do_01(p_doing.addr, p_doing.num, out IEnumerable<bool> values))
                                    return false;
                                SetModbusData(PLCAddressArea.Coil, p_doing.addr, values);
                            }
                            break;
                        case PLCAddressArea.Register:
                            {
                                if (!Client.Do_03(p_doing.addr, p_doing.num, out IEnumerable<UInt16> values))
                                    return false;
                                SetModbusData(PLCAddressArea.Register, p_doing.addr, values);
                            }
                            break;
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// PC -> PLC
        /// 为命名数据赋值,会改变Modbus的寄存器值,并产生通知
        /// </summary>
        /// <param name="dr">数据映射</param>
        /// <param name="val">数据值,不能为空</param>
        /// <returns></returns>
        public override void SetNameData(DataToRegs dr, object val)
        {
            RegWrite rw = new RegWrite(dr, val);
            lock (rws)
            {
                rws.Add(rw);
            }
        }

        /// <summary>
        /// 提取全部写命令缓冲区 输出
        /// </summary>
        bool UpdateWriteData()
        {
            while (true)
            {
                RegWrite rw;
                lock (rws)
                {
                    if (rws.Count() == 0)
                        break;
                    rw = rws.First();
                    rws.RemoveAt(0);
                }
                //强制令读时,推送数据
                rw.dr.isPlcValueChanged = true;
                object plc_value = rw.dr.ToPLCObj(rw.val);
                switch (rw.dr.dataArea)
                {
                    case PLCAddressArea.Coil:
                        if (!Client.Do_0F((UInt16)rw.dr.addr, new bool[] {(bool)plc_value }))
                            return false;
                        break;
                    default:
                        //case PLCAddressArea.Register:
                        if (!Client.Do_10((UInt16)rw.dr.addr, (UInt16[])plc_value))
                            return false;
                        break;
                }
            }
            return true;
        }

    }
}