/// <summary>
 /// Constructor for a DCB, using the DCB provided by another object.
 /// </summary>
 /// <param name="handle">Valid handle to a serial port object.</param>
 /// <param name="state">A CommState object for which the DCB settings should be
 /// taken. Note, the handle managed by the state object is ignored. If this
 /// parameter is null, then a default DCB is created.</param>
 internal CommState(SafeFileHandle handle, CommState state)
 {
     m_ComPortHandle = handle;
     if (state == null) {
         m_Dcb.DCBLength = Marshal.SizeOf(m_Dcb);
         GetCommState();
     } else {
         m_Dcb = state.m_Dcb;
     }
 }
Exemplo n.º 2
0
        public void HaveData()
        {
            if (CommState is IdleState)
            {
                CommState.HaveData();
                // Change state
                ChangeToTransENQState();
#if DEBUG
                AppendToLog("HaveData complete.");
#endif
            }
        }
Exemplo n.º 3
0
 public void RcvNAK()
 {
     CommState.RcvNAK();
     if (CommState is TransWaitState && comm.numNAK == 6)
     {
         ChangeToIdleState();
     }
     if (CommState is TransEnqState)
     {
         ChangeToIdleState();
     }
 }
Exemplo n.º 4
0
 public void RcvENQ()
 {
     CommState.RcvENQ();
     if (CommState is IdleState)
     {
         ChangeToRcvWaitState();
     }
     if (CommState is TransEnqState)
     {
         ChangeToIdleState();
     }
 }
 /// <summary>
 /// Constructor for a DCB, using the DCB provided by another object.
 /// </summary>
 /// <param name="handle">Valid handle to a serial port object.</param>
 /// <param name="state">A CommState object for which the DCB settings should be
 /// taken. Note, the handle managed by the state object is ignored. If this
 /// parameter is null, then a default DCB is created.</param>
 internal CommState(SafeFileHandle handle, CommState state)
 {
     m_ComPortHandle = handle;
     if (state == null)
     {
         m_Dcb.DCBLength = Marshal.SizeOf(m_Dcb);
         GetCommState();
     }
     else
     {
         m_Dcb = state.m_Dcb;
     }
 }
Exemplo n.º 6
0
 public void RcvEOT()
 {
     CommState.RcvEOT();
     if (CommState is RcvWaitState)
     {
         // Return to Idle.
         ChangeToIdleState();
         if (comm.OutboundMessageQueue.Count > 0)
         {
             // Don't make the operator wait for the timer tick.
             IdleCheck();
         }
     }
 }
Exemplo n.º 7
0
 /// <summary>
 /// Closes the serial port.
 /// </summary>
 /// <exception cref="System.ObjectDisposedException"/>
 /// <remarks>
 /// Closing the serial port invalidates actions that can be done to the serial port,
 /// but it does not prevent the serial port from being reopened
 /// </remarks>
 public void Close()
 {
     if (m_IsDisposed)
     {
         throw new ObjectDisposedException("WinNativeSerial");
     }
     if (IsOpen)
     {
         m_CommOverlappedIo.Dispose();
         m_CommOverlappedIo = null;
         m_CommState        = null;
         m_CommModemStatus  = null;
         m_ComPortHandle.Dispose();
         m_ComPortHandle = null;
     }
 }
Exemplo n.º 8
0
 public void SetState(CommState state)
 {
     if (_commAccessLock.WaitOne(100))
     {
         _commAccessor.Read(_statusOffset, out _status);
         _status.State    = state;
         _driverTimestamp = _status.DriverTime;
         if (_driverTimestamp != _prevDriverTimestamp)
         {
             DriverTime = DateTime.Now;
         }
         _prevDriverTimestamp = _driverTimestamp;
         _commAccessor.Write(_statusOffset, ref _status);
         _commAccessLock.ReleaseMutex();
     }
 }
            /// <summary>
            /// Open the port specified by the Port property.
            /// </summary>
            public void Open()
            {
                if (IsDisposed)
                {
                    throw new ObjectDisposedException("NativeSerialPort");
                }
                if (string.IsNullOrWhiteSpace(m_Port))
                {
                    throw new InvalidOperationException("Port must first be set");
                }
                if (IsOpen)
                {
                    throw new InvalidOperationException("Serial Port currently open");
                }

                m_ComPortHandle = UnsafeNativeMethods.CreateFile(@"\\.\" + m_Port,
                                                                 NativeMethods.FileAccess.GENERIC_READ | NativeMethods.FileAccess.GENERIC_WRITE,
                                                                 NativeMethods.FileShare.FILE_SHARE_NONE,
                                                                 IntPtr.Zero,
                                                                 NativeMethods.CreationDisposition.OPEN_EXISTING,
                                                                 NativeMethods.FileAttributes.FILE_FLAG_OVERLAPPED,
                                                                 IntPtr.Zero);
                if (m_ComPortHandle.IsInvalid)
                {
                    WinIOError();
                }

                NativeMethods.FileType t = UnsafeNativeMethods.GetFileType(m_ComPortHandle);
                if (t != NativeMethods.FileType.FILE_TYPE_CHAR && t != NativeMethods.FileType.FILE_TYPE_UNKNOWN)
                {
                    m_ComPortHandle.Close();
                    m_ComPortHandle = null;
                    throw new IOException("Wrong Filetype: " + m_Port);
                }

                // Set the default parameters
                UnsafeNativeMethods.SetupComm(m_ComPortHandle, m_DriverInQueue, m_DriverOutQueue);

                m_CommState      = new CommState(m_ComPortHandle, m_CommState);
                m_CommProperties = new CommProperties(m_ComPortHandle);
                m_CommModem      = new CommModemStatus(m_ComPortHandle);
                CommOverlappedIo commIo = new CommOverlappedIo(m_ComPortHandle, m_CommIo, Port);

                m_CommIo.Dispose();
                m_CommIo = commIo;
            }
