Example #1
0
        public virtual int CfRunLoop()
        {
            this.CfIsRunning = true;
            try
            {
                //三個方法(三個保護)控管執行
                while (!disposed && this.CfIsRunning)
                {
                    if (taskRun != null)
                    {
                        if (this.taskRun.CancelToken.IsCancellationRequested)
                        {
                            break;
                        }
                        this.taskRun.CancelToken.ThrowIfCancellationRequested();//一般cancel task 在 while 和 第一行
                    }
                    this.CfRunOnce();
                }


                CtkLog.Info("Finish SensorDevice");
            }
            catch (Exception ex) { CtkLog.Write(ex, CtkLoggerEnumLevel.Error); }
            return(0);
        }
        public void Disconnect()
        {
            if (this.threadNonStopConnect != null)
            {
                this.threadNonStopConnect.Abort();
            }

            foreach (var tc in this.TcpClientList)
            {
                if (tc == null)
                {
                    continue;
                }
                try { tc.Close(); }
                catch (Exception ex) { CtkLog.Write(ex); }
            }

            if (this.m_tcpListener != null)
            {
                this.m_tcpListener.Stop();
            }

            //一旦結束就死了, 需要重new, 所以清掉event沒問題
            CtkEventUtil.RemoveEventHandlersFromOwningByFilter(this, (dlgt) => true);
        }
        public void CleanUntilLast()
        {
            var sourceList = this.m_tcpClientList;

            try
            {
                Monitor.TryEnter(sourceList, 1000);
                var       list   = new List <TcpClient>();
                TcpClient client = null;


                while (!sourceList.IsEmpty)
                {
                    if (!sourceList.TryDequeue(out client))
                    {
                        break;
                    }
                    if (sourceList.IsEmpty)
                    {
                        list.Add(client);
                    }
                    else
                    {
                        CtkNetUtil.DisposeTcpClient(client);
                    }
                }

                foreach (var tc in list)
                {
                    sourceList.Enqueue(tc);
                }
            }
            catch (Exception ex) { CtkLog.Write(ex); }
            finally { Monitor.Exit(sourceList); }
        }
        public void CleanDisconnect()
        {
            try
            {
                Monitor.TryEnter(this.TcpClientList, 1000);
                var       list   = new List <TcpClient>();
                TcpClient client = null;
                while (!this.TcpClientList.IsEmpty)
                {
                    if (!this.TcpClientList.TryDequeue(out client))
                    {
                        break;
                    }
                    if (client.Client != null && client.Connected)
                    {
                        list.Add(client);
                    }
                    else
                    {
                        CtkNetUtil.DisposeTcpClient(client);
                    }
                }

                foreach (var tc in list)
                {
                    this.m_tcpClientList.Enqueue(tc);
                }
            }
            catch (Exception ex) { CtkLog.Write(ex); }
            finally { Monitor.Exit(this.TcpClientList); }
        }
Example #5
0
 void DisposeSelf()
 {
     try { this.Disconnect(); }
     catch (Exception ex) { CtkLog.Write(ex); }
     //斷線不用清除Event, 但Dispsoe需要, 因為即使斷線此物件仍存活著
     CtkEventUtil.RemoveEventHandlersOfOwnerByFilter(this, (dlgt) => true);
 }
        void EndReadCallback(IAsyncResult ar)
        {
            try
            {
                //var stateea = (CtkNonStopTcpStateEventArgs)ar.AsyncState;
                var myea   = (CtkNonStopTcpStateEventArgs)ar.AsyncState;
                var client = myea.workClient;
                if (!ar.IsCompleted || client == null || client.Client == null || !client.Connected)
                {
                    myea.Message = "Read Fail";
                    return;
                }

                var           ctkBuffer = myea.TrxMessageBuffer;
                NetworkStream stream    = client.GetStream();
                int           bytesRead = stream.EndRead(ar);
                ctkBuffer.Length = bytesRead;
                //呼叫他人不應影響自己運作, catch起來
                try { this.OnDataReceive(myea); }
                catch (Exception ex) { CtkLog.Write(ex); }
                stream.BeginRead(ctkBuffer.Buffer, 0, ctkBuffer.Buffer.Length, new AsyncCallback(EndReadCallback), myea);
            }
            catch (IOException ex) { CtkLog.Write(ex); }
            catch (Exception ex) { CtkLog.Write(ex); }
        }
