VERSION 5.00
Object = "{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}#2.0#0"; "MSCOMCTL.OCX"
Object = "{648A5603-2C6E-101B-82B6-000000000014}#1.1#0"; "MSCOMM32.OCX"
Begin VB.Form Form1 
   Caption         =   "Tester Módulo Comunicaciones 1V1 Softel"
   ClientHeight    =   5535
   ClientLeft      =   60
   ClientTop       =   450
   ClientWidth     =   11235
   LinkTopic       =   "Form1"
   ScaleHeight     =   5535
   ScaleWidth      =   11235
   StartUpPosition =   3  'Windows Default
   Begin VB.Frame Frame1 
      Caption         =   "Consola 4"
      Height          =   4575
      Index           =   4
      Left            =   240
      TabIndex        =   14
      Top             =   720
      Visible         =   0   'False
      Width           =   10455
      Begin VB.CheckBox Check1 
         Caption         =   "¿Cargar Tester?"
         BeginProperty Font 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   255
         Index           =   4
         Left            =   240
         TabIndex        =   33
         Top             =   480
         Width           =   1695
      End
      Begin VB.ComboBox Combo2 
         Height          =   315
         Index           =   4
         ItemData        =   "TesterVendo.frx":0000
         Left            =   5520
         List            =   "TesterVendo.frx":000A
         TabIndex        =   29
         Text            =   "Seleccionar..."
         Top             =   480
         Width           =   1455
      End
      Begin VB.Timer Timer1 
         Enabled         =   0   'False
         Index           =   4
         Left            =   9840
         Top             =   360
      End
      Begin VB.ComboBox Combo1 
         Height          =   315
         Index           =   4
         ItemData        =   "TesterVendo.frx":0016
         Left            =   2880
         List            =   "TesterVendo.frx":0038
         TabIndex        =   17
         Text            =   "Seleccionar..."
         Top             =   480
         Width           =   1335
      End
      Begin VB.CommandButton Command1 
         Caption         =   "Empezar Prueba"
         Height          =   495
         Index           =   4
         Left            =   7200
         TabIndex        =   16
         Top             =   360
         Width           =   1335
      End
      Begin VB.TextBox Text1 
         Height          =   3495
         Index           =   4
         Left            =   240
         MultiLine       =   -1  'True
         ScrollBars      =   2  'Vertical
         TabIndex        =   15
         Top             =   960
         Width           =   9975
      End
      Begin MSCommLib.MSComm MSComm1 
         Index           =   4
         Left            =   9120
         Top             =   240
         _ExtentX        =   1005
         _ExtentY        =   1005
         _Version        =   393216
         DTREnable       =   -1  'True
      End
      Begin VB.Label Label3 
         Caption         =   "¿Leds ok?"
         BeginProperty Font 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   255
         Index           =   4
         Left            =   4320
         TabIndex        =   25
         Top             =   480
         Width           =   1095
      End
      Begin VB.Label Label1 
         Caption         =   "COM:"
         BeginProperty Font 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   255
         Index           =   4
         Left            =   2280
         TabIndex        =   18
         Top             =   480
         Width           =   495
      End
   End
   Begin VB.Frame Frame1 
      Caption         =   "Consola 3"
      Height          =   4575
      Index           =   3
      Left            =   240
      TabIndex        =   9
      Top             =   720
      Visible         =   0   'False
      Width           =   10455
      Begin VB.CheckBox Check1 
         Caption         =   "¿Cargar Tester?"
         BeginProperty Font 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   255
         Index           =   3
         Left            =   240
         TabIndex        =   32
         Top             =   480
         Width           =   1695
      End
      Begin VB.ComboBox Combo2 
         Height          =   315
         Index           =   3
         ItemData        =   "TesterVendo.frx":005B
         Left            =   5520
         List            =   "TesterVendo.frx":0065
         TabIndex        =   28
         Text            =   "Seleccionar..."
         Top             =   480
         Width           =   1455
      End
      Begin VB.Timer Timer1 
         Enabled         =   0   'False
         Index           =   3
         Left            =   9840
         Top             =   360
      End
      Begin VB.ComboBox Combo1 
         Height          =   315
         Index           =   3
         ItemData        =   "TesterVendo.frx":0071
         Left            =   2880
         List            =   "TesterVendo.frx":0093
         TabIndex        =   12
         Text            =   "Seleccionar..."
         Top             =   480
         Width           =   1335
      End
      Begin VB.CommandButton Command1 
         Caption         =   "Empezar Prueba"
         Height          =   495
         Index           =   3
         Left            =   7200
         TabIndex        =   11
         Top             =   360
         Width           =   1335
      End
      Begin VB.TextBox Text1 
         Height          =   3495
         Index           =   3
         Left            =   240
         MultiLine       =   -1  'True
         ScrollBars      =   2  'Vertical
         TabIndex        =   10
         Top             =   960
         Width           =   9975
      End
      Begin MSCommLib.MSComm MSComm1 
         Index           =   3
         Left            =   9120
         Top             =   240
         _ExtentX        =   1005
         _ExtentY        =   1005
         _Version        =   393216
         DTREnable       =   -1  'True
      End
      Begin VB.Label Label3 
         Caption         =   "¿Leds ok?"
         BeginProperty Font 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   255
         Index           =   3
         Left            =   4320
         TabIndex        =   24
         Top             =   480
         Width           =   1095
      End
      Begin VB.Label Label1 
         Caption         =   "COM:"
         BeginProperty Font 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   255
         Index           =   3
         Left            =   2280
         TabIndex        =   13
         Top             =   480
         Width           =   495
      End
   End
   Begin VB.Frame Frame1 
      Caption         =   "Consola 2"
      Height          =   4575
      Index           =   2
      Left            =   240
      TabIndex        =   5
      Top             =   720
      Visible         =   0   'False
      Width           =   10455
      Begin VB.CheckBox Check1 
         Caption         =   "¿Cargar Tester?"
         BeginProperty Font 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   255
         Index           =   2
         Left            =   240
         TabIndex        =   31
         Top             =   480
         Width           =   1695
      End
      Begin VB.ComboBox Combo2 
         Height          =   315
         Index           =   2
         ItemData        =   "TesterVendo.frx":00B6
         Left            =   5520
         List            =   "TesterVendo.frx":00C0
         TabIndex        =   27
         Text            =   "Seleccionar..."
         Top             =   480
         Width           =   1455
      End
      Begin VB.Timer Timer1 
         Enabled         =   0   'False
         Index           =   2
         Left            =   9840
         Top             =   240
      End
      Begin VB.TextBox Text1 
         Height          =   3495
         Index           =   2
         Left            =   240
         MultiLine       =   -1  'True
         ScrollBars      =   2  'Vertical
         TabIndex        =   20
         Top             =   960
         Width           =   9975
      End
      Begin VB.ComboBox Combo1 
         Height          =   315
         Index           =   2
         ItemData        =   "TesterVendo.frx":00CC
         Left            =   2880
         List            =   "TesterVendo.frx":00EE
         TabIndex        =   7
         Text            =   "Seleccionar..."
         Top             =   480
         Width           =   1335
      End
      Begin VB.CommandButton Command1 
         Caption         =   "Empezar Prueba"
         Height          =   495
         Index           =   2
         Left            =   7200
         TabIndex        =   6
         Top             =   360
         Width           =   1335
      End
      Begin MSCommLib.MSComm MSComm1 
         Index           =   2
         Left            =   9000
         Top             =   240
         _ExtentX        =   1005
         _ExtentY        =   1005
         _Version        =   393216
         DTREnable       =   -1  'True
      End
      Begin VB.Label Label3 
         Caption         =   "¿Leds ok?"
         BeginProperty Font 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   255
         Index           =   2
         Left            =   4320
         TabIndex        =   23
         Top             =   480
         Width           =   1095
      End
      Begin VB.Label Label1 
         Caption         =   "COM:"
         BeginProperty Font 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   255
         Index           =   2
         Left            =   2280
         TabIndex        =   8
         Top             =   480
         Width           =   495
      End
   End
   Begin VB.Frame Frame1 
      Caption         =   "Consola 1"
      Height          =   4575
      Index           =   1
      Left            =   240
      TabIndex        =   1
      Top             =   720
      Visible         =   0   'False
      Width           =   10455
      Begin VB.CheckBox Check1 
         Caption         =   "¿Cargar Tester?"
         BeginProperty Font 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   255
         Index           =   1
         Left            =   240
         TabIndex        =   30
         Top             =   480
         Width           =   1695
      End
      Begin VB.ComboBox Combo2 
         Height          =   315
         Index           =   1
         ItemData        =   "TesterVendo.frx":0111
         Left            =   5520
         List            =   "TesterVendo.frx":011B
         TabIndex        =   26
         Text            =   "Seleccionar..."
         Top             =   480
         Width           =   1455
      End
      Begin VB.Timer Timer1 
         Enabled         =   0   'False
         Index           =   1
         Left            =   9720
         Top             =   360
      End
      Begin VB.TextBox Text1 
         Height          =   3495
         Index           =   1
         Left            =   240
         MultiLine       =   -1  'True
         ScrollBars      =   2  'Vertical
         TabIndex        =   19
         Top             =   960
         Width           =   9975
      End
      Begin MSCommLib.MSComm MSComm1 
         Index           =   1
         Left            =   8880
         Top             =   240
         _ExtentX        =   1005
         _ExtentY        =   1005
         _Version        =   393216
         DTREnable       =   -1  'True
      End
      Begin VB.CommandButton Command1 
         Caption         =   "Empezar Prueba"
         Height          =   495
         Index           =   1
         Left            =   7200
         TabIndex        =   4
         Top             =   360
         Width           =   1335
      End
      Begin VB.ComboBox Combo1 
         Height          =   315
         Index           =   1
         ItemData        =   "TesterVendo.frx":0127
         Left            =   2880
         List            =   "TesterVendo.frx":0149
         TabIndex        =   3
         Text            =   "Seleccionar..."
         Top             =   480
         Width           =   1335
      End
      Begin VB.Label Label3 
         Caption         =   "¿Leds ok?"
         BeginProperty Font 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   255
         Index           =   1
         Left            =   4320
         TabIndex        =   22
         Top             =   480
         Width           =   1095
      End
      Begin VB.Label Label2 
         BeginProperty Font 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   255
         Index           =   0
         Left            =   2760
         TabIndex        =   21
         Top             =   3360
         Width           =   1095
      End
      Begin VB.Label Label1 
         Caption         =   "COM:"
         BeginProperty Font 
            Name            =   "MS Sans Serif"
            Size            =   8.25
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   255
         Index           =   1
         Left            =   2280
         TabIndex        =   2
         Top             =   480
         Width           =   495
      End
   End
   Begin MSComctlLib.TabStrip TabStrip1 
      Height          =   5175
      Left            =   120
      TabIndex        =   0
      Top             =   240
      Width           =   10935
      _ExtentX        =   19288
      _ExtentY        =   9128
      _Version        =   393216
      BeginProperty Tabs {1EFB6598-857C-11D1-B16A-00C0F0283628} 
         NumTabs         =   4
         BeginProperty Tab1 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
            Caption         =   "Consola 1"
            ImageVarType    =   2
         EndProperty
         BeginProperty Tab2 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
            Caption         =   "Consola 2"
            ImageVarType    =   2
         EndProperty
         BeginProperty Tab3 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
            Caption         =   "Consola 3"
            ImageVarType    =   2
         EndProperty
         BeginProperty Tab4 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
            Caption         =   "Consola 4"
            ImageVarType    =   2
         EndProperty
      EndProperty
   End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit
