void tmConnect_Tick(object eventState)
        {
            lock (this)
            {
                if(bFlagCon) return;
                bFlagCon = true;
            }
            if(DeviceToConnect!= (TypeDevice)eventState)
            {

            }
            if (Connect2Device((TypeDevice)eventState, NumConDev) == 0)
            {
                try
                {
                    tmConnect.Dispose();
                    tmConnect = null;
                }
                catch (Exception ex)
                {

                }
                if (StatCon != StatusConnect.Connected)
                {
                    StatCon = StatusConnect.Connected;
                    if (evStatusConnect != null)
                        evStatusConnect(StatCon);
                }
            }
            else
            {
                if (StatCon != StatusConnect.NotConnect)
                {
                    StatCon = StatusConnect.NotConnect;
                    if (evStatusConnect != null)
                        evStatusConnect(StatCon);
                }
            }
            bFlagCon = false;
        }
        public int Connect2Device(TypeDevice typeDevice, uint NumDev)
        {
            DeviceToConnect = typeDevice;
            UseFtdiChip.SearchDevice();

            bool bFound = false;
            if (typeDevice == TypeDevice.Selector)
            {
                for (uint i = 0; i < UseFtdiChip.DevInformation.Length; i++)
                {
                    FTDI.DevData _dev = UseFtdiChip.DevInformation[i];

                    if (_dev == null) continue;
                    string str = _dev.DevDescription;

                    if (str.Contains(TypeDevice.Selector.ToString())
                        || str.Contains("USB <-> Serial")
                        || str.Contains("FT232R USB UART")
                        || str.Contains("Electric") == false
                        )
                    {
                        NumConDev = i;
                        bFound = true;
                    }
                }
            }
            else if (typeDevice == TypeDevice.ElectricBarred)
            {
                for (uint i = 0; i < UseFtdiChip.DevInformation.Length; i++)
                {
                    FTDI.DevData _dev = UseFtdiChip.DevInformation[i];

                    if (_dev == null) continue;
                    string str = _dev.DevDescription;

                    if (str.Contains("Electric"))
                    {
                        NumConDev = i;
                        bFound = true;
                    }
                }
            }
            if (bFound == false)
            {
                if (tmConnect == null)
                {
                    if (StatCon != StatusConnect.NotConnect)
                    {
                        StatCon = StatusConnect.NotConnect;
                        if (evStatusConnect != null)
                            evStatusConnect(StatCon);
                    }
                    tmConnect = new Timer(timerDelegate, DeviceToConnect, 0, 250);
                }
                return 1;
            }
            NumDev = NumConDev;

            //Установка параметров связи по умолчанию
            if (UseFtdiChip.ConnectWithDefSetting(NumDev) != 0)
            {
                //Соединение не удалось
                if (tmConnect == null)
                {
                    if (StatCon != StatusConnect.NotConnect)
                    {
                        StatCon = StatusConnect.NotConnect;
                        if (evStatusConnect != null)
                            evStatusConnect(StatCon);
                    }
                    tmConnect = new Timer(timerDelegate, DeviceToConnect, 0, 250);
                }
                return 1;
            }
            if (StatCon != StatusConnect.Connected)
            {
                StatCon = StatusConnect.Connected;
                if (evStatusConnect != null)
                    evStatusConnect(StatCon);
            }

            if (tmConnect != null)
            {
                try
                {
                    //tmConnect.Stop();//.Abort();
                    tmConnect.Dispose();
                    tmConnect = null;
                }
                catch
                {
                }
                finally
                {
                }
            }
            try
            {
                ReceiveDataTh = new Thread(FuncRecD);
                //ReceiveDataTh.
                ReceiveDataTh.Name = "ReceiveDataTh";
                ReceiveDataTh.Start();
            }
            catch (System.Exception e)
            {

            }

            return 0;
        }