Example #7
0
        public int CfLoad()
        {
            CtkThreadingUtil.RunWorkerAsyn(delegate(object sender, DoWorkEventArgs e)
            {
                for (int idx = 0; !this.disposed; idx++)
                {
                    try
                    {
                        hsmsConnector.ConnectIfNo();
                    }
                    catch (Exception ex)
                    {
                        CtkLog.Write(ex);
                        System.Threading.Thread.Sleep(5000);//無法連線等待5秒
                    }


                    try
                    {
                        hsmsConnector.ReceiveRepeat();
                    }
                    catch (Exception ex)
                    {
                        CtkLog.Write(ex);
                        System.Threading.Thread.Sleep(5000);//無法連線等待5秒
                    }
                    finally { System.Threading.Thread.Sleep(1000); }
                }
            });
            return(0);
        }
        public List <SNetSignalTransEventArgs> AnalysisSignal <T>(object sender, object msg, IList <T> infos)
        {
            var result  = new List <SNetSignalTransEventArgs>();
            var secsMsg = msg as CxHsmsMessage;

            try
            {
                var list = secsMsg.rootNode as CxSecsIINodeList;

                for (int idx = 0; idx < list.Data.Count; idx++)
                {
                    var ea = new SNetSignalTransEventArgs();
                    ea.Sender = sender;
                    var data = list.Data[idx] as CxSecsIINodeASCII;
                    if (data.Data.Count <= 0)
                    {
                        continue;
                    }

                    ea.Data = new List <double>();
                    ea.Data.Add(double.Parse(data.GetString()));

                    //this.OnDataTrigger(ea);
                    result.Add(ea);
                }
                return(result);
            }
            catch (Exception ex) { CtkLog.Write(ex); }

            return(null);
        }
 void DisposeSelf()
 {
     try
     {
         this.Disconnect();
         //一旦結束就死了, 需要重new, 所以清掉event沒問題
         CtkEventUtil.RemoveEventHandlersOfOwnerByFilter(this, (dlgt) => true);
     }
     catch (Exception ex) { CtkLog.Write(ex); }
 }
        protected virtual int RealExec()
        {
            try
            {
                if (!SpinWait.SpinUntil(() => !this.CfIsRunning || this.ProtoConn.IsRemoteConnected, 100))
                {
                    Thread.Sleep(1000);
                    return(0);
                }
                if (!this.CfIsRunning)
                {
                    return(0);                  //若不再執行->return 0
                }
                if (this.Config.IsActivelyTx)
                {
                    var ackDataMsg = this.SignalTran.CreateAckMsg(this.Config.SignalCfgList);
                    if (ackDataMsg != null)
                    {
                        this.ProtoConn.WriteMsg(ackDataMsg);
                    }
                }
                else
                {
                    //等待下次要求資料的間隔
                    if (this.Config.TxInterval > 0)
                    {
                        var interval = DateTime.Now - prevAckTime;
                        while (interval.TotalMilliseconds < this.Config.TxInterval)
                        {
                            if (!this.CfIsRunning)
                            {
                                return(0);                  //若不再執行->直接return
                            }
                            var sleep = this.Config.TxInterval - (int)interval.TotalMilliseconds;
                            if (sleep > 0)
                            {
                                Thread.Sleep(sleep);
                            }
                            interval = DateTime.Now - prevAckTime;
                        }
                    }
                    prevAckTime = DateTime.Now;

                    var reqDataMsg = this.SignalTran.CreateDataReqMsg(this.Config.SignalCfgList);
                    this.ProtoConn.WriteMsg(reqDataMsg);
                }


                //收到資料 或 Timeout 就往下走
                this.areMsg.WaitOne(this.Config.TimeoutResponse);
            }
            catch (Exception ex) { CtkLog.Write(ex); }
            return(0);
        }
Example #11
0
 public int CfRunOnce()
 {
     try
     {
         hsmsConnector.ConnectTry();
         hsmsConnector.ReceiveLoop();
     }
     catch (Exception ex)
     {
         CtkLog.Write(ex);
     }
     finally { System.Threading.Thread.Sleep(1000); }
     return(0);
 }