Exemplo n.º 10
0
        //private CVRSystem _vrSystem;

        //private string DisplayAddress = "127.0.0.1";
        //private string DisplayAddress = "192.168.0.27";

        //private CommState _state = CommState.Uninitialized;

        private void SetState(CommState state, bool set)
        {
            var prevState = _sharedMem.State;
            var newState  = _sharedMem.State;

            if (set)
            {
                newState |= state;
            }
            else
            {
                newState &= ~state;
            }
            if (prevState != newState)
            {
                _sharedMem.State = newState;
            }
        }
Exemplo n.º 11
0
 public static OperateResult EndDoCommunication()
 {
     try
     {
         currentCommState = CommState.Idel;
         if (MainForm.CommMaster is Master)
         {
             return(DoCommunicationFunc.EndInvoke(iar));
         }
         else
         {
             return(DoCommunicationTcpFunc.EndInvoke(iar));
         }
     }
     catch (Exception ex)
     {
         return(OperateResult.Create(false, ex.Message, new byte[] { }, new byte[] { }));
     }
 }
            /// <summary>
            /// Release resources.
            /// </summary>
            /// <param name="disposing"><b>true</b> if this is being called from dispose(), or <b>false</b>
            /// if by the finaliser.</param>
            private void Dispose(bool disposing)
            {
                if (disposing)
                {
                    if (IsOpen)
                    {
                        Close();
                    }
                    m_CommIo.Dispose();
                    m_CommIo         = null;
                    m_CommState      = null;
                    m_CommProperties = null;
                    m_CommModem      = null;
                }

                // Note: the SafeFileHandle will close the object itself when finalising, so
                // we don't need to do it here. It would be different if we managed the handle
                // with an IntPtr however.
                m_IsDisposed = true;
            }
Exemplo n.º 13
0
 public static bool BeginDoCommunication(ModlesMsg modlesMsg)
 {
     if (currentCommState != CommState.Idel)
     {
         return(false);
     }
     iar = null;
     currentCommState = modlesMsg.Function;
     if (MainForm.CommMaster != null)
     {
         if (MainForm.CommMaster is Master)
         {
             iar = DoCommunicationFunc.BeginInvoke((MainForm.CommMaster as Master), modlesMsg, null, null);
         }
         else
         {
             iar = DoCommunicationTcpFunc.BeginInvoke((MainForm.CommMaster as TcpMaster), modlesMsg, null, null);
         }
     }
     return(true);
 }