Exemple #3
0
        public void Timer_Search_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            //Este timer se desactiva siempre al entrar y se debe hacer un start siempre qu se salga
            bool   bRestartTimer = true;
            string sError        = "";

            lock (m_LockTimer)
            {
                StatusConnect StatusConnect_New = new StatusConnect();
                IPEndPoint    NumEndPoint       = default(IPEndPoint);

                switch (m_StatusConnect)
                {
                case StatusConnect.StopSearch:
                    // si se solicitó un puerto
                    if (!string.IsNullOrEmpty(EndPointSearch))
                    {
                        bRestartTimer = false;
                    }
                    break;

                case StatusConnect.WaitSearch:
                    // iRefreshUDPCount = -1 Detenida la actualización
                    if (iRefreshUDPCount >= 0)
                    {
                        iRefreshUDPCount++;
                    }
                    if (iRefreshUDPCount >= iRefreshUDPinWaitSearch || bRefreshUDPForce)
                    {
                        myRefreshStationList();
                        iRefreshUDPCount = 0;
                    }

                    IndexStation = discoveredStations.Number - 1;

                    StatusConnect_New       = StatusConnect.Search;
                    m_Timer_Search.Interval = MS_NEW_SEARCH;
                    break;

                case StatusConnect.Search:
                    try
                    {
                        if (!string.IsNullOrEmpty(EndPointSearch))
                        {
                            string[] aIPPort = EndPointSearch.Split(':');
                            WinSockIn = new RoutinesLibrary.Net.Protocols.TCP.TCP(new IPEndPoint(IPAddress.Parse(aIPPort[0].Trim()), System.Convert.ToInt32(ushort.Parse(aIPPort[1].Trim()))));
                            WinSockIn.ClosedConnectionTCP += new RoutinesLibrary.Net.Protocols.TCP.TCP.ClosedConnectionTCPEventHandler(WinSockIn_FinishConnection);
                            WinSockIn.DataReceived        += new RoutinesLibrary.Net.Protocols.TCP.TCP.DataReceivedEventHandler(WinSockIn_DataReceived);
                            if (WinSockIn.Connect(ref sError))
                            {
                                m_Timer_Search.Interval = MS_WAIT_NAK;
                                StatusConnect_New       = StatusConnect.WaitNAKorHS;
                                m_FrameDataIn01.Reset();     // preparar buffer de entrada
                                m_FrameDataOut01.Reset();    // preparar buffer de salida
                                m_FrameDataIn02.Reset();     // preparar buffer de entrada
                                m_FrameDataOut02.Reset();    // preparar buffer de salida
                                m_Conection_FrameProtocol = CStationBase.Protocol.Protocol_undefined;
                            }
                            else
                            {
                                //Error. Se prepara para una nueva busqueda
                                StatusConnect_New = StatusConnect.Search;
                                if (m_Timer_Search != null)
                                {
                                    m_Timer_Search.Interval = MS_NEW_SEARCH; //Genera un nuevo evento lo antes posible
                                }
                                CloseWinSock(ref WinSockIn);                 // se elimina el puerto creado
                            }
                        }
                        else if (IndexStation < 0)
                        {
                            StatusConnect_New       = StatusConnect.WaitSearch;
                            m_Timer_Search.Interval = MS_WAIT_SEARCH;
                        }
                        else
                        {
                            // define the next indexstation
                            while (IndexStation >= 0)
                            {
                                if (discoveredStations.get_Connected(IndexStation))
                                {
                                    IndexStation--;
                                }
                                else
                                {
                                    break;
                                }
                            }

                            if (IndexStation < 0)
                            {
                                StatusConnect_New       = StatusConnect.WaitSearch;
                                m_Timer_Search.Interval = MS_WAIT_SEARCH;
                            }
                            else
                            {
                                NumEndPoint = discoveredStations.GetStation(IndexStation).StationData.IPEndPointValue;
                                WinSockIn   = new RoutinesLibrary.Net.Protocols.TCP.TCP(new IPEndPoint(NumEndPoint.Address, System.Convert.ToInt32((ushort)NumEndPoint.Port)));
                                WinSockIn.ClosedConnectionTCP += new RoutinesLibrary.Net.Protocols.TCP.TCP.ClosedConnectionTCPEventHandler(WinSockIn_FinishConnection);
                                WinSockIn.DataReceived        += new RoutinesLibrary.Net.Protocols.TCP.TCP.DataReceivedEventHandler(WinSockIn_DataReceived);
                                if (WinSockIn.Connect(ref sError))
                                {
                                    //Debug.Print("SearchTCP WinSockIn.Connect true: " & NumEndPoint.ToString)
                                    m_Timer_Search.Interval = MS_WAIT_NAK;
                                    StatusConnect_New       = StatusConnect.WaitNAKorHS;
                                    m_FrameDataIn01.Reset();     // preparar buffer de entrada
                                    m_FrameDataOut01.Reset();    // preparar buffer de salida
                                    m_FrameDataIn02.Reset();     // preparar buffer de entrada
                                    m_FrameDataOut02.Reset();    // preparar buffer de salida
                                    m_Conection_FrameProtocol = CStationBase.Protocol.Protocol_undefined;
                                }
                                else
                                {
                                    //Debug.Print("SearchTCP WinSockIn.Connect false: " & NumEndPoint.ToString)
                                    //Error. Se prepara para una nueva busqueda
                                    StatusConnect_New = StatusConnect.Search;
                                    if (m_Timer_Search != null)
                                    {
                                        m_Timer_Search.Interval = MS_NEW_SEARCH; //Genera un nuevo evento lo antes posible
                                    }
                                    CloseWinSock(ref WinSockIn);                 // se elimina el puerto creado
                                }
                                IndexStation--;
                            }
                        }
                    }
                    catch (Exception)
                    {
                        //Debug.Print("SearchTCP Exception in Search: " & ex.Message)
                        //Error. Se prepara para una nueva busqueda
                        StatusConnect_New = StatusConnect.Search;
                        if (m_Timer_Search != null)
                        {
                            m_Timer_Search.Interval = MS_NEW_SEARCH; //Genera un nuevo evento lo antes posible
                        }
                        CloseWinSock(ref WinSockIn);                 // se elimina el puerto creado
                        IndexStation--;
                    }
                    break;

                case StatusConnect.WaitNAKorHS:
                case StatusConnect.WaitFW:
                case StatusConnect.WaitHS:
                case StatusConnect.WaitACK:
                case StatusConnect.WaitNum:
                    //TimeOut. Se prepara para una nueva busqueda
                    //Debug.Print("SearchTCP TimeOut en StatusConnect: " & StatusConnect.ToString)
                    StatusConnect_New       = StatusConnect.Search;
                    m_Timer_Search.Interval = MS_NEW_SEARCH; //Genera un nuevo evento lo antes posible
                    CloseWinSock(ref WinSockIn);             // se elimina el puerto creado

                    // si se solicitó una dirección específica, reintentar y luego parar
                    if (!string.IsNullOrEmpty(EndPointSearch))
                    {
                        if (iReintentosSobreEndPointSolicitado >= MAX_REINTENTOS_SOBRE_ENDPOINT_SOLICITADO)
                        {
                            if (NoConexionEvent != null)
                            {
                                NoConexionEvent(EndPointSearch);
                            }
                            m_StatusConnect = StatusConnect.StopSearch;
                            // no rearranca el timer
                            bRestartTimer = false;
                        }
                        else
                        {
                            iReintentosSobreEndPointSolicitado++;
                        }
                    }
                    else
                    {
                        IndexStation--;
                    }
                    break;
                }

                m_reintentos   += 1;
                m_StatusConnect = StatusConnect_New;

                try
                {
                    if (bRestartTimer && m_Timer_Search != null)
                    {
                        m_Timer_Search.Start();
                    }
                }
                catch (Exception)
                {
                }
            }
        }