Private mintCurFrame As Integer ' Marco activo visible

'Funcion basada en llamadas al API de Windows para saber cuando un proceso ejecutado via shell a terminado
'Declaraciones del API
Private Declare Function WaitForSingleObject Lib "kernel32" _
    (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
Private Declare Function OpenProcess Lib "kernel32" (ByVal dwAccess As _
    Long, ByVal fInherit As Integer, ByVal hObjects As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" _
    (ByVal hObject As Long) As Long
'Espera un numero de milisegundos y regresa el status de un proceso. Si el argumento es omitido
'espera hasta que el proceso termine
Function WaitForProcess(taskId As Long, Optional msecs As Long = -1) As Boolean
    Dim procHandle As Long
    procHandle = OpenProcess(&H100000, True, taskId)
    Do
        WaitForProcess = WaitForSingleObject(procHandle, 50)
        DoEvents
    Loop Until WaitForProcess = False
    CloseHandle procHandle
End Function
'para hacer un dump en consola
Sub ProcDump(header As String, data As String, Index As Integer)
    Dim i As Integer
    Dim h As String
    h = ""
    For i = 1 To Len(data)
        h = h + Right("00" + Hex(Asc(Mid(data, i, 1))), 2) + " "
    Next
    Text1(Index).Text = Text1(Index).Text + header + h + vbCrLf
    Text1(Index).SelStart = Len(Text1(Index).Text)
End Sub
'activa el timer de la consola indicada
Public Sub activa_timer(tiempo As Integer, Index As Integer)
Comun.matriz(Index - 1).espera = 1
Timer1(Index).Interval = tiempo
Timer1(Index).Enabled = True
End Sub
'manda mensajes a la consola correspondiente
Public Sub escribe_consola(Index As Integer, texto As String)
Text1(Index).Text = Text1(Index).Text & texto & vbCrLf
Text1(Index).SelStart = Len(Text1(Index).Text)
End Sub
' llena la matriz de control con los valores iniciales y borra archivos con resultados en caso de existir
Sub matriz_init()
Dim contador As Integer
Dim file As String
Dim res As Integer
Dim fso As New Scripting.FileSystemObject
For contador = 1 To 4 Step 1
    res = sql.conecta_bd(contador)
    Comun.matriz(contador - 1).Index = contador
    Comun.matriz(contador - 1).Status = INICIO
    Comun.matriz(contador - 1).espera = 0
    file = App.Path & "\flash_loader\log" & contador & ".txt"
    If fso.FileExists(file) = True Then
        fso.DeleteFile (file)
    End If
Next contador
End Sub
'escribe en el puerto serial correspondiente
Sub escribe_serial(Index As Integer, trama As String)
Dim basura As String
basura = MSComm1(Index).Input
MSComm1(Index).Output = trama
End Sub
'abre el puerto serial correspondiente
Sub abre_serial(Index As Integer)
On Error GoTo OpenErr
Dim basura As String
MSComm1(Index).PortOpen = True
Call escribe_consola(Index, "Puerto Serial:Com " & Comun.matriz(Index - 1).Com & " Abierto")
Comun.matriz(Index - 1).Status = ABRE_PUERTO
basura = MSComm1(Index).Input
GoTo FIN
OpenErr:
    Call escribe_consola(Index, "Error abre_serial: " & Error$)
    Comun.matriz(Index - 1).Status = ERR
FIN:
End Sub
'carga el tester y el bootloader softel
Sub load_tester(Index As Integer)
Dim file As String
Dim Path_exec As String
Dim fso As New Scripting.FileSystemObject
Dim ts As Scripting.TextStream
Dim fil As Scripting.file
Dim pos As Long
Dim cuenta As Integer
Dim busca As Integer
On Error GoTo OpenErr
file = App.Path & "\flash_loader\log" & Index & ".txt"
Path_exec = "cmd /C " & """" & App.Path & "\flash_loader\sflash.exe " _
    & App.Path & "\flash_loader\vendoTesterFreeRTOS.bin -p 0x1000 -c " _
    & Comun.matriz(Index - 1).Com & " -l " _
    & App.Path & "\flash_loader\SFT_LM3S808_bootloader_gcc.bin" & """" _
    & " >" & App.Path & "\flash_loader\log" & Index & ".txt"
WaitForProcess Shell(Path_exec)
If fso.FileExists(file) = True Then
    Set fil = fso.GetFile(file)
    Set ts = fil.OpenAsTextStream(ForReading)
    pos = InStr(1, ts.ReadAll, "Successfully downloaded to device.", vbTextCompare)
    ts.Close
    If pos > 0 Then
        Call escribe_consola(Index, "load_tester confirmado!!!!")
        Call escribe_consola(Index, "Esperando minuto y medio a que arranque el tester...")
        Comun.matriz(Index - 1).Status = CARGA_TESTER
        cuenta = 9
        Do
            Call activa_timer(10000, Index)
            Do
                DoEvents
            Loop Until Comun.matriz(Index - 1).espera = 0
            cuenta = cuenta - 1
        Loop Until cuenta = 0
        TabStrip1.Tabs(Index).Caption = "Tester listo...."
        Combo2(Index).Enabled = True
        Command1(Index).Caption = "Empezar Prueba"
        Command1(Index).Enabled = True
    Else
        Call escribe_consola(Index, "Error load_tester:Falla carga!!!")
        Comun.matriz(Index - 1).Status = ERR
    End If
Else
    Call escribe_consola(Index, "Error load_tester: no encontré archivo log")
    Comun.matriz(Index - 1).Status = ERR
End If
GoTo FIN
OpenErr:
    Call escribe_consola(Index, "Error load_tester: " & Error$)
    Comun.matriz(Index - 1).Status = ERR
FIN:
If Comun.matriz(Index - 1).Status = ERR Then
    TabStrip1.Tabs(Index).Caption = "FALLO"
    Combo1(Index).Enabled = True
    Combo2(Index).Enabled = False
    Command1(Index).Enabled = True
    Check1(Index).Enabled = True
End If
End Sub
'carga la aplicación final
Sub load_app(Index As Integer)
Dim file As String
Dim Path_exec As String
Dim fso As New Scripting.FileSystemObject
Dim ts As Scripting.TextStream
Dim fil As Scripting.file
Dim pos As Long
Dim cuenta As Integer
Dim busca As Integer
On Error GoTo OpenErr
file = App.Path & "\flash_loader\log" & Index & ".txt"
Path_exec = "cmd /C " & """" & App.Path & "\flash_loader\sflash.exe " _
    & App.Path & "\flash_loader\vendo_OK.bin -p 0x1000 -c " _
    & Comun.matriz(Index - 1).Com & " -d -b 9600 " _
    & """" & " >" & App.Path & "\flash_loader\log" & Index & ".txt"
WaitForProcess Shell(Path_exec)
If fso.FileExists(file) = True Then
    Set fil = fso.GetFile(file)
    Set ts = fil.OpenAsTextStream(ForReading)
    pos = InStr(1, ts.ReadAll, "Successfully downloaded to device.", vbTextCompare)
    ts.Close
    If pos > 0 Then
        Call escribe_consola(Index, "load_app confirmado!!!!")
        Call escribe_consola(Index, "Esperando un minuto a que arranque la aplicación...")
        Comun.matriz(Index - 1).Status = FIN_OK
        cuenta = 6
        Do
            Call activa_timer(10000, Index)
            Do
                DoEvents
            Loop Until Comun.matriz(Index - 1).espera = 0
            cuenta = cuenta - 1
        Loop Until cuenta = 0
    Else
        Call escribe_consola(Index, "Error load_app:Falla carga!!!")
        Comun.matriz(Index - 1).Status = ERR
    End If
Else
    Call escribe_consola(Index, "Error load_app: no encontré archivo log")
    Comun.matriz(Index - 1).Status = ERR
End If
GoTo FIN
OpenErr:
    Call escribe_consola(Index, "Error load_tester: " & Error$)
    Comun.matriz(Index - 1).Status = ERR
FIN:
End Sub
Function valida_trama(Buffer As String, lon As Integer) As Integer
valida_trama = 0
If Asc(Mid(Buffer, 1, 1)) = 2 Then
    If Asc(Mid(Buffer, lon, 1)) = 3 Then
        valida_trama = 1
    End If
End If
End Function
Public Function CHex(sHex As String) As Long
    Dim iNegative As Integer, sPrefixH As String
    
    On Error Resume Next
    iNegative = CBool(Left$(sHex, 1) = "-")
    sPrefixH = IIf(InStr(1, sHex, "H", vbTextCompare), "", "H")
    
    If iNegative Then
        'Negative number
        If Mid$(sHex, 2, 1) = "&" Then
            CHex = CLng("&" & sPrefixH & Mid$(sHex, 3)) * iNegative
        Else
            'Append the ampersand to enable CLng to convert the value
            CHex = CLng("&" & sPrefixH & Mid$(sHex, 2)) * iNegative
        End If
    Else
        'Positive number
        If Left$(sHex, 1) = "&" Then
            CHex = CLng("&" & sPrefixH & Mid$(sHex, 2))
        Else
            'Append the ampersand to enable CLng to convert the value
            sPrefixH = "&" & sPrefixH & sHex
            CHex = CLng(sPrefixH)
        End If
    End If
End Function


Function analiza_trama(Buffer As String, lon As Integer, Index As Integer) As Integer
Dim valor As Integer
Dim compara As Integer
Dim falla As Integer
Dim serie As String
Dim compara1 As Long
On Error GoTo OpenErr
falla = 0
Select Case Comun.matriz(Index - 1).Status
    Case ABRE_PUERTO
       If Asc(Mid(Buffer, 3, 1)) = 160 Then
            valor = Asc(Mid(Buffer, 4, 1))
            compara = valor And 1
            If compara = 1 Then
                Comun.matriz(Index - 1).registro = 1
            Else
                falla = 1
                Comun.matriz(Index - 1).registro = 0
            End If
            compara = valor And 2
            If compara = 2 Then
                Comun.matriz(Index - 1).ppp = 1
            Else
                falla = 1
                Comun.matriz(Index - 1).ppp = 0
            End If
            compara = valor And 4
            If compara = 4 Then
                Comun.matriz(Index - 1).attach = 1
            Else
                falla = 1
                Comun.matriz(Index - 1).attach = 0
            End If
            compara = valor And 8
            If compara = 8 Then
                Comun.matriz(Index - 1).rssi = 1
            Else
                falla = 1
                Comun.matriz(Index - 1).rssi = 0
            End If
            compara = valor And 16
            If compara = 16 Then
                Comun.matriz(Index - 1).simcom = 1
            Else
                Comun.matriz(Index - 1).simcom = 0
            End If
            compara = valor And 32
            If compara = 32 Then
                Comun.matriz(Index - 1).wavecom = 1
            Else
                Comun.matriz(Index - 1).wavecom = 0
            End If
            compara = valor And 64
            If compara = 64 Then
                Comun.matriz(Index - 1).sim = 1
            Else
                falla = 1
                Comun.matriz(Index - 1).sim = 0
            End If
            compara = valor And 128
            If compara = 128 Then
                Comun.matriz(Index - 1).comandos_at = 1
            Else
                falla = 1
                Comun.matriz(Index - 1).comandos_at = 0
            End If
            valor = Asc(Mid(Buffer, 4, 1))
            compara = valor And 128
            If compara = 128 Then
                Comun.matriz(Index - 1).eeprom = 1
            Else
                falla = 1
                Comun.matriz(Index - 1).eeprom = 0
            End If
            Call escribe_consola(Index, "Resultados pruebas:")
            Call escribe_consola(Index, "Comandos AT: " & Comun.matriz(Index - 1).comandos_at)
            Call escribe_consola(Index, "SIM: " & Comun.matriz(Index - 1).sim)
            Call escribe_consola(Index, "Modem Wavecom: " & Comun.matriz(Index - 1).wavecom)
            Call escribe_consola(Index, "Modem Simcom: " & Comun.matriz(Index - 1).simcom)
            Call escribe_consola(Index, "RSSI: " & Comun.matriz(Index - 1).rssi)
            Call escribe_consola(Index, "Attach: " & Comun.matriz(Index - 1).attach)
            Call escribe_consola(Index, "PPP: " & Comun.matriz(Index - 1).ppp)
            Call escribe_consola(Index, "EEPROM: " & Comun.matriz(Index - 1).eeprom)
            Call escribe_consola(Index, "Registro: " & Comun.matriz(Index - 1).registro)
            If Comun.matriz(Index - 1).wavecom = 0 And Comun.matriz(Index - 1).simcom = 0 Then
                Call escribe_consola(Index, "Error corre tester: La tarjeta no pudo identificar modem!!!")
                falla = 1
            End If
            If falla = 1 Then
                Call escribe_consola(Index, "Alguna de las pruebas falló..el equipo no será registrado en la BD")
                Comun.matriz(Index - 1).Status = ERR
            Else
                Comun.matriz(Index - 1).Status = PRUEBAS_TESTER
            End If
        Else
            Call escribe_consola(Index, "Error corre_tester: esperaba comando A0")
            Comun.matriz(Index - 1).Status = ERR
       End If
    Case PRUEBAS_TESTER
        If Asc(Mid(Buffer, 3, 1)) = 176 Then
            Comun.matriz(Index - 1).Status = MANDA_SERIE
        Else
            Call escribe_consola(Index, "Error corre_serie: esperaba comando B0")
            Comun.matriz(Index - 1).Status = ERR
       End If
    Case MANDA_SERIE
       If Asc(Mid(Buffer, 3, 1)) = 192 Then
            compara1 = (Asc(Mid(Buffer, 6, 1)) * 65536) + (Asc(Mid(Buffer, 7, 1)) * 256) + Asc(Mid(Buffer, 8, 1))
            serie = Asc(Mid(Buffer, 4, 1)) & Asc(Mid(Buffer, 5, 1)) & compara1
            Select Case 10 - Len(serie)
            Case 7
                serie = Mid(serie, 1, 2) & "0000000" & Mid(serie, 3, 1)
            Case 6
                serie = Mid(serie, 1, 2) & "000000" & Mid(serie, 3, 2)
            Case 5
                serie = Mid(serie, 1, 2) & "00000" & Mid(serie, 3, 3)
            Case 4
                serie = Mid(serie, 1, 2) & "0000" & Mid(serie, 3, 4)
            Case 3
                serie = Mid(serie, 1, 2) & "000" & Mid(serie, 3, 5)
            Case 2
                serie = Mid(serie, 1, 2) & "00" & Mid(serie, 3, 6)
            Case 1
                serie = Mid(serie, 1, 2) & "0" & Mid(serie, 3, 7)
            End Select
            If InStr(1, serie, Comun.matriz(Index - 1).numero_serie) <> 0 Then
                Comun.matriz(Index - 1).imei = Mid(Buffer, 10, 15)
                Call escribe_consola(Index, "IMEI recibido: " & Comun.matriz(Index - 1).imei)
                Comun.matriz(Index - 1).Status = CONFIRMA_SERIE
            Else
                Call escribe_consola(Index, "Error corre_id:no recibo el número de serie esperado")
                Comun.matriz(Index - 1).Status = ERR
            End If
        Else
            Call escribe_consola(Index, "Error corre_id: esperaba comando C0")
            Comun.matriz(Index - 1).Status = ERR
            
       End If
    Case MANDA_RESET
    If Asc(Mid(Buffer, 3, 1)) = 208 Then
            Comun.matriz(Index - 1).Status = CARGA_APLICACION
        Else
            Call escribe_consola(Index, "Error corre_reset: esperaba comando D0")
            Comun.matriz(Index - 1).Status = ERR
       End If
End Select
GoTo FIN
OpenErr:
    Call escribe_consola(Index, "Error corre_tester: " & Error$)
    Comun.matriz(Index - 1).Status = ERR
FIN:
End Function
'lanza las pruebas del auto tester en la tarjeta
Private Sub corre_test(Index As Integer)
Dim trama As String
Dim res As Integer
Dim cuenta As Integer
On Error GoTo OpenErr
trama = Chr(2) & Chr(2) & Chr(160) & Chr(MIN_RSSI) & Chr(3)
Call ProcDump("Envio trama de arranque test: ", trama, Index)
Call escribe_serial(Index, trama)
Call escribe_consola(Index, "corre_test:Esperando respuesta...")
cuenta = 0
Do
    Call activa_timer(30000, Index)
    Do
        DoEvents
    Loop Until Comun.matriz(Index - 1).espera = 0
    If Comun.matriz(Index - 1).len_rx = 6 Then
        cuenta = 10
    End If
    cuenta = cuenta + 1
Loop Until cuenta > 9
If Comun.matriz(Index - 1).len_rx <> 6 Then
    Call escribe_consola(Index, "Error corre_test: No hubo respuesta esperada de la tarjeta!!!")
    Comun.matriz(Index - 1).Status = ERR
Else
    Call ProcDump("Trama recibida: ", Comun.matriz(Index - 1).buffer_rx, Index)
    res = valida_trama(Comun.matriz(Index - 1).buffer_rx, Comun.matriz(Index - 1).len_rx)
    If res <> 1 Then
        Call escribe_consola(Index, "Error corre_test: No hubo respuesta valida de la tarjeta!!!")
        Comun.matriz(Index - 1).Status = ERR
    Else
        Call escribe_consola(Index, "Paquete válido!!!!")
        Call analiza_trama(Comun.matriz(Index - 1).buffer_rx, Comun.matriz(Index - 1).len_rx, Index)
    End If
End If
GoTo FIN
OpenErr:
    Call escribe_consola(Index, "Error corre_test: " & Error$)
    Comun.matriz(Index - 1).Status = ERR
FIN:
End Sub
'le manda el numero de serie a utilizar al equipo
Sub corre_serie(Index As Integer)
Dim trama As String
Dim res As Long
Dim serie1 As Integer
Dim serie2 As Integer
Dim serie3 As Integer
Dim serie4 As Integer
Dim serie5 As Integer
On Error GoTo OpenErr
res = Mid(Comun.matriz(Index - 1).numero_serie, 3, 8)
serie1 = Mid(Comun.matriz(Index - 1).numero_serie, 1, 1)
serie2 = Mid(Comun.matriz(Index - 1).numero_serie, 2, 1)
If res > 65535 Then
    serie3 = (res / 65536) And 255
    serie4 = (res / 256) And 255
    serie5 = res And 255
ElseIf res > 255 Then
    serie3 = 0
    serie4 = (res / 256) And 255
    serie5 = res And 255
Else
    serie3 = 0
    serie4 = 0
    serie5 = res And 255
End If
Call escribe_consola(Index, "Número de serie a mandar: " & Comun.matriz(Index - 1).numero_serie)
trama = Chr(2) & Chr(6) & Chr(176) & Chr(serie1) & Chr(serie2) & Chr(serie3) & Chr(serie4) & Chr(serie5) & Chr(3)
Call ProcDump("Envio trama de numero de serie: ", trama, Index)
Call escribe_serial(Index, trama)
Call escribe_consola(Index, "corre_serie:Esperando respuesta...")
Call activa_timer(4000, Index)
Do
    DoEvents
Loop Until Comun.matriz(Index - 1).espera = 0
If Comun.matriz(Index - 1).len_rx <> 4 Then
    Call escribe_consola(Index, "Error corre_serie: No hubo respuesta esperada de la tarjeta!!!")
    Comun.matriz(Index - 1).Status = ERR
Else
    Call ProcDump("Trama recibida: ", Comun.matriz(Index - 1).buffer_rx, Index)
    res = valida_trama(Comun.matriz(Index - 1).buffer_rx, Comun.matriz(Index - 1).len_rx)
    If res <> 1 Then
        Call escribe_consola(Index, "Error corre_serie: No hubo respuesta valida de la tarjeta!!!")
        Comun.matriz(Index - 1).Status = ERR
    Else
        Call escribe_consola(Index, "Paquete válido!!!!")
        Call analiza_trama(Comun.matriz(Index - 1).buffer_rx, Comun.matriz(Index - 1).len_rx, Index)
        End If
End If
GoTo FIN
OpenErr:
    Call escribe_consola(Index, "Error load_tester: " & Error$)
    Comun.matriz(Index - 1).Status = ERR
FIN:
End Sub
'confirma numero de serie y obtiene imei
Sub corre_id(Index As Integer)
Dim trama As String
Dim res As Integer
On Error GoTo OpenErr
trama = Chr(2) & Chr(1) & Chr(192) & Chr(3)
Call ProcDump("Envio trama de confirmación id: ", trama, Index)
Call escribe_serial(Index, trama)
Call escribe_consola(Index, "corre_id:Esperando respuesta...")
Call activa_timer(4000, Index)
Do
    DoEvents
Loop Until Comun.matriz(Index - 1).espera = 0
If Comun.matriz(Index - 1).len_rx <> 25 Then
    Call escribe_consola(Index, "Error corre_id: No hubo respuesta esperada de la tarjeta!!!")
    Comun.matriz(Index - 1).Status = ERR
Else
    Call ProcDump("Trama recibida: ", Comun.matriz(Index - 1).buffer_rx, Index)
    res = valida_trama(Comun.matriz(Index - 1).buffer_rx, Comun.matriz(Index - 1).len_rx)
    If res <> 1 Then
        Call escribe_consola(Index, "Error corre_id: No hubo respuesta valida de la tarjeta!!!")
        Comun.matriz(Index - 1).Status = ERR
    Else
        Call escribe_consola(Index, "Paquete válido!!!!")
        Call analiza_trama(Comun.matriz(Index - 1).buffer_rx, Comun.matriz(Index - 1).len_rx, Index)
        End If
End If
GoTo FIN
OpenErr:
    Call escribe_consola(Index, "Error corre_id: " & Error$)
    Comun.matriz(Index - 1).Status = ERR
FIN:
End Sub
'manda reset al equipo
Sub corre_reset(Index As Integer)
Dim trama As String
Dim res As Integer
On Error GoTo OpenErr
trama = Chr(2) & Chr(1) & Chr(208) & Chr(3)
Call ProcDump("Envio trama de solicitud reset: ", trama, Index)
Call escribe_serial(Index, trama)
Call escribe_consola(Index, "corre_reset:Esperando respuesta...")
Call activa_timer(5000, Index)
Do
    DoEvents
Loop Until Comun.matriz(Index - 1).espera = 0
If Comun.matriz(Index - 1).len_rx < 4 Then
    Call escribe_consola(Index, "Error corre_reset: No hubo respuesta esperada de la tarjeta!!!")
    Comun.matriz(Index - 1).Status = ERR
Else
    If Comun.matriz(Index - 1).len_rx > 4 Then
        Comun.matriz(Index - 1).len_rx = 4
    End If
    Call ProcDump("Trama recibida: ", Comun.matriz(Index - 1).buffer_rx, Index)
    res = valida_trama(Comun.matriz(Index - 1).buffer_rx, Comun.matriz(Index - 1).len_rx)
    If res <> 1 Then
        Call escribe_consola(Index, "Error corre_reset: No hubo respuesta valida de la tarjeta!!!")
        Comun.matriz(Index - 1).Status = ERR
    Else
        Call escribe_consola(Index, "Paquete válido!!!!")
        Call analiza_trama(Comun.matriz(Index - 1).buffer_rx, Comun.matriz(Index - 1).len_rx, Index)
        End If
End If
GoTo FIN
OpenErr:
    Call escribe_consola(Index, "Error corre_reset: " & Error$)
    Comun.matriz(Index - 1).Status = ERR
FIN:
End Sub
'Controla el check box
Private Sub Check1_Click(Index As Integer)
If Check1(Index).Value = 1 Then
    Command1(Index).Caption = "Cargar Tester"
    Combo2(Index).Enabled = False
    Combo1(Index).Enabled = True
    TabStrip1.Tabs(Index).Caption = "Consola " & Index
    Comun.matriz(Index - 1).Status = INICIO
Else
    TabStrip1.Tabs(Index).Caption = "Tester listo...."
    Command1(Index).Caption = "Empezar Prueba"
    Combo2(Index).Enabled = True
    Combo1(Index).Enabled = True
    Comun.matriz(Index - 1).Status = CARGA_TESTER
End If
End Sub

'rutina que dispara la prueba
Private Sub Command1_Click(Index As Integer)
Dim fso As New Scripting.FileSystemObject
Dim file As String
Dim res As Integer
On Error GoTo OpenErr
Check1(Index).Enabled = False
If Command1(Index).Caption = "Cargar Tester" Then
    If Combo1(Index).Text = "Seleccionar..." Then
        Call escribe_consola(Index, "Faltan datos por capturar!!!!")
        Check1(Index).Enabled = True
    Else
        If Comun.matriz(Index - 1).Status <> INICIO Then
            Comun.matriz(Index - 1).Status = INICIO
            Comun.matriz(Index - 1).espera = 0
            file = App.Path & "\flash_loader\log" & Index & ".txt"
            If fso.FileExists(file) = True Then
                fso.DeleteFile (file)
            End If
        End If
        If Comun.matriz(Index - 1).cn.State = 0 Then
            Call sql.conecta_bd(Index)
        End If
        If Comun.matriz(Index - 1).cn.State = 0 Then
            Call escribe_consola(Index, "No tengo conexion a la bd!!!")
            Check1(Index).Enabled = True
        Else
            Text1(Index).Text = ""
            Command1(Index).Enabled = False
            MSComm1(Index).CommPort = Combo1(Index).Text
            Comun.matriz(Index - 1).Com = Combo1(Index).Text
            TabStrip1.Tabs(Index).Caption = "Cargando tester..."
            Combo1(Index).Enabled = False
            Select Case Comun.matriz(Index - 1).Status
                    Case INICIO
                        Call escribe_consola(Index, "load_tester: Esperando por carga de tester....")
                        Call activa_timer(3000, Index)
                        Do
                            DoEvents
                        Loop Until Comun.matriz(Index - 1).espera = 0
                        Call load_tester(Index)
            End Select
            End If
    End If
Else
    If Combo1(Index).Text = "Seleccionar..." Or Combo2(Index).Text = "Seleccionar..." Then
        Call escribe_consola(Index, "Faltan datos por capturar!!!!")
        Check1(Index).Enabled = True
    Else
        If Comun.matriz(Index - 1).cn.State = 0 Then
            Call sql.conecta_bd(Index)
        End If
        If Comun.matriz(Index - 1).cn.State = 0 Then
            Call escribe_consola(Index, "No tengo conexion a la bd!!!")
            Check1(Index).Enabled = True
        Else
            If Combo2(Index).Text = "No" Then
                Call escribe_consola(Index, "La prueba no puede realizarse debido a fallo en los leds!!!")
                Comun.matriz(Index - 1).Status = ERR
            Else
                Comun.matriz(Index - 1).leds = 1
            End If
            MSComm1(Index).CommPort = Combo1(Index).Text
            Comun.matriz(Index - 1).Com = Combo1(Index).Text
            Command1(Index).Enabled = False
            TabStrip1.Tabs(Index).Caption = "Probando..."
            Combo2(Index).Enabled = False
            Text1(Index).Text = ""
            Do While Comun.matriz(Index - 1).Status < ERR
                Select Case Comun.matriz(Index - 1).Status
                    Case INICIO
                        Call escribe_consola(Index, "load_tester: Esperando por carga de tester....")
                        Call activa_timer(3000, Index)
                        Do
                            DoEvents
                        Loop Until Comun.matriz(Index - 1).espera = 0
                        Call load_tester(Index)
                    Case CARGA_TESTER
                        Call abre_serial(Index)
                    Case ABRE_PUERTO
                        Call corre_test(Index)
                    Case PRUEBAS_TESTER
                        Call sql.asigna_serie(Index)
                        Call corre_serie(Index)
                    Case MANDA_SERIE
                        Call corre_id(Index)
                    Case CONFIRMA_SERIE
                        res = sql.guarda_imei(Index)
                        If res = 1 Then
                            res = sql.guarda_prueba(Index)
                            If res = 1 Then
                                Comun.matriz(Index - 1).Status = MANDA_RESET
                            Else
                               Comun.matriz(Index - 1).Status = ERR
                            End If
                        Else
                            Comun.matriz(Index - 1).Status = ERR
                        End If
                        If Comun.matriz(Index - 1).Status = ERR Then
                            Call escribe_consola(Index, "No pude guardar los datos en la bd!!!!")
                        End If
                    Case MANDA_RESET
                        Call corre_reset(Index)
                    Case CARGA_APLICACION
                        MSComm1(Index).PortOpen = False
                        file = App.Path & "\flash_loader\log" & Index & ".txt"
                        If fso.FileExists(file) = True Then
                            fso.DeleteFile (file)
                        End If
                        Call escribe_consola(Index, "load_app: Esperando por carga de aplicacion....")
                        TabStrip1.Tabs(Index).Caption = "Cargando Ap..."
                        Call activa_timer(3000, Index)
                        Do
                            DoEvents
                        Loop Until Comun.matriz(Index - 1).espera = 0
                        Call load_app(Index)
                End Select
            Loop
            If Comun.matriz(Index - 1).Status = ERR Then
                Call escribe_consola(Index, "equipo reprobado!!!")
                TabStrip1.Tabs(Index).Caption = "FALLO"
            Else
                Call escribe_consola(Index, "equipo aprobado y almacenado en BD!!!")
                TabStrip1.Tabs(Index).Caption = "OK"
            End If
            If Check1(Index).Value = 1 Then
                Command1(Index).Caption = "Cargar Tester"
            End If
            If MSComm1(Index).PortOpen = True Then
                MSComm1(Index).PortOpen = False
            End If
            Combo1(Index).Enabled = True
            Combo2(Index).Text = "Seleccionar..."
            Combo2(Index).Enabled = False
            Command1(Index).Enabled = True
            Check1(Index).Enabled = True
        End If
    End If
End If
GoTo FIN
OpenErr:
    Call escribe_consola(Index, "Error Command Click: " & Error$)
FIN:
End Sub
'carga la forma
Private Sub Form_Load()
Call matriz_init
mintCurFrame = TabStrip1.SelectedItem.Index
Frame1(mintCurFrame).Visible = True
Command1(1).Caption = "Cargar Tester"
Command1(2).Caption = "Cargar Tester"
Command1(3).Caption = "Cargar Tester"
Command1(4).Caption = "Cargar Tester"
Combo2(1).Enabled = False
Combo2(2).Enabled = False
Combo2(3).Enabled = False
Combo2(4).Enabled = False
Check1(1).Value = 1
Check1(2).Value = 1
Check1(3).Value = 1
Check1(4).Value = 1
End Sub

'permite seleccionar el tab de la consola activa
Private Sub Tabstrip1_Click()
   If TabStrip1.SelectedItem.Index = mintCurFrame Then
        Exit Sub ' No necesita cambiar el marco.
   End If
   ' Oculte el marco antiguo y muestre el nuevo.
   Frame1(TabStrip1.SelectedItem.Index).Visible = True
   Frame1(mintCurFrame).Visible = False
   ' Establece mintCurFrame al nuevo valor.
   mintCurFrame = TabStrip1.SelectedItem.Index
End Sub
'handler para los timers
Private Sub Timer1_Timer(Index As Integer)
Timer1(Index).Enabled = False
Comun.matriz(Index - 1).espera = 0
If MSComm1(Index).PortOpen = True Then
    Comun.matriz(Index - 1).len_rx = MSComm1(Index).InBufferCount
    Comun.matriz(Index - 1).buffer_rx = MSComm1(Index).Input
End If
End Sub
