NirenIO_.cs 2.6 KB
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using TcpKPIO;

namespace BLL
{
    public class NirenIO1 : IO_Interface
    {
        static int diCount = 2;

        public event IOManage.DI_Changed DI_Changed_Event;

        public string IP { get; set; }

        public bool IsConn
        {
            get
            {
                var i= 0;
                while (i < 5)
                {
                    var isonline = KPIOServer.DeviceIsOnline(IP);
                    if (isonline)
                        return true;                    
                    i++;
                    Thread.Sleep(1000);
                }
                return false;
                
            }
        }

        public int Port { get; set; }

        public NirenIO(string ip)
        {
            IP = ip;
            Port = 6000;
            bool rtn = KPIOServer.StartServer(Port);
            KPIOServer.DeviceDIChangeEvent += KPIOServer_DeviceDIChangeEvent;
            KPIOServer.DeviceOnlineEvent += KPIOServer_DeviceOnlineEvent;
            IOLogUtil.info($"开启IO模块:{rtn}");
        }

        private void KPIOServer_DeviceOnlineEvent(string ip)
        {
            IP = ip;
            IOLogUtil.info($"IO模块:{IP}上线");
        }

        private void KPIOServer_DeviceDIChangeEvent(string ip, int[] diStatus)
        {
            Status[] statuses = new Status[diStatus.Length];
            for (int i = 0; i < diStatus.Length; i++)
            {
                statuses[i] = diStatus[i] == 0 ? Status.On : Status.Off;
            }
            DI_Changed_Event?.Invoke(statuses);
        }


        public void Close()
        {
            KPIOServer.StopServer();
        }

        public bool Connect()
        {
            //throw new NotImplementedException();
            return true;
        }

        public bool ReadDI(Addr add, out Status sta)
        {
            sta = Status.Off;
            try
            {
                int index = ((int)add) - 10200;
                var onoff = KPIOServer.GetDI(IP, index);
                sta = onoff == 0 ? Status.Off : Status.On;
                return true;
            }
            catch
            {
                return false;
            }
        }

        public bool ReadDO(Addr add, out Status sta)
        {
            sta = KPIOServer.GetDO(IP, (int)add - 100) == 0 ? Status.Off : Status.On;
            return true;
        }

        public bool WriteDO(int add, Status sta)
        {
            return KPIOServer.WriteDO(IP, add, sta== Status.On ?1:0);
        }
    }
}