Exemplo n.º 14
0
 public void RcvACK()
 {
     CommState.RcvACK();
     if (CommState is TransEnqState)
     {
         // Transition to TransWaitState.
         ChangeToTransWaitState();
     }
     if (CommState is IdleState)    // In case the ACK comes back before we've transitioned to TransENQState.
     {
         // DEBUG: Better keep track of how often this happens, for testing purposes.
         AppendToLog("RcvACK in IdleState!");
         // Transition to TransENQState?
         ChangeToTransENQState();
         CommState.RcvACK();
         // Transition to TransWaitState.
         ChangeToTransWaitState();
     }
     if (CommState is TransWaitState && comm.CurrentMessage.FrameList.Count < comm.CurrentFrameCounter)
     {
         // When all frames have been sent, return to IdleState.
         ChangeToIdleState();
     }
 }
 /// <summary>
 /// Default constructor, doesn't associate with a COM port.
 /// </summary>
 public NativeSerialPort()
 {
     m_CommState = new CommState();
     m_CommIo = new CommOverlappedIo();
 }
            /// <summary>
            /// Release resources.
            /// </summary>
            /// <param name="disposing"><b>true</b> if this is being called from dispose(), or <b>false</b> 
            /// if by the finaliser.</param>
            private void Dispose(bool disposing)
            {
                if (disposing) {
                    if (IsOpen) Close();
                    m_CommIo.Dispose();
                    m_CommIo = null;
                    m_CommState = null;
                    m_CommProperties = null;
                    m_CommModem = null;
                }

                // Note: the SafeFileHandle will close the object itself when finalising, so
                // we don't need to do it here. It would be different if we managed the handle
                // with an IntPtr however.
                m_IsDisposed = true;
            }
            /// <summary>
            /// Open the port specified by the Port property.
            /// </summary>
            public void Open()
            {
                if (IsDisposed) throw new ObjectDisposedException("NativeSerialPort");
                if (string.IsNullOrWhiteSpace(m_Port)) throw new InvalidOperationException("Port must first be set");
                if (IsOpen) throw new InvalidOperationException("Serial Port currently open");

                m_ComPortHandle = UnsafeNativeMethods.CreateFile(@"\\.\" + m_Port,
                    NativeMethods.FileAccess.GENERIC_READ | NativeMethods.FileAccess.GENERIC_WRITE,
                    NativeMethods.FileShare.FILE_SHARE_NONE,
                    IntPtr.Zero,
                    NativeMethods.CreationDisposition.OPEN_EXISTING,
                    NativeMethods.FileAttributes.FILE_FLAG_OVERLAPPED,
                    IntPtr.Zero);
                if (m_ComPortHandle.IsInvalid) WinIOError();

                NativeMethods.FileType t = UnsafeNativeMethods.GetFileType(m_ComPortHandle);
                if (t != NativeMethods.FileType.FILE_TYPE_CHAR && t != NativeMethods.FileType.FILE_TYPE_UNKNOWN) {
                    m_ComPortHandle.Close();
                    m_ComPortHandle = null;
                    throw new IOException("Wrong Filetype: " + m_Port);
                }

                // Set the default parameters
                UnsafeNativeMethods.SetupComm(m_ComPortHandle, m_DriverInQueue, m_DriverOutQueue);

                m_CommState = new CommState(m_ComPortHandle, m_CommState);
                m_CommProperties = new CommProperties(m_ComPortHandle);
                m_CommModem = new CommModemStatus(m_ComPortHandle);
                CommOverlappedIo commIo = new CommOverlappedIo(m_ComPortHandle, m_CommIo, Port);
                m_CommIo.Dispose();
                m_CommIo = commIo;
            }