Example #12
0
        public int CfRunLoop()
        {
            this.CfIsRunning = true;
            while (!this.disposed && this.CfIsRunning)
            {
                try
                {
                    this.CfRunOnce();
                    Thread.Sleep(1000);
                }
                catch (Exception ex) { CtkLog.Write(ex); }
            }

            return(0);
        }
Example #13
0
        public void NonStopRunStart()
        {
            NonStopRunStop();

            this.runningTask = CtkTask.RunOnce((ct) =>
            {
                while (!this.disposed && !ct.IsCancellationRequested)
                {
                    ct.ThrowIfCancellationRequested();
                    try
                    {
                        this.ConnectTry();
                    }
                    catch (Exception ex) { CtkLog.Write(ex); }
                    Thread.Sleep(this.IntervalTimeOfConnectCheck);
                }
            });
        }
Example #14
0
        public void NonStopRunStart()
        {
            this.NonStopRunStop();
            this.runningTask = CtkTask.RunOnce(() =>
            {
                //TODO: 重啟時, 會有執行緒被中止的狀況
                while (!this.disposed)
                {
                    try
                    {
                        this.ConnectTryStart();
                    }
                    catch (Exception ex) { CtkLog.Write(ex); }

                    Thread.Sleep(this.IntervalTimeOfConnectCheck);
                }
            });
        }
Example #15
0
        public void NonStopConnectAsyn()
        {
            AbortNonStopConnect();

            this.NonStopTask = CtkCancelTask.RunOnce((ct) =>
            {
                while (!this.disposed && !ct.IsCancellationRequested)
                {
                    ct.ThrowIfCancellationRequested();
                    try
                    {
                        this.ConnectIfNo();
                    }
                    catch (Exception ex) { CtkLog.Write(ex); }
                    Thread.Sleep(this.IntervalTimeOfConnectCheck);
                }
            });
        }
        void ClientEndConnectCallback(IAsyncResult ar)
        {
            var myea      = new CtkNonStopTcpStateEventArgs();
            var trxBuffer = myea.TrxMessageBuffer;

            try
            {
                Monitor.Enter(this);//一定要等到進去
                var state  = (CtkNonStopTcpClient)ar.AsyncState;
                var client = state.activeWorkClient;
                client.EndConnect(ar);

                myea.Sender     = state;
                myea.workClient = client;
                if (!ar.IsCompleted || client.Client == null || !client.Connected)
                {
                    myea.Message = "Connection Fail";
                    this.OnFailConnect(myea);
                    return;
                }

                //呼叫他人不應影響自己運作, catch起來
                try { this.OnFirstConnect(myea); }
                catch (Exception ex) { CtkLog.Write(ex); }

                var stream = client.GetStream();
                stream.BeginRead(trxBuffer.Buffer, 0, trxBuffer.Buffer.Length, new AsyncCallback(EndReadCallback), myea);
            }
            catch (SocketException ex)
            {
                myea.Message   = ex.Message;
                myea.Exception = ex;
                this.OnFailConnect(myea);
            }
            catch (Exception ex)
            {
                CtkLog.Write(ex, CtkLoggerEnumLevel.Warn);
            }
            finally
            {
                this.mreIsConnecting.Set();
                Monitor.Exit(this);
            }
        }
        public void NonStopConnectAsyn()
        {
            AbortNonStopConnect();

            this.threadNonStopConnect = new Thread(new ThreadStart(delegate()
            {
                while (!disposed)
                {
                    try
                    {
                        this.ConnectIfNo();
                    }
                    catch (Exception ex) { CtkLog.Write(ex); }

                    Thread.Sleep(this.IntervalTimeOfConnectCheck);
                }
            }));
            this.threadNonStopConnect.Start();
        }
        //用途是避免重複要求連線
        public void ConnectIfNo()
        {
            try
            {
                if (!Monitor.TryEnter(this, 1000))
                {
                    return;                               //進不去先離開
                }
                //在Lock後才判斷, 避免判斷無連線後, 另一邊卻連線好了
                if (this.activeWorkClient != null && this.activeWorkClient.Connected)
                {
                    return;                                                                  //連線中直接離開
                }
                if (!mreIsConnecting.WaitOne(10))
                {
                    return;                   //連線中就離開
                }
                this.mreIsConnecting.Reset(); //先卡住, 不讓後面的再次進行連線

                if (this.activeWorkClient != null)
                {
                    var workClient = this.activeWorkClient;
                    try
                    {
                        if (workClient.GetStream() != null)
                        {
                            using (var stm = workClient.GetStream()) stm.Close();
                        }
                    }
                    catch (Exception) { }

                    try { workClient.Close(); }
                    catch (Exception ex) { CtkLog.Write(ex); }

                    this.activeWorkClient = null;
                }
                this.activeWorkClient         = localEP == null ? new TcpClient() : new TcpClient(localEP);
                this.activeWorkClient.NoDelay = true;
                this.activeWorkClient.BeginConnect(this.remoteEP.Address, this.remoteEP.Port, new AsyncCallback(ClientEndConnectCallback), this);
            }
            finally { Monitor.Exit(this); }
        }