Exemple #4
0
        public void Timer_Search_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            //Este timer se desactiva siempre al entrar y se debe hacer un start siempre qu se salga
            bool   bRestartTimer = true;
            string SearchingPort = "";

            lock (m_LockTimer)
            {
                StatusConnect StatusConnect_New = new StatusConnect();

                switch (m_StatusConnect)
                {
                case StatusConnect.StopSearch:
                    // si se solicitó un puerto
                    if (!string.IsNullOrEmpty(m_PortSearch) || m_StartHandshake)
                    {
                        bRestartTimer = false;
                    }
                    break;

                case StatusConnect.WaitSearch:
                    // begin to searching thru the port list
                    if (string.IsNullOrEmpty(m_PortSearch))
                    {
                        string[] portlist = System.IO.Ports.SerialPort.GetPortNames();
                        if (!ReferenceEquals(Type.GetType("Mono.Runtime"), null))
                        {
                            List <string> availablePorts = new List <string>();

                            foreach (string c in portlist)
                            {
                                if (c.Contains("ttyUSB") || c.Contains("ttyACM"))
                                {
                                    availablePorts.Add(c);
                                }
                            }

                            portlist = availablePorts.ToArray();
                        }
                        m_PortsList = new ReadOnlyCollection <string>(portlist);
                    }
                    else
                    {
                        List <string> tempList = new List <string>();
                        tempList.Add(m_PortSearch);
                        m_PortsList = new ReadOnlyCollection <string>(tempList);
                        m_iReintentosSobrePuertoSolicitado = 0;
                    }

                    m_IndexPort       = m_PortsList.Count - 1;
                    StatusConnect_New = StatusConnect.Search;
                    if (m_Timer_Search != null)
                    {
                        m_Timer_Search.Interval = MS_NEW_SEARCH;
                    }
                    break;

                case StatusConnect.Search:
                case StatusConnect.RetryHS:
                    // next in the port list or retry Handshake
                    try
                    {
                        if (m_StatusConnect == StatusConnect.RetryHS)
                        {
                            m_iReintentosSobrePuertoSolicitado++; // aumentar reintentos
                            m_IndexPort++;                        // reintentar con el índice anterior
                        }
                        if (m_IndexPort < 0)
                        {
                            StatusConnect_New = StatusConnect.WaitSearch;
                            if (m_Timer_Search != null)
                            {
                                m_Timer_Search.Interval = MS_WAIT_SEARCH;
                            }
                        }
                        else
                        {
                            SerialPort NewSP = new SerialPort();
                            SearchingPort  = m_PortsList[m_IndexPort];
                            NewSP.PortName = m_PortsList[m_IndexPort];
                            if (!(RoutinesLibrary.IO.SerialPort.isOpen(NewSP)))
                            {
                                m_SerialPort_Int = new RoutinesLibrary.IO.SerialPort(NewSP);
                                m_SerialPort_Int.DataReceived += new RoutinesLibrary.IO.SerialPort.DataReceivedEventHandler(SerialPort_Int_DataReceived);
                                m_SerialPort_Int.ConfigPort(m_PortConfig);
                                m_IndexPort--;

                                if (m_Timer_Search != null)
                                {
                                    m_Timer_Search.Interval = MS_WAIT_NAK;
                                }

                                m_MessageFIFOIn.Reset();      // preparar lista de tramas recibidas
                                m_FrameDataIn01.Reset();      // preparar buffer de entrada
                                m_FrameDataOut01.Reset();     // preparar buffer de salida
                                m_FrameDataIn02.Reset();      // preparar buffer de entrada
                                m_FrameDataOut02.Reset();     // preparar buffer de salida

                                if (m_StartHandshake)
                                {
                                    StatusConnect_New         = StatusConnect.WaitACKofHS;
                                    m_Conection_FrameProtocol = CStationBase.Protocol.Protocol_02;
                                    SendHandshake();
                                }
                                else
                                {
                                    StatusConnect_New         = StatusConnect.WaitNAKorHS;
                                    m_Conection_FrameProtocol = CStationBase.Protocol.Protocol_undefined;
                                }
                            }
                            else
                            {
                                //m_SerialPort_Int.DataReceived -= new RoutinesLibrary.IO.SerialPort.DataReceivedEventHandler(SerialPort_Int_DataReceived);
                                //TODO: Tiene sentido???
                                StatusConnect_New = StatusConnect.Search;
                                m_IndexPort--;
                                if (m_SerialPort_Int != null)
                                {
                                    m_SerialPort_Int.Dispose();
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(System.Reflection.MethodInfo.GetCurrentMethod().Name + ". Error: " + ex.Message);
                        //Error. Se prepara para una nueva busqueda
                        StatusConnect_New = StatusConnect.Search;
                        if (m_Timer_Search != null)
                        {
                            m_Timer_Search.Interval = MS_NEW_SEARCH;
                        }
                        //m_SerialPort_Int.DataReceived -= new RoutinesLibrary.IO.SerialPort.DataReceivedEventHandler(SerialPort_Int_DataReceived);
                        m_SerialPort_Int.Dispose();
                    }
                    break;

                case StatusConnect.WaitNAKorHS:
                    //TimeOut. Se prepara para una nueva busqueda
                    // HANDSHAKE DE ESTACIÓN
                    StatusConnect_New = StatusConnect.Search;
                    if (m_Timer_Search != null)
                    {
                        m_Timer_Search.Interval = MS_NEW_SEARCH;
                    }
                    //m_SerialPort_Int.DataReceived -= new RoutinesLibrary.IO.SerialPort.DataReceivedEventHandler(SerialPort_Int_DataReceived);
                    m_SerialPort_Int.Dispose();

                    // si se solicitó un puerto, reintentar 5 veces
                    if (!string.IsNullOrEmpty(m_PortSearch))
                    {
                        if (m_iReintentosSobrePuertoSolicitado >= MAX_REINTENTOS_SOBRE_PUERTO_SOLICITADO)
                        {
                            if (NoConexionEvent != null)
                            {
                                NoConexionEvent(m_PortSearch);
                            }
                            StatusConnect_New = StatusConnect.StopSearch;
                            // no rearranca el timer
                            bRestartTimer = false;
                        }
                        else
                        {
                            StatusConnect_New = StatusConnect.RetryHS;
                        }
                    }
                    break;

                case StatusConnect.WaitACKofHS:
                    //TimeOut. Se prepara para una nueva busqueda
                    // HANDSHAKE DE PC
                    StatusConnect_New = StatusConnect.Search;
                    if (m_Timer_Search != null)
                    {
                        m_Timer_Search.Interval = MS_NEW_SEARCH;
                    }
                    //m_SerialPort_Int.DataReceived -= new RoutinesLibrary.IO.SerialPort.DataReceivedEventHandler(SerialPort_Int_DataReceived);
                    m_SerialPort_Int.Dispose();

                    // si se solicitó handshake desde el PC, reintentar 5 veces
                    if (m_iReintentosSobrePuertoSolicitado >= MAX_REINTENTOS_SOBRE_PUERTO_SOLICITADO)
                    {
                        // si se especificó un puerto, detener. si no, sigue el StatusConnect.Search
                        if (!string.IsNullOrEmpty(m_PortSearch))
                        {
                            if (NoConexionEvent != null)
                            {
                                NoConexionEvent(m_PortSearch);
                            }
                            StatusConnect_New = StatusConnect.StopSearch;
                            // no rearranca el timer
                            bRestartTimer = false;
                        }
                    }
                    else
                    {
                        StatusConnect_New = StatusConnect.RetryHS;
                    }
                    break;

                case StatusConnect.WaitACK:
                    //TimeOut. Se prepara para una nueva busqueda
                    StatusConnect_New = StatusConnect.Search;
                    if (m_Timer_Search != null)
                    {
                        m_Timer_Search.Interval = MS_NEW_SEARCH;
                    }
                    //m_SerialPort_Int.DataReceived -= new RoutinesLibrary.IO.SerialPort.DataReceivedEventHandler(SerialPort_Int_DataReceived);
                    m_SerialPort_Int.Dispose();
                    break;

                case StatusConnect.WaitNum:
                    //TimeOut. Se prepara para una nueva busqueda
                    StatusConnect_New = StatusConnect.Search;
                    if (m_Timer_Search != null)
                    {
                        m_Timer_Search.Interval = MS_NEW_SEARCH;
                    }
                    //m_SerialPort_Int.DataReceived -= new RoutinesLibrary.IO.SerialPort.DataReceivedEventHandler(SerialPort_Int_DataReceived);
                    m_SerialPort_Int.Dispose();
                    break;

                case StatusConnect.WaitFW:
                case StatusConnect.WaitHS:
                    //TimeOut protocolo 2. Se prepara para una nueva busqueda
                    //Debug.Print("Timer_Search_Elapsed-WaitFM timeout")
                    StatusConnect_New = StatusConnect.Search;
                    if (m_Timer_Search != null)
                    {
                        m_Timer_Search.Interval = MS_NEW_SEARCH;
                    }
                    //m_SerialPort_Int.DataReceived -= new RoutinesLibrary.IO.SerialPort.DataReceivedEventHandler(SerialPort_Int_DataReceived);
                    m_SerialPort_Int.Dispose();
                    break;
                }

                m_StatusConnect = StatusConnect_New;

                try
                {
                    if (bRestartTimer && m_Timer_Search != null)
                    {
                        m_Timer_Search.Start();
                    }
                }
                catch (Exception)
                {
                }
            }
        }
        protected void ParseDataReceived()
        {
            byte[]       DataIn           = null;
            byte[]       DataOut          = null;
            bool         Conecta          = false;
            EnumReceived ReceivedWaitACK  = default(EnumReceived);
            string       sStationModel    = "";
            int          iErrors          = 0; //Unused
            string       sCommandProtocol = "";
            string       SoftwareVersion  = "";
            string       HardwareVersion  = "";

            switch (m_StatusConnect)
            {
            case StatusConnect.WaitNAKorHS:
            case StatusConnect.WaitHS:
                // esperanndo NAK de protocolo 01 o inicio de trama handshake (DLE-STX) de protocolo 02

                DataIn = ReadBytes();

                //
                // Conexión protocolo 02 (por tramas)
                //

                // Nuevo protocolo 2: puede venir una trama de handshaking
                // verificar si viene una trama y cargar en FrameDatain
                if (((DataIn.Length > 0 && DataIn[0] == ASCII_DLE) & m_StatusConnect == StatusConnect.WaitNAKorHS) ||
                    (m_StatusConnect == StatusConnect.WaitHS))
                {
                    m_Conection_FrameProtocol = CStationBase.Protocol.Protocol_02;

                    // seguir leyendo en buffer de entrada
                    iErrors = m_FrameDataIn02.DecodeCheckReceivedData(DataIn, -1, ref m_MessageFIFOIn);

                    // ha recibido un frame
                    if (m_MessageFIFOIn.Number > 0)
                    {
                        // verificar trama Handshake y obtener número de dispositivo del PC asignado por la estación
                        // si conecta = false -> frames leídos sin handshaking
                        Conecta = false;
                        foreach (CDllFifoMessages.MessageDll message in m_MessageFIFOIn.GetTable)
                        {
                            // FID a recibir FDh
                            // Control Handshake 00h
                            // El número de dispositivo asignado vendrá tanto en TargetDevice como en los datos
                            // Filtramos las direcciones origen
                            if (message.Command == (byte)EnumCommandFrame_02_SOLD.M_HS &&
                                message.FID == 0xFD &&
                                STATION_ADDRESS_AVAILABLES.Contains(message.SourceDevice))
                            {
                                m_pcNumDevice      = message.TargetDevice;
                                m_stationNumDevice = message.SourceDevice;
                                Conecta            = true;
                                break;
                            }
                        }
                    }
                    else if (m_FrameDataIn02.GetFrame().Length > 0)
                    {
                        // ha recibido parte de un frame, seguir leyendo
                        m_StatusConnect = StatusConnect.WaitHS;
                        break;
                    }
                    else
                    {
                        Conecta = false;
                    }


                    //
                    // Conexión protocolo 01
                    //
                }
                else
                {
                    foreach (byte byt in DataIn)
                    {
                        if (byt == ASCII_NAK)
                        {
                            // protocolo conexión 01
                            Conecta = true;
                            m_Conection_FrameProtocol = CStationBase.Protocol.Protocol_01;
                        }
                        else
                        {
                            // si no es protocolo conexión 02, todos han de ser NAK
                            m_Conection_FrameProtocol = CStationBase.Protocol.Protocol_undefined;
                            Conecta = false;
                            break;
                        }
                    }
                }

                //Conexion no válida
                if (Conecta == false)
                {
                    CloseConnection();
                    m_StatusConnect = StatusConnect.Search;

                    m_Timer_Search.Stop();
                    m_Timer_Search.Interval = MS_NEW_SEARCH;
                    m_Timer_Search.Start();
                    break;
                }

                // conexión válida -> responder, según protocolo
                try
                {
                    switch (m_Conection_FrameProtocol)
                    {
                    case CStationBase.Protocol.Protocol_01:
                        // send SYN
                        SendBytes(new byte[] { ASCII_SYN });

                        m_Timer_Search.Interval = MS_WAIT_ACK;
                        m_StatusConnect         = StatusConnect.WaitACK;
                        break;

                    case CStationBase.Protocol.Protocol_02:
                        // responder con Handshake y ACK en Datos
                        // 04/04/2016 Limpiar buffer de entrada para la próxima consulta
                        m_MessageFIFOIn.Reset();         // inicializa los mensajes de entrada
                        m_FrameDataIn02.Reset();         // inicializa buffer de entrada

                        DataOut    = new byte[1];
                        DataOut[0] = (byte)EnumCommandFrame_02_SOLD.M_ACK;
                        // XOR porque es respuesta
                        m_FrameDataOut02.EncodeFrame(DataOut, (byte)(m_pcNumDevice ^ 0x80), m_stationNumDevice, (byte)EnumCommandFrame_02_SOLD.M_HS, (byte)(0xFD));
                        SendBytes(m_FrameDataOut02.GetStuffedFrame());

                        // enviar solicitud de firmware
                        DataOut = new byte[0];
                        byte FIDSent_1 = (byte)237;
                        // 26/06/2014 El FIRMWARE se pide siempre al Device 0 (en protocolo 02), porque en las touch el HANDSHAKE lo emite el device COM y devuelve COM
                        //FrameDataOut02.EncodeFrame(DataOut, pcNumDevice, stationNumDevice, Stack_apl_JBC.EnumCommandFrame.M_FIRMWARE, FIDSent)
                        // 05/11/2014 Se vuelve a enviar al device de conexión y se analiza en WaitFW si se debe enviar al 00
                        //FrameDataOut02.EncodeFrame(DataOut, pcNumDevice, 0, Stack_apl_JBC_BURST.EnumCommandFrame.M_FIRMWARE, FIDSent)
                        m_FrameDataOut02.EncodeFrame(DataOut, m_pcNumDevice, m_stationNumDevice, (byte)EnumCommandFrame_02_SOLD.M_FIRMWARE, FIDSent_1);
                        SendBytes(m_FrameDataOut02.GetStuffedFrame());

                        m_Timer_Search.Interval = MS_WAIT_FIRMWARE;
                        m_StatusConnect         = StatusConnect.WaitFW;
                        break;
                    }
                }
                catch (Exception)
                {
                    CloseConnection();
                    m_StatusConnect         = StatusConnect.Search;
                    m_Timer_Search.Interval = MS_NEW_SEARCH;
                }
                break;

            case StatusConnect.WaitACKofHS:
                // esperanndo ACK (o NAK) de protocolo 02 de un handshake emitido por el PC
                DataIn = ReadBytes();

                //
                // Respuesta handshake de PC protocolo 02
                //

                // verificar si viene una trama de respuesta de Handshake y cargar en FrameDatain
                if (DataIn.Length > 0 && DataIn[0] == ASCII_DLE)
                {
                    m_Conection_FrameProtocol = CStationBase.Protocol.Protocol_02;

                    // seguir leyendo en buffer de entrada
                    iErrors = m_FrameDataIn02.DecodeCheckReceivedData(DataIn, -1, ref m_MessageFIFOIn);

                    // ha recibido un frame
                    if (m_MessageFIFOIn.Number > 0)
                    {
                        // verificar trama respuesta de Handshake
                        // si conecta = false -> frames leídos sin handshaking
                        Conecta = false;
                        foreach (CDllFifoMessages.MessageDll message in m_MessageFIFOIn.GetTable)
                        {
                            // FID a recibir FDh
                            // Control Handshake 00h
                            // El número de dispositivo asignado vendrá tanto en TargetDevice como en los datos
                            // Filtramos las direcciones origen
                            if (message.Command == (byte)EnumCommandFrame_02_SOLD.M_HS & message.FID == 0xFD)
                            {
                                if (message.Datos[0] == (byte)EnumCommandFrame_02_SOLD.M_ACK)
                                {
                                    m_pcNumDevice      = message.TargetDevice;
                                    m_stationNumDevice = message.SourceDevice;
                                    Conecta            = true;
                                    break;
                                }
                                else
                                {
                                    Conecta = false;
                                }
                            }
                        }
                    }
                    else if (m_FrameDataIn02.GetFrame().Length > 0)
                    {
                        // ha recibido parte de un frame, seguir leyendo
                        m_StatusConnect = StatusConnect.WaitACKofHS;
                        break;
                    }
                    else
                    {
                        Conecta = false;
                    }
                }

                //Conexion no válida
                if (Conecta == false)
                {
                    CloseConnection();
                    m_StatusConnect = StatusConnect.Search;

                    m_Timer_Search.Stop();
                    m_Timer_Search.Interval = MS_NEW_SEARCH;
                    m_Timer_Search.Start();
                    break;
                }

                // conexión válida -> solicitar FIRMWARE
                try
                {
                    switch (m_Conection_FrameProtocol)
                    {
                    case CStationBase.Protocol.Protocol_02:
                        // enviar solicitud de firmware
                        m_MessageFIFOIn.Reset();         // inicializa los mensajes de entrada
                        m_FrameDataIn02.Reset();         // inicializa buffer de entrada

                        // enviar solicitud de firmware
                        DataOut = new byte[0];
                        byte FIDSent_2 = (byte)237;
                        m_FrameDataOut02.EncodeFrame(DataOut, m_pcNumDevice, m_stationNumDevice, (byte)EnumCommandFrame_02_SOLD.M_FIRMWARE, FIDSent_2);
                        SendBytes(m_FrameDataOut02.GetStuffedFrame());

                        m_Timer_Search.Interval = MS_WAIT_FIRMWARE;
                        m_StatusConnect         = StatusConnect.WaitFW;
                        break;
                    }
                }
                catch (Exception)
                {
                    CloseConnection();
                    m_StatusConnect         = StatusConnect.Search;
                    m_Timer_Search.Interval = MS_NEW_SEARCH;
                }
                break;

            case StatusConnect.WaitFW:
                // se espera la respuesta a la solicitud de FIRMWARE (para los 2 protocolos de conexión 01 y 02)
                DataIn = ReadBytes();

                // esperando trama de firmware del protocolo de conexión 02
                if (m_Conection_FrameProtocol == CStationBase.Protocol.Protocol_02)
                {
                    // quizás checkear devices
                    iErrors = m_FrameDataIn02.DecodeCheckReceivedData(DataIn, -1, ref m_MessageFIFOIn);
                    if (m_MessageFIFOIn.Number > 0)
                    {
                        // ha recibido un frame
                        // analizar trama y obtener dato station model y protocolo
                        // si conecta = false -> frames leídos sin FIRMWARE
                        Conecta = false;
                        foreach (CDllFifoMessages.MessageDll message in m_MessageFIFOIn.GetTable)
                        {
                            // Control Firmware
                            // analizar trama y obtener dato station model
                            if (message.Command == (byte)EnumCommandFrame_02_SOLD.M_FIRMWARE)
                            {
                                string   sFirmw = System.Text.Encoding.UTF8.GetString(message.Datos);
                                string[] aFirmw = sFirmw.Split(':');

                                if (aFirmw.Length < 2)
                                {
                                    m_StatusConnect = StatusConnect.Search;
                                    m_Timer_Search.Stop();
                                    m_Timer_Search.Interval = MS_NEW_SEARCH;
                                    m_Timer_Search.Start();
                                    break;
                                }

                                sCommandProtocol = aFirmw[0].Trim();
                                sStationModel    = aFirmw[1].Trim();  // format: model_modeltype_modelversion
                                SoftwareVersion  = aFirmw[2].Trim();
                                HardwareVersion  = aFirmw[3].Trim();

                                CStationBase.Protocol commandProtocol = default(CStationBase.Protocol);
                                switch (sCommandProtocol)
                                {
                                case "01":
                                    commandProtocol = CStationBase.Protocol.Protocol_01;
                                    break;

                                case "02":
                                    commandProtocol = CStationBase.Protocol.Protocol_02;
                                    break;

                                default:
                                    commandProtocol = CStationBase.Protocol.Protocol_01;
                                    break;
                                }

                                // ver si el FIRMWARE me ha devuelto como modelo COM_DTE_01, por lo que es una DME
                                // no actualizada y debo pedir el FIRMWARE (y continuar) con el devide H00
                                if (commandProtocol == CStationBase.Protocol.Protocol_02 & sStationModel.Substring(0, 3) == "COM")
                                {
                                    // OJO, borrar lista de mensajes de entrada para recibir de nuevo el M_FIRMWARE
                                    // si no lo hacemos, se queda el mensaje anterior en la lista y se lee el primero que encuentra (el mismo)
                                    // 04/04/2016 Limpiar buffer de entrada para la próxima consulta
                                    m_MessageFIFOIn.Reset();     // inicializa los mensajes de entrada
                                    m_FrameDataIn02.Reset();     // inicializa buffer de entrada

                                    // volver a enviar solicitud de firmware pero al device 0
                                    DataOut = new byte[0];
                                    byte FIDSent = (byte)(message.FID + 1);
                                    m_stationNumDevice = (byte)0;
                                    m_FrameDataOut02.EncodeFrame(DataOut, m_pcNumDevice, m_stationNumDevice, (byte)EnumCommandFrame_02_SOLD.M_FIRMWARE, FIDSent);
                                    SendBytes(m_FrameDataOut02.GetStuffedFrame());

                                    m_Timer_Search.Interval = MS_WAIT_FIRMWARE;
                                    m_StatusConnect         = StatusConnect.WaitFW;
                                }
                                else
                                {
                                    //Se prepara para una nueva conexión
                                    m_StatusConnect = StatusConnect.Search;

                                    if (m_Timer_Search != null)
                                    {
                                        m_Timer_Search.Interval = MS_NEW_SEARCH;
                                    }

                                    // nueva conexión
                                    RaiseNewConnection(commandProtocol, sStationModel, SoftwareVersion, HardwareVersion);
                                }

                                break;
                            }
                        }
                    }
                    else if (m_FrameDataIn02.GetFrame().Length > 0)
                    {
                        // ha recibido parte de un frame, seguir leyendo
                        m_StatusConnect = StatusConnect.WaitFW;
                        break;
                    }

                    // esperando trama de firmware del protocolo de conexión 01
                }
                else if (m_Conection_FrameProtocol == CStationBase.Protocol.Protocol_01)
                {
                    // quizás checkear devices
                    iErrors = m_FrameDataIn01.DecodeCheckReceivedData(DataIn, -1, ref m_MessageFIFOIn);
                    if (m_MessageFIFOIn.Number > 0)
                    {
                        // ha recibido un frame
                        // analizar trama y obtener dato station model y protocolo
                        // si conecta = false -> frames leídos sin FIRMWARE
                        Conecta = false;
                        foreach (CDllFifoMessages.MessageDll message in m_MessageFIFOIn.GetTable)
                        {
                            // Control Firmware
                            // analizar trama y obtener dato station model y protocolo
                            if (message.Command == (byte)EnumCommandFrame_01_SOLD.M_FIRMWARE)
                            {
                                string   sFirmw = System.Text.Encoding.UTF8.GetString(message.Datos);
                                string[] aFirmw = sFirmw.Split(':');

                                if (aFirmw.Length < 3)
                                {
                                    m_StatusConnect = StatusConnect.Search;
                                    m_Timer_Search.Stop();
                                    m_Timer_Search.Interval = MS_NEW_SEARCH;
                                    m_Timer_Search.Start();

                                    break;
                                }

                                sCommandProtocol = aFirmw[0].Trim();
                                sStationModel    = aFirmw[1].Trim();  // format: model_modeltype?_modelversion
                                                                      // 01/06/2016 Edu Se detecta que en protocolo 01, al grabar un UID de 20 caracteres, añade los últimos 7 también al Software del string de FIRMWARE,
                                                                      // por lo tanto se toman sólo los 7 primeros caracteres del software y del hardware
                                SoftwareVersion = aFirmw[2].Trim().Substring(0, 7);
                                HardwareVersion = aFirmw[3].Trim().Substring(0, 7);

                                CStationBase.Protocol commandProtocol = default(CStationBase.Protocol);
                                switch (sCommandProtocol)
                                {
                                case "01":
                                    commandProtocol = CStationBase.Protocol.Protocol_01;
                                    break;

                                case "02":
                                    commandProtocol = CStationBase.Protocol.Protocol_02;
                                    break;

                                default:
                                    commandProtocol = CStationBase.Protocol.Protocol_01;
                                    break;
                                }

                                //Se prepara para una nueva conexión
                                m_StatusConnect = StatusConnect.Search;

                                if (m_Timer_Search != null)
                                {
                                    m_Timer_Search.Interval = MS_NEW_SEARCH;
                                }

                                RaiseNewConnection(commandProtocol, sStationModel, SoftwareVersion, HardwareVersion);

                                break;
                            }
                        }
                    }
                    else if (m_FrameDataIn01.GetFrame().Length > 0)
                    {
                        // ha recibido parte de un frame, seguir leyendo
                        m_StatusConnect = StatusConnect.WaitFW;
                        break;
                    }
                }
                break;

            case StatusConnect.WaitACK:
                // Protocol 01: waiting ACK
                // se espera la respuesta a la solicitud de FIRMWARE (para los 2 protocolos de conexión 01 y 02)

                DataIn          = ReadBytes();
                ReceivedWaitACK = EnumReceived.Null;

                foreach (byte byt in DataIn)
                {
                    if (byt == ASCII_ACK)
                    {
                        ReceivedWaitACK = EnumReceived.ACK;
                    }
                    else if (byt == ASCII_NAK)
                    {
                        ReceivedWaitACK = EnumReceived.NAK;
                    }
                    else     //Todos han de ser ACK o NAK
                    {
                        ReceivedWaitACK = EnumReceived.Other;
                        break;
                    }
                }

                switch (ReceivedWaitACK)
                {
                case EnumReceived.Null:         // si no ha llegado nada
                    break;

                // seguir esperando
                case EnumReceived.ACK:         // si todo lo que ha llegado son NAK menos el último que es un ACK
                    try
                    {
                        SendBytes(new byte[] { ASCII_ACK });
                    }
                    catch (Exception)
                    {
                        CloseConnection();
                        m_StatusConnect         = StatusConnect.Search;
                        m_Timer_Search.Interval = MS_NEW_SEARCH;
                        break;
                    }

                    m_StatusConnect         = StatusConnect.WaitNum;
                    m_Timer_Search.Interval = MS_WAIT_ACK;
                    break;

                case EnumReceived.NAK:         // si todos son NAK salir y esperar más caracteres
                    break;

                // seguir esperando
                case EnumReceived.Other:         // si ha llegado algo inesperado
                    CloseConnection();
                    m_StatusConnect         = StatusConnect.Search;
                    m_Timer_Search.Interval = MS_NEW_SEARCH;
                    break;

                default:
                    break;
                }

                break;

            case StatusConnect.WaitNum:
                // ProtocolO de conexión 01, se espera el número del PC (device)
                // se espera sólo el número del PC

                m_pcNumDevice      = System.Convert.ToByte(ReadBytes(1)[0]);
                m_stationNumDevice = (byte)0;
                try
                {
                    SendBytes(new byte[] { ASCII_ACK });
                }
                catch (Exception)
                {
                    CloseConnection();
                    m_StatusConnect         = StatusConnect.Search;
                    m_Timer_Search.Interval = MS_NEW_SEARCH;
                    break;
                }

                // enviar solicitud de firmware
                DataOut = new byte[0];
                m_FrameDataOut01.EncodeFrame(DataOut, m_pcNumDevice, m_stationNumDevice, (byte)EnumCommandFrame_01_SOLD.M_FIRMWARE);
                SendBytes(m_FrameDataOut01.GetStuffedFrame());
                m_Timer_Search.Interval = MS_WAIT_FIRMWARE;
                m_StatusConnect         = StatusConnect.WaitFW;
                m_FrameDataIn01.Reset();     // inicializa buffer de entrada
                break;
            }
        }