Exemplo n.º 18
0
        private void ThreadComm()
        {
            CommState myCommState = new CommState();

            myCommState = CommState.STATE_TX;
            QueueInfo myQueueInfoTx      = new QueueInfo();
            int       usart_tx_length    = 0;
            int       CommRxTimeOutCount = 0;

            while (true)
            {
                //start 自动检查任务

                //end 自动检查任务
                switch (myCommState)
                {
                case CommState.STATE_TX:
                    //获取事件
                    myQueueInfoTx = myQueue.DecQune();
                    if (myQueueInfoTx == null)        //没有新事件
                    {
                        mySetByteArry[0] = (byte)'a'; //0x01;
                        mySetByteArry[1] = 0x0d;
                        mySetByteArry[2] = 0x0a;
                        usart_tx_length  = 3;
                    }
                    else
                    {
                        switch (myQueueInfoTx.Type)
                        {
                        case 'k':
                            object aaa = myQueueInfoTx.Msg;
                            mySetByteArry[0] = (byte)'k';           // 0x01;
                            mySetByteArry[1] = 0;                   //levelState;// 0x06;
                            mySetByteArry[2] = Convert.ToByte(aaa); // 0x00;
                            mySetByteArry[3] = 0x0d;                // 0x00;
                            mySetByteArry[4] = 0x0a;                // levelState;
                            usart_tx_length  = 5;
                            break;

                        case 'l':
                            break;

                        case 'v':
                            mySetByteArry[0] = (byte)'v';        //0x01;
                            mySetByteArry[1] = 0x0d;
                            mySetByteArry[2] = 0x0a;
                            usart_tx_length  = 3;
                            break;

                        case 'p':
                            mySetByteArry[0] = (byte)'p';
                            int txLength = SetUpParmArry[0] % 16;
                            mySetByteArry[1] = (byte)txLength;
                            for (int i = 0; i <= txLength; i++)
                            {
                                mySetByteArry[2 + 2 * i]     = (byte)(SetUpParmArry[i] % 256);
                                mySetByteArry[2 + 2 * i + 1] = (byte)(SetUpParmArry[i] / 256);
                            }
                            mySetByteArry[4 + 2 * txLength] = 0x0d;        // (byte)(res % 256);
                            mySetByteArry[5 + 2 * txLength] = 0x0a;        // (byte)(res / 256);
                            usart_tx_length = 6 + 2 * txLength;
                            break;

                        default:
                            break;
                        }
                    }
                    if (sp.IsOpen)
                    {
                        Thread.Sleep(100);
                        sp.Write(mySetByteArry, 0, usart_tx_length);
                    }
                    myCommState = CommState.STATE_RX;    //进入到接受

                    break;

                case CommState.STATE_RX:
                    int SDataLength = 0;
                    try
                    {
                        SDataLength = this.sp.BytesToRead;
                    }
                    catch {
                    }
                    while (SDataLength > RX_BUFFER_LENGTH)
                    {
                        byte[] temp = new byte[RX_BUFFER_LENGTH];
                        sp.Read(temp, 0, RX_BUFFER_LENGTH);
                        SDataLength = this.sp.BytesToRead;
                    }
                    if ((RxArrPtrTail + SDataLength) > RX_BUFFER_LENGTH)
                    {
                        sp.Read(RxArr, RxArrPtrTail, RX_BUFFER_LENGTH - RxArrPtrTail);
                        sp.Read(RxArr, 0, SDataLength + RxArrPtrTail - RX_BUFFER_LENGTH);
                    }
                    else
                    {
                        sp.Read(RxArr, RxArrPtrTail, SDataLength);
                    }
                    RxArrPtrTail += SDataLength;

                    //RxArr[RxArrPtrTail++] = ArrTmp[j];//(byte)(SDateTemp);
                    if (RxArrPtrTail >= RX_BUFFER_LENGTH)
                    {
                        RxArrPtrTail = RxArrPtrTail % RX_BUFFER_LENGTH;    //循环指针
                    }
                    if (RxArr[(RxArrPtrTail + RX_BUFFER_LENGTH - 2) % RX_BUFFER_LENGTH] == 0x0d && RxArr[(RxArrPtrTail + RX_BUFFER_LENGTH - 1) % RX_BUFFER_LENGTH] == 0x0a)
                    {
                        int j = 0;
                        while (j < usart_tx_length)
                        {
                            if (RxArr[(RxArrPtrHeader + j) % RX_BUFFER_LENGTH] == mySetByteArry[j++])
                            {
                                continue;
                            }
                            else
                            {
                                break;
                            }
                        }
                        if (j == usart_tx_length)
                        {
                            RxArrPtrHeader += usart_tx_length;
                            RxArrPtrHeader %= RX_BUFFER_LENGTH;
                        }
                        int i        = 0;
                        int s_header = RxArrPtrHeader;
                        for (; i < (RxArrPtrTail + RX_BUFFER_LENGTH - s_header) % RX_BUFFER_LENGTH; i++)
                        {
                            UpdataArr[i]            = RxArr[RxArrPtrHeader];
                            RxArr[RxArrPtrHeader++] = 0;
                            if (RxArrPtrHeader >= RX_BUFFER_LENGTH)
                            {
                                RxArrPtrHeader = 0;
                            }
                        }
                        UpdataArr[0]       = UpdataArr[0];
                        CommRxTimeOutCount = 0;
                        this.Invoke(myGuiUpdata);
                        myCommState = CommState.STATE_TX;    //接收成功,下一跳到发送状态
                    }
                    CommRxTimeOutCount++;
                    if (CommRxTimeOutCount > 100)
                    {
                        myCommState = CommState.STATE_RX_TIME_OUT;    //吓一跳到,通讯超时状态
                    }
                    Thread.Sleep(5);
                    //Console.WriteLine("字符" + ttttttt_count++);
                    //this.Invoke(myGuiUpdata);
                    // this.label_Version.Text = ttttttt_count.ToString();

                    break;

                case CommState.STATE_RX_TIME_OUT:    //接收通讯超时
                    Console.WriteLine("通讯超时  timeout ");
                    CommRxTimeOutCount = 0;
                    myCommState        = CommState.STATE_TX;
                    break;

                default:
                    break;
                }
            }
        }
Exemplo n.º 19
0
		void Accept( IAsyncResult result )
		{
			TcpListener listener = result.AsyncState as TcpListener;
			CommState commState = new CommState();

			commState.socket = listener.EndAcceptSocket( result );
			commState.connected_from = commState.socket.RemoteEndPoint;

			commState.socket.BeginReceive( commState.buffer.GetBuffer(), 0, 4, SocketFlags.None
						, commState.Received, commState );
			clients.Add( commState );
			// accept another connection
			listener.BeginAcceptTcpClient( Accept, listener );
		}