Example #19
0
        public int CfRunOnce()
        {
            try
            {
                if (!Monitor.TryEnter(this, 5 * 1000))
                {
                    return(-1);
                }

                this.configs.UpdateIfTimeout();
                this.RunHandlerStatus();
            }
            finally
            {
                Monitor.Exit(this);
            }
            try { this.OnAfterEachExec(new EventArgs()); }
            catch (Exception ex) { CtkLog.Write(ex, CtkLoggerEnumLevel.Warn); }

            return(0);
        }
        void EndConnectCallback(IAsyncResult ar)
        {
            var stateea   = new CtkNonStopTcpStateEventArgs();
            var ctkBuffer = stateea.TrxMessageBuffer;

            try
            {
                // End the operation and display the received data on
                // the console.
                var state = (CtkNonStopTcpListener)ar.AsyncState;
                stateea.Sender = state;
                var tcpClient = state.m_tcpListener.EndAcceptTcpClient(ar);
                stateea.workClient = tcpClient;
                this.m_tcpListener.BeginAcceptTcpClient(new AsyncCallback(EndConnectCallback), this);


                if (tcpClient.Client == null || !tcpClient.Connected)
                {
                    throw new CtkException("連線失敗");
                }

                this.TcpClientList.Enqueue(tcpClient);


                //呼叫他人不應影響自己運作, catch起來
                try { this.OnFirstConnect(stateea); }
                catch (Exception ex) { CtkLog.Write(ex); }

                NetworkStream stream = tcpClient.GetStream();
                stream.BeginRead(ctkBuffer.Buffer, 0, ctkBuffer.Buffer.Length, new AsyncCallback(EndReadCallback), stateea);
            }
            catch (Exception ex)
            {
                stateea.Message   = ex.Message;
                stateea.Exception = ex;
                this.OnFailConnect(stateea);
            }
            finally { }
        }
Example #21
0
        void EndReadCallback(IAsyncResult ar)
        {
            //var stateea = (CtkNonStopTcpStateEventArgs)ar.AsyncState;
            var myea = (CtkNonStopTcpStateEventArgs)ar.AsyncState;

            try
            {
                var client = myea.WorkTcpClient;
                if (!ar.IsCompleted || client == null || client.Client == null || !client.Connected)
                {
                    throw new CtkException("Read Fail");
                }

                var           ctkBuffer = myea.TrxMessageBuffer;
                NetworkStream stream    = client.GetStream();
                int           bytesRead = stream.EndRead(ar);
                ctkBuffer.Length = bytesRead;
                //呼叫他人不應影響自己運作, catch起來
                try { this.OnDataReceive(myea); }
                catch (Exception ex) { CtkLog.Write(ex); }

                if (this.IsAsynAutoRead)
                {
                    stream.BeginRead(ctkBuffer.Buffer, 0, ctkBuffer.Buffer.Length, new AsyncCallback(EndReadCallback), myea);
                }
            }
            //catch (IOException ex) { CtkLog.Write(ex); }
            catch (Exception ex)
            {
                //讀取失敗, 中斷連線(會呼叫 OnDisconnect), 不需要呼叫 OnFailConnect
                this.Disconnect();
                myea.Message   = ex.Message;
                myea.Exception = ex;
                this.OnErrorReceive(myea);//但要呼叫 OnErrorReceive
                CtkLog.WarnNs(this, ex);
            }
        }
        void EndReadCallback(IAsyncResult ar)
        {
            try
            {
                var tcpstate  = (CtkNonStopTcpStateEventArgs)ar.AsyncState;
                var ctkBuffer = tcpstate.TrxMessageBuffer;
                var client    = tcpstate.workClient;

                if (client == null || client.Client == null || !client.Connected)
                {
                    return;
                }
                NetworkStream stream    = client.GetStream();
                int           bytesRead = stream.EndRead(ar);
                ctkBuffer.Length = bytesRead;

                //呼叫他人不應影響自己運作, catch起來
                try { this.OnDataReceive(tcpstate); }
                catch (Exception ex) { CtkLog.Write(ex); }

                stream.BeginRead(ctkBuffer.Buffer, 0, ctkBuffer.Buffer.Length, new AsyncCallback(EndReadCallback), tcpstate);
            }
            catch (Exception ex) { CtkLog.Write(ex); }
        }
Example #23
0
        public void ConnectIfNo()
        {
            if (this.serialPort != null && this.serialPort.IsOpen)
            {
                return;                                                   //連線中直接離開
            }
            try
            {
                if (!Monitor.TryEnter(this, 1000))
                {
                    return;                               //進不去先離開
                }
                if (!connectMre.WaitOne(10))
                {
                    return;              //連線中就離開
                }
                this.connectMre.Reset(); //先卡住, 不讓後面的再次進行連線

                if (this.serialPort != null)
                {
                    try
                    {
                        this.serialPort.Close();
                        this.OnDisconnect(new CtkNonStopSerialPortEventArgs()
                        {
                            Sender = this, SerialPort = this.serialPort
                        });
                        this.serialPort.Dispose();
                    }
                    catch (Exception ex) { CtkLog.Write(ex); }
                }
                this.serialPort           = new SerialPort(this.Config.PortName);
                this.serialPort.BaudRate  = this.Config.BaudRate;
                this.serialPort.Parity    = this.Config.Parity;
                this.serialPort.StopBits  = this.Config.StopBits;
                this.serialPort.DataBits  = this.Config.DataBits;
                this.serialPort.Handshake = this.Config.Handshake;
                this.serialPort.RtsEnable = this.Config.RtsEnable;

                this.serialPort.DataReceived += (sender, e) =>
                {
                    var sp = sender as SerialPort;
                    var ea = new CtkNonStopSerialPortEventArgs();
                    ea.Sender           = this;
                    ea.SerialPort       = sp;
                    ea.DataType         = e.EventType;
                    ea.TrxMessageBuffer = new CtkProtocolBufferMessage();
                    var ctkBuffer = ea.TrxMessageBuffer;
                    do
                    {
                        ctkBuffer.Length = sp.Read(ctkBuffer.Buffer, 0, ctkBuffer.Buffer.Length);
                        if (ctkBuffer.Length > 0)
                        {
                            this.OnDataReceive(ea);
                        }
                    } while (ctkBuffer.Length > 0);
                };
                this.serialPort.ErrorReceived += (sender, e) =>
                {
                    var sp = sender as SerialPort;
                    var ea = new CtkNonStopSerialPortEventArgs();
                    ea.Sender     = this;
                    ea.SerialPort = sp;
                    ea.ErrorType  = e.EventType;
                    this.OnErrorReceive(ea);
                };


                try
                {
                    this.serialPort.Open();
                    this.OnFirstConnect(new CtkNonStopSerialPortEventArgs()
                    {
                        Sender = this, SerialPort = this.serialPort
                    });
                }
                catch (Exception ex)
                {
                    this.OnFailConnect(new CtkNonStopSerialPortEventArgs()
                    {
                        Sender = this, SerialPort = this.serialPort, Exception = ex
                    });
                }

                this.connectMre.Set();
            }
            finally { Monitor.Exit(this); }
        }
Example #24
0
 void DisposeSelf()
 {
     try { this.Disconnect(); }
     catch (Exception ex) { CtkLog.Write(ex); }
 }
 void DisposeSelf()
 {
     try { this.Disconnect(); }
     catch (Exception ex) { CtkLog.Write(ex); }
     CtkEventUtil.RemoveEventHandlersFromOwningByFilter(this, (dlgt) => true);
 }