Exemplo n.º 20
0
        private void USBProcessor()
        {
            List <byte[]> outgoingPackets = null;
            HIDDev        _usb            = null;
            var           data            = new byte[33];
            DateTime      lastOutgoing    = DateTime.MinValue;

            while (_running)
            {
                if (_usb == null)
                {
                    var hd = HIDBrowse.Browse().FirstOrDefault(h => h.Vid == 0x1974 && h.Pid == 0x001);
                    if (hd != null)
                    {
                        _usb = new HIDDev();
                        _usb.Open(hd);
                        State = CommState.Connected;
                        _sharedMem.SetState(State);
                    }
                }
                try
                {
                    if (_usb != null)
                    {
                        outgoingPackets = _sharedMem.ReadOutgoingPackets();
                        if (outgoingPackets != null)
                        {
                            lock (OutgoingPackets)
                                foreach (var item in outgoingPackets)
                                {
                                    OutgoingPackets.Enqueue(item);
                                }
                        }
                        lock (OutgoingPackets)
                            if (OutgoingPackets.Count > 0 && (DateTime.Now - lastOutgoing).TotalMilliseconds >= 100)
                            {
                                lastOutgoing = DateTime.Now;
                                var d = OutgoingPackets.Dequeue(); //33 byte packets in queue
                                _usb.Write(d);                     //send before monitor process
                                if (IsDebug && IsVisible)
                                {
                                    var packet = StructFromBytes <USBPacket>(d, 1);
                                    packet.ParseFields();
                                    lock (OutPacketMonitor)
                                        OutPacketMonitor.Add(packet);
                                }
                            }

                        _usb.Read(data);
                        if (CheckPacketCrc(data, 1))
                        {
                            _sharedMem.WriteIncomingPacket(data); //send before monitor process
                            State = _sharedMem.IsDriverActive ? CommState.Active : CommState.ActiveNoDriver;
                            if (IsDebug && IsVisible)
                            {
                                //var x = Marshal.SizeOf(typeof(USBPacket));
                                var packet = StructFromBytes <USBPacket>(data, 1);
                                packet.ParseFields();
                                lock (InPacketMonitor)
                                    InPacketMonitor.Add(packet);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    if (_usb != null)
                    {
                        _usb.Close();
                        _usb.Dispose();
                    }
                    _usb  = null;
                    State = CommState.Disconnected;
                    _sharedMem.SetState(State);

                    Thread.Sleep(100);
                }
            }
            if (_usb != null)
            {
                _usb.Close();
                _usb.Dispose();
            }
            _usb  = null;
            State = CommState.Disconnected;
            _sharedMem.SetState(CommState.Disconnected);
        }
 /// <summary>
 /// Default constructor, doesn't associate with a COM port.
 /// </summary>
 public NativeSerialPort()
 {
     m_CommState = new CommState();
     m_CommIo    = new CommOverlappedIo();
 }
Exemplo n.º 22
0
		void Accept( IAsyncResult result )
		{
			TcpListener listener = result.AsyncState as TcpListener;
			CommState commState = new CommState();

			commState.socket = listener.EndAcceptSocket( result );
			commState.socket.SetSocketOption( SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true );
			commState.connected_from = commState.socket.RemoteEndPoint;

            commState.socket.BeginReceive( commState.buffer.GetBuffer(), 0, 4, SocketFlags.None
						, commState.Received, null );

			listener.BeginAcceptTcpClient( Accept, listener );
		}
Exemplo n.º 23
0
        private async void ExcuteUtilityDialog(object obj)
        {
            await DialogHost.Show(new UtilityRunDialog()
            {
                DataContext = new UtilityRunDialogViewModel(mCommState)
            }, "RootDialog", async (object sender, DialogClosingEventArgs eventArgs) =>
            {
                if (eventArgs.Parameter == null)
                {
                    return;
                }

                mCommState = (CommState)eventArgs.Parameter;

                switch (mCommState.Mode)
                {
                case CommMode.SerialPort:
                    {
                        mCommAdapter = new CommSerialPort();
                        break;
                    }

                case CommMode.UDP:
                    {
                        mCommAdapter = new CommUDP();
                        break;
                    }

                case CommMode.TCPClient:
                    {
                        mCommAdapter = new CommTCPClient();
                        break;
                    }

                case CommMode.TCPServer:
                    {
                        mCommAdapter = new CommTCPServer();
                        break;
                    }

                default:
                    {
                        break;
                    }
                }

                if (mCommAdapter == null)
                {
                    await DialogHost.Show(new NotifyDialog()
                    {
                        DataContext = new NotifyDialogViewModel
                        {
                            EnableYesNoQuestion = false,
                            NotifyTitle         = "Warning",
                            NotifyMessage       = "Please check Mode!"
                        }
                    }, "NotifyDialog");

                    return;
                }

                int ret = mCommAdapter.Connect(mCommState.Address, mCommState.Port);
                if (ret != 0)
                {
                    await DialogHost.Show(new NotifyDialog()
                    {
                        DataContext = new NotifyDialogViewModel
                        {
                            EnableYesNoQuestion = false,
                            NotifyTitle         = "Warning",
                            NotifyMessage       = "Please check Address and Port!"
                        }
                    }, "NotifyDialog");

                    return;
                }

                TransmissionMessage = "";
                ReceivedMessage     = "";

                mCommAdapter.ConnectEvent      += CommAdapter_ConnectEvent;
                mCommAdapter.DisconnectEvent   += CommAdapter_DisconnectEvent;
                mCommAdapter.DataReceivedEvent += CommAdapter_DataReceivedEvent;

                RefreshSettingUI();
            });
        }
Exemplo n.º 24
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Stop();
            if ((DateTime.Now - LastInquireDatetime).TotalMilliseconds > 300 && Communication.GetDoCommState() != 1 && UpWriteDic.Count == 0)
            {
                if (ModelsOperate.ModelsList.Count > 0)
                {
                    if (CurreentInquireindex >= ModelsOperate.ModelsList.Count)
                    {
                        CurreentInquireindex = 0;
                    }
                    DOInquire(ModelsOperate.ModelsList[CurreentInquireindex]);
                    CurreentInquireindex++;
                }
                //LastInquireDatetime = DateTime.Now;
            }
            if (!isRegex)
            {
                btn_场景设置.Enabled = false;
            }
            else
            {
                if (MainForm.UserName == "管理员")
                {
                    btn_场景设置.Enabled = true;
                }
            }
            DateTime tmpDate = DateTime.Now;

            当前时间.Text = tmpDate.ToString("yyyy/MM/dd HH:mm:ss");
            if (frm_主模块 != null)
            {
                frm_主模块.RefreshForm(Communication.RoutInspecting || Communication.EachRoutInspecting);
            }
            if (frm_开关模块界面 != null)
            {
                frm_开关模块界面.RefreshForm(Communication.RoutInspecting || Communication.EachRoutInspecting);
            }
            if (Communication.GetDoCommState() == 2)
            {
                int           index  = 0;
                CommState     state  = Communication.GetCommState();
                OperateResult result = Communication.EndDoCommunication();
                if (result.IsSuccess == false)
                {
                    switch (state)
                    {
                        #region "数据处理"
                    case CommState.GetModlesMsg:
                        if ((index = ModelsOperate.ModelsList.FindIndex(t => t.模块编号 == Communication.CurrentAddr.ToString())) != -1)
                        {
                            ModelsOperate.ModelsList[index].State      = 3;
                            ModelsOperate.ModelsList[index].FalutState = 3;
                            if (OpenModel)
                            {
                                OpenModel = false;
                            }
                        }
                        frm_主模块.RefreshPanel();
                        if (frm_开关模块界面 != null)
                        {
                            frm_开关模块界面.RefreshPanel();
                        }
                        break;

                    case CommState.GetModlesAllMsg:
                        if ((index = ModelsOperate.ModelsList.FindIndex(t => t.模块编号 == Communication.CurrentAddr.ToString())) != -1)
                        {
                            ModelsOperate.ModelsList[index].State      = 3;
                            ModelsOperate.ModelsList[index].FalutState = 3;
                            if (OpenModel)
                            {
                                OpenModel = false;
                            }
                        }
                        break;

                    case CommState.SetModles_TK:
                        break;

                    case CommState.SetModles_Reset:
                        //通信状态 = 3;
                        break;
                        #endregion
                    }
                }
                else
                {
                    index = 0;
                    if (result.IsSuccess)
                    {
                        List <byte[]> tmpList = new List <byte[]>();
                        switch (state)
                        {
                            #region "数据处理"
                        case CommState.GetModlesMsg:
                            通信状态 = 2;
                            for (int i = 0; i < result.ResultData.Length; i += 13)
                            {
                                if (result.ResultData.Length < i + 13)
                                {
                                    continue;
                                }
                                if ((result.ResultData[i] & 0x80) > 0 && result.ResultData[i + 1] == 0 && result.ResultData[i + 2] == 0)
                                {
                                    continue;
                                }
                                byte[] b = new byte[13];
                                Array.Copy(result.ResultData, i, b, 0, 13);
                                tmpList.Add(b);
                            }
                            tmpList = tmpList.OrderBy(t => (t[3] << 8 | t[4])).ToList();
                            ModelsOperate.RefreshModel(tmpList);
                            frm_主模块.RefreshPanel();
                            if (frm_开关模块界面 != null)
                            {
                                frm_开关模块界面.RefreshPanel();
                            }
                            LastInquireDatetime = DateTime.Now;
                            break;

                        case CommState.GetModlesAllMsg:
                            if ((index = ModelsOperate.ModelsList.FindIndex(t => t.模块编号 == Communication.CurrentAddr.ToString())) != -1)
                            {
                                if (OpenModel == true)
                                {
                                    frm_开关模块界面     = New_Form <开关模块界面>(frm_开关模块界面);
                                    frm_开关模块界面.tmp = ModelsOperate.ModelsList[index];
                                    OpenModel      = false;
                                }
                            }
                            for (int i = 0; i < result.ResultData.Length; i += 13)
                            {
                                byte[] b = new byte[13];
                                Array.Copy(result.ResultData, i, b, 0, 13);
                                tmpList.Add(b);
                            }
                            if (tmpList.Count > 0)
                            {
                                tmpList = tmpList.OrderBy(t => (t[4] << 8 | t[5])).ToList();
                            }
                            ModelsOperate.RefreshModel(tmpList);
                            if (frm_开关模块界面 != null)
                            {
                                frm_开关模块界面.RefreshPanel();
                            }
                            break;

                        case CommState.SetModles_TK:

                            break;

                        case CommState.SetModles_Reset:

                            break;
                            #endregion
                        }
                    }
                }
            }
            if ((DateTime.Now - LastReadDatetime).TotalMilliseconds > currentParam.接收速度 && MainForm.CommMaster != null)
            {
                LastReadDatetime = DateTime.Now;
                OperateResult operateResult;
                byte[]        tmp = Communication.CommReadData(out operateResult);
                if (operateResult.IsSuccess)
                {
                    List <byte[]> tmpList = new List <byte[]>();
                    for (int i = 0; i < operateResult.ResultData.Length; i += 13)
                    {
                        if (operateResult.ResultData.Length < i + 13)
                        {
                            continue;
                        }
                        if ((operateResult.ResultData[i] & 0x80) > 0 && operateResult.ResultData[i + 1] == 0 && operateResult.ResultData[i + 2] == 0)
                        {
                            continue;
                        }
                        byte[] b = new byte[13];
                        Array.Copy(operateResult.ResultData, i, b, 0, 13);
                        tmpList.Add(b);
                    }
                    tmpList = tmpList.OrderBy(t => (t[4] << 8 | t[5])).ToList();
                    ModelsOperate.RefreshModel(tmpList);
                    if (frm_开关模块界面 != null)
                    {
                        frm_开关模块界面.RefreshPanel();
                    }
                }
            }
            if ((DateTime.Now - LastWriteDatetime).TotalMilliseconds > currentParam.发送速度 && (MainForm.WriteDic.Count() > 0 || MainForm.UpWriteDic.Count() > 0) && Communication.GetDoCommState() != 1 && !Communication.RoutInspecting && !Communication.EachRoutInspecting)
            {
                LastWriteDatetime = DateTime.Now;
                ModlesMsg v;
                if (MainForm.UpWriteDic.Count > 0)
                {
                    MainForm.UpWriteDic.TryRemove(MainForm.UpWriteDic.ElementAt(0).Key, out v);
                }
                else
                {
                    MainForm.WriteDic.TryRemove(MainForm.WriteDic.ElementAt(0).Key, out v);
                }
                if (v.模块类型 == "模块查询")
                {
                    v.Function = CommState.GetModlesMsg;
                    Communication.BeginDoCommunication(v);
                }
                else if (v.模块类型 == "信息查询")
                {
                    v.Function = CommState.GetModlesAllMsg;
                    Communication.BeginDoCommunication(v);
                }
                else
                {
                    switch (v.action)
                    {
                    case ActionState.脱扣:
                        v.Function = CommState.SetModles_TK;
                        Communication.BeginDoCommunication(v);
                        break;

                    case ActionState.位:
                        v.Function = CommState.SetModles_Reset;
                        Communication.BeginDoCommunication(v);
                        break;
                    }
                }
            }
            timer1.Start();
            label2.Text = (DateTime.Now - tmpDate).TotalMilliseconds.ToString();
            InitMsg();
        }
Exemplo n.º 25
0
 public void RcvData(string InputString)
 {
     CommState.RcvData(InputString);
 }
Exemplo n.º 26
0
        /// <summary>
        /// Opens the serial port specified by <see cref="PortName" />.
        /// </summary>
        /// <exception cref="System.ObjectDisposedException"/>
        /// <exception cref="System.InvalidOperationException">
        /// Port must first be set;
        /// or
        /// Serial Port currently open.
        /// </exception>
        /// <exception cref="System.IO.IOException">Wrong file type.</exception>
        /// <remarks>
        /// Opening the serial port does not set any settings (such as baud rate, etc.). On the windows implementation,
        /// it only sets the internal driver input and output queue.
        /// </remarks>
        public void Open()
        {
            if (m_IsDisposed)
            {
                throw new ObjectDisposedException("WinNativeSerial");
            }
            if (string.IsNullOrWhiteSpace(PortName))
            {
                throw new InvalidOperationException("Port must first be set");
            }
            if (IsOpen)
            {
                throw new InvalidOperationException("Serial Port currently open");
            }

            m_ComPortHandle = UnsafeNativeMethods.CreateFile(@"\\.\" + PortName,
                                                             NativeMethods.FileAccess.GENERIC_READ | NativeMethods.FileAccess.GENERIC_WRITE,
                                                             NativeMethods.FileShare.FILE_SHARE_NONE,
                                                             IntPtr.Zero,
                                                             NativeMethods.CreationDisposition.OPEN_EXISTING,
                                                             NativeMethods.FileAttributes.FILE_FLAG_OVERLAPPED,
                                                             IntPtr.Zero);
            if (m_ComPortHandle.IsInvalid)
            {
                WinIOError();
            }

            NativeMethods.FileType t = UnsafeNativeMethods.GetFileType(m_ComPortHandle);
            bool validOverride       = false;

            if (t != NativeMethods.FileType.FILE_TYPE_CHAR && t != NativeMethods.FileType.FILE_TYPE_UNKNOWN)
            {
                foreach (string port in GetPortNames())
                {
#if NETSTANDARD15
                    if (port.Equals(PortName, StringComparison.OrdinalIgnoreCase))
                    {
                        validOverride = true;
                        break;
                    }
#else
                    if (port.Equals(PortName, StringComparison.InvariantCultureIgnoreCase))
                    {
                        validOverride = true;
                        break;
                    }
#endif
                }

                if (!validOverride)
                {
                    m_ComPortHandle.Dispose();
                    m_ComPortHandle = null;
                    throw new IOException("Wrong file type: " + PortName);
                }
            }

            // Set the default parameters
            UnsafeNativeMethods.SetupComm(m_ComPortHandle, m_DriverInQueue, m_DriverOutQueue);

            m_CommState        = new CommState(m_ComPortHandle);
            m_CommProperties   = new CommProperties(m_ComPortHandle);
            m_CommModemStatus  = new CommModemStatus(m_ComPortHandle);
            m_CommOverlappedIo = new CommOverlappedIo(m_ComPortHandle);
            RegisterEvents();
        }
        protected override async void OnAppearing()
        {
            base.OnAppearing();
            if (!_reEntry)
            {
                _reEntry = true;
                var device = SoterDeviceFactoryBle.Instance.CurrentDevice;
                if ((device == null) || (!device.Connected))
                {
                    if (!await ConnectDevicePage.Connect(this))
                    {
                        await Navigation.PopModalAsync();

                        return;
                    }
                }
                try
                {
                    device             = SoterDeviceFactoryBle.Instance.CurrentDevice;
                    deviceName.Text    = device.Name;
                    PinPage.ParentPage = this;
                    device.DeviceButtonRequestCallback += Device_DeviceButtonRequestCallback;
                    try
                    {
                        while (_processStep < _selectedProcess.Count)
                        {
                            var currentState = _selectedProcess[_processStep];
                            switch (currentState)
                            {
                            case CommState.WipeDevice:
                                messageLabel.Text = AppResources.ConfirmWipeMessage;
                                await SoterDeviceFactoryBle.Instance.CurrentDevice.WipeDeviceAsync();

                                _state = CommState.ResetDevice;
                                break;

                            case CommState.ResetDevice:
                                messageLabel.Text = AppResources.InitializeDeviceMessage;
                                await SoterDeviceFactoryBle.Instance.CurrentDevice.ResetDeviceAsync(_deviceLabel);

                                _state = CommState.UpdateCoinTable;
                                break;

                            case CommState.UpdateCoinTable:
                                messageLabel.Text = AppResources.LoadingMessage;
                                await device.InitializeAsync();

                                Repository.SaveCurrentDeviceToDb(device);
                                await Repository.LoadCoinTableFromDeviceAsync(device);

                                break;

                            case CommState.SignBitcoinTx:
                                await device.InitializeAsync();

                                _bitcoinTX.SerializedTx = await device.SignTransactionAsync(_bitcoinTX);

                                break;
                            }
                            _processStep++;
                        }
                    }
                    finally
                    {
                        PinPage.ParentPage = null;
                        device.DeviceButtonRequestCallback -= Device_DeviceButtonRequestCallback;
                        device.Disconnect();
                        await Navigation.PopModalAsync();
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex.ToString());
                }
                _waitHandle.Set();
            }
        }