Club Delphi  
    FTP   CCD     Buscar   Trucos   Trabajo   Foros

Retroceder   Foros Club Delphi > Principal > OOP
Registrarse FAQ Miembros Calendario Guía de estilo Temas de Hoy

Grupo de Teaming del ClubDelphi

Respuesta
 
Herramientas Buscar en Tema Desplegado
  #1  
Antiguo 04-11-2021
CrazySoft CrazySoft is offline
Miembro
 
Registrado: abr 2005
Posts: 96
Poder: 20
CrazySoft Va por buen camino
Ayuda a implementar DLL

Buen día y gracias por la ayuda,

no tengo mucha experiencia con el uso de DLL y tengo problemas con la implementacion de la libreria LibraryPOS.dll que esta en VB, las funciones estan dentro de una clase y no se como importarlas e usarlas en Delphi, todas las llamadas a funciones de la librería DLL se comentán con “//-- dll ---”.

Código:
Configuración inicial
1. Crear una instancia de la clase _POSLibrary
Dim _pos As New _POSLibrary._LibraryPOS
2. Crear una instancia de la clase SerialPort
Dim _portPOS As New IO.Ports.SerialPort
3. Conexión al puerto serial e inicio de conexión
En éste ejemplo se muestra la funcionalidad asignada a un botón InicioPago que es el que el
cajero o cliente presionará para proceder con el pago con tarjeta
• La función validarMonto() valida que el formato del monto total a pagar sea
correcto. Esta función es opcional si la validación se realiza en otra instancia.
• La instrucción foreach recorre los puertos COM disponibles y para cada uno, prueba
conectarse. En el caso de una conexión exitosa, se guarda el puerto conectado en
_portPOS.
• Una vez realizada la conexión, se inicializa un Event Handler para recibir los datos
recibidos del POS, en la variable _portPOS.DataReceived, y se asigna el handler a la
función PortCOM_DataReceived.
• Luego se inicia el PASO 1, Flujo 1. “Transacción Solicitud de conexión”, llamando a la
función ReqConnectionToPOS_Local();
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles btnPagarChip.Click
If (validarDatosTransac() And validarMonto()) Then
_pagoChip = True
Dim isConnected As Boolean = False
If (Not _portPOS.IsOpen) Then
ActivePorts = _pos._ListActivePorts_POS() ' -- dll --
For Each puerto As String In ActivePorts
_NumPort = puerto
Next
isConnected = _pos._OpenPort_POS(_NumPort) ' -- dll --
If (isConnected) Then
_status = "0"
_portPOS = _pos.PortUSB
AddHandler _portPOS.DataReceived, AddressOf PortCOM_DataReceived
End If
Else
isConnected = True
_status = "0"
End If
If (Not isConnected) Then
MsgBox("No hay conexion al puerto COM.")
Return
End If
ReqConnectionToPOS_Local()
End If

Flujo entre Caja/Kiosco y el POS
A partir de este momento se debe controlar los mensajes de respuesta del POS, de acuerdo
al Flujo Transaccional y los 4 PASOS descritos.
La función que controla la recepción de datos seriales es PortCOM_DataReceived.
• Si los datos corresponden a una respuesta de acuerdo al flujo, se envía la trama
recibida a las funciones asociadas al flujo en curso. Por ejemplo, la función
FlujoPagoChip(srtReply) se encarga de controlar el estado o PASO para una venta
con tarjeta con Chip.
Flujo Transacción de venta con Chip
La función ContinueFlow se encarga de controlar los estados o PASOS en los que se
encuentra el flujo transaccional para una venta tradicional con tarjeta Chip. Para esto, se
maneja una estructura tipo case, donde la variable _status guarda el estado actual del flujo.
Private Sub PortCOM_DataReceived(sender As Object, e As SerialDataReceivedEventArgs)
Dim strReply As String
Dim sp As SerialPort = CType(sender, SerialPort)
Dim bytes As Integer = sp.BytesToRead
Dim comBuffer As Byte() = New Byte(bytes - 1) {}
sp.Read(comBuffer, 0, bytes)
strReply = _pos._ByteArrayToString(comBuffer)
Console.Write("POS:")
Console.WriteLine(strReply)
Log("POS: " + strReply)
If (Not String.IsNullOrEmpty(strReply)) Then
If (_pagoChip) Then
FlujoPagoChip(strReply)
ElseIf (_pagoCtl) Then
FlujoPagoCTL(strReply)
ElseIf (_cierrePOS) Then
FlujoCierre(strReply)
ElseIf (_anularTrans) Then
FlujoAnular(strReply)
ElseIf (_inicializarPOS) Then
FlujoInicializar(strReply)
End If
End If
 End Sub
este es el codigo en VB

Código:
Imports System.IO.Ports

Public Class DemoCajasPOS

    Dim total As Double = 0.00
    Dim montoBOB As Integer
    Dim _pos As New _POSLibrary._LibraryPOS
    Dim _portPOS As New IO.Ports.SerialPort
    Dim ActivePorts As New List(Of String)
    Dim _NumPort As String

    Dim _pagoChip As Boolean = False
    Dim _pagoCtl As Boolean = False
    Dim _cierrePOS As Boolean = False
    Dim _anularTrans As Boolean = False
    Dim _inicializarPOS As Boolean = False

    Dim _status As String
    Dim _1isACK As Boolean
    Dim _2isACK As Boolean
    Dim _3isACK As Boolean
    Dim _wait3isACK As Boolean

    Public Sub New()

        ' Esta llamada es exigida por el diseñador.
        InitializeComponent()
        Productos.Rows.Clear()
        Control.CheckForIllegalCrossThreadCalls = False
        ' Agregue cualquier inicialización después de la llamada a InitializeComponent().

    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles btnPagarChip.Click

        If (validarDatosTransac() And validarMonto()) Then
            _pagoChip = True
            Dim isConnected As Boolean = False
            If (Not _portPOS.IsOpen) Then
                ActivePorts = _pos._ListActivePorts_POS()           ' -- dll --
                For Each puerto As String In ActivePorts
                    _NumPort = puerto
                Next
                isConnected = _pos._OpenPort_POS(_NumPort)          ' -- dll --
                If (isConnected) Then
                    _status = "0"
                    _portPOS = _pos.PortUSB
                    AddHandler _portPOS.DataReceived, AddressOf PortCOM_DataReceived
                End If
            Else
                isConnected = True
                _status = "0"
            End If
            If (Not isConnected) Then
                MsgBox("No hay conexion al puerto COM.")
                Return
            End If
            ReqConnectionToPOS_Local()
        End If
    End Sub

    Private Sub btnPagarCtl_Click(sender As Object, e As EventArgs) Handles btnPagarCtl.Click

        If (validarDatosTransac() And validarMonto()) Then
            _pagoCtl = True
            Dim isConnected As Boolean = False
            If (Not _portPOS.IsOpen) Then
                ActivePorts = _pos._ListActivePorts_POS()           ' -- dll --
                For Each puerto As String In ActivePorts
                    _NumPort = puerto
                Next
                isConnected = _pos._OpenPort_POS(_NumPort)          ' -- dll --
                If (isConnected) Then
                    _status = "0"
                    _portPOS = _pos.PortUSB
                    AddHandler _portPOS.DataReceived, AddressOf PortCOM_DataReceived
                End If
            Else
                isConnected = True
                _status = "0"
            End If
            If (Not isConnected) Then
                MsgBox("No hay conexion al puerto COM.")
                Return
            End If
            ReqConnectionCTLToPOS_Local()
        End If
    End Sub

    Private Sub btnCierre_Click(sender As Object, e As EventArgs) Handles btnCierre.Click
        _cierrePOS = True
        Dim isConnected As Boolean = False
        If (Not _portPOS.IsOpen) Then
            ActivePorts = _pos._ListActivePorts_POS()           ' -- dll --
            For Each puerto As String In ActivePorts
                _NumPort = puerto
            Next
            isConnected = _pos._OpenPort_POS(_NumPort)          ' -- dll --
            If (isConnected) Then
                _status = "0"
                _portPOS = _pos.PortUSB
                AddHandler _portPOS.DataReceived, AddressOf PortCOM_DataReceived
            End If
        Else
            isConnected = True
            _status = "0"
        End If
        If (Not isConnected) Then
            MsgBox("No hay conexion al puerto COM.")
            Return
        End If
        ReqCierreToPOS_Local()
    End Sub

    Private Sub btnAnular_Click(sender As Object, e As EventArgs) Handles btnAnular.Click
        If (validarAnulacion()) Then
            _anularTrans = True
            Dim isConnected As Boolean = False
            If (Not _portPOS.IsOpen) Then
                ActivePorts = _pos._ListActivePorts_POS()           ' -- dll --
                For Each puerto As String In ActivePorts
                    _NumPort = puerto
                Next
                isConnected = _pos._OpenPort_POS(_NumPort)          ' -- dll --
                If (isConnected) Then
                    _status = "0"
                    _portPOS = _pos.PortUSB
                    AddHandler _portPOS.DataReceived, AddressOf PortCOM_DataReceived
                End If
            Else
                isConnected = True
                _status = "0"
            End If
            If (Not isConnected) Then
                MsgBox("No hay conexion al puerto COM.")
                Return
            End If
            ReqAnulacionToPOS_Local()
        End If
    End Sub

    Private Sub btnInicializar_Click(sender As Object, e As EventArgs) Handles btnInicializar.Click
        _inicializarPOS = True
        Dim isConnected As Boolean = False
        If (Not _portPOS.IsOpen) Then
            ActivePorts = _pos._ListActivePorts_POS()           ' -- dll --
            For Each puerto As String In ActivePorts
                _NumPort = puerto
            Next
            isConnected = _pos._OpenPort_POS(_NumPort)          ' -- dll --
            If (isConnected) Then
                _status = "0"
                _portPOS = _pos.PortUSB
                AddHandler _portPOS.DataReceived, AddressOf PortCOM_DataReceived
            End If
        Else
            isConnected = True
            _status = "0"
        End If
        If (Not isConnected) Then
            MsgBox("No hay conexion al puerto COM.")
            Return
        End If
        ReqInicializarToPOS_Local()
    End Sub

    Private Sub PortCOM_DataReceived(sender As Object, e As SerialDataReceivedEventArgs)
        Dim strReply As String
        Dim sp As SerialPort = CType(sender, SerialPort)
        Dim bytes As Integer = sp.BytesToRead
        Dim comBuffer As Byte() = New Byte(bytes - 1) {}
        sp.Read(comBuffer, 0, bytes)
        strReply = _pos._ByteArrayToString(comBuffer)
        Console.Write("POS:")
        Console.WriteLine(strReply)
        Log("POS: " + strReply)

        If (Not String.IsNullOrEmpty(strReply)) Then
            If (_pagoChip) Then
                FlujoPagoChip(strReply)
            ElseIf (_pagoCtl) Then
                FlujoPagoCTL(strReply)
            ElseIf (_cierrePOS) Then
                FlujoCierre(strReply)
            ElseIf (_anularTrans) Then
                FlujoAnular(strReply)
            ElseIf (_inicializarPOS) Then
                FlujoInicializar(strReply)
            End If
        End If
    End Sub

    Private Sub btnCafe_Click(sender As Object, e As EventArgs) Handles btnCafe.Click
        Productos.Rows.Insert(0, "Cafe", "12.50", "1", "12.50")
        total = total + Val("12.50")
        txtMonto.Text = total.ToString("00.00")
    End Sub

    Private Sub btnLatte_Click(sender As Object, e As EventArgs) Handles btnLatte.Click
        Productos.Rows.Insert(0, "Latte", "14.50", "1", "14.50")
        total = total + Val("14.50")
        txtMonto.Text = total.ToString("00.00")
    End Sub

    Private Sub btnChocolate_Click(sender As Object, e As EventArgs) Handles btnChocolate.Click
        Productos.Rows.Insert(0, "Chocolate", "13.50", "1", "13.50")
        total = total + Val("13.50")
        txtMonto.Text = total.ToString("00.00")
    End Sub

    Private Sub FlujoPagoChip(strReply As String)
        Select Case _status
            Case "1"
                If (_1isACK) Then                   ' Ultima transaccion
                    ACKtoPOS_Local()                ' ACK
                    RevTransactionNtoPOS_Local()    ' TransRevNo
                    _status = "2"
                    _2isACK = False
                Else
                    If (IsACK(strReply)) Then       ' ACK
                        _1isACK = True
                    Else

                    End If
                End If
            Case "2"
                If (_2isACK) Then                   ' Solicitud Pantalla Ingrese tarjeta
                    ACKtoPOS_Local()
                    _status = "wait2"
                Else
                    If (IsACK(strReply)) Then
                        _2isACK = True
                    Else

                    End If
                End If
            Case "wait2"                            ' Solicitud de Datos
                ACKtoPOS_Local()
                DataToPOS_Local()
                _status = "3"
                _3isACK = False
            Case "3"
                If (_3isACK) Then                   ' Solicitud Pantalla ingrese Pin
                    ACKtoPOS_Local()
                    _status = "4"
                Else
                    If (IsACK(strReply)) Then
                        _3isACK = True
                    Else

                    End If
                End If
            Case "4"
                ACKtoPOS_Local()
                CierreTransaccionChip(strReply)
                _1isACK = False
                _2isACK = False
                _3isACK = False

        End Select
    End Sub

    Private Sub FlujoPagoCTL(strReply As String)
        Select Case _status
            Case "1"
                If (_1isACK) Then                   ' Ultima Transaccion
                    ACKtoPOS_Local()                ' ACK
                    RevTransactionNtoPOS_Local()    ' TransRevNo
                    _status = "2"
                    _2isACK = False
                Else
                    If (IsACK(strReply)) Then
                        _1isACK = True
                    Else

                    End If
                End If
            Case "2"
                If (_2isACK) Then                   ' Solicitud de Datos
                    ACKtoPOS_Local()
                    DataToPOS_Local()
                    _status = "3"
                    _3isACK = False
                Else
                    If (IsACK(strReply)) Then       ' ACK
                        _2isACK = True
                    Else

                    End If
                End If

            Case "3"
                If (_3isACK) Then                   ' Solicitud Pantalla Acerque tarjeta
                    ACKtoPOS_Local()                ' ACK
                    TipoLecturaCTLtoPOS_Local()
                    _status = "wait3"
                    _wait3isACK = False
                Else
                    If (IsACK(strReply)) Then       ' ACK
                        _3isACK = True
                    Else

                    End If
                End If
            Case "wait3"
                If (_wait3isACK) Then               ' Solicitud Pantalla Ingrese Pin
                    ACKtoPOS_Local()                ' ACK
                    _status = "4"
                Else
                    If (IsACK(strReply)) Then       ' ACK
                        _wait3isACK = True
                    Else

                    End If
                End If
            Case "4"
                ACKtoPOS_Local()
                CierreTransaccionCtl(strReply)
                _1isACK = False
                _2isACK = False
                _3isACK = False
                _wait3isACK = False

        End Select
    End Sub

    Private Sub FlujoCierre(strReply As String)
        Select Case _status
            Case "1"
                If (_1isACK) Then                   ' Cantidad de transacciones
                    ACKtoPOS_Local()                ' ACK
                    Dim resp As String = strReply.Substring(50, 4)
                    Dim cant As String = strReply.Substring(64, 8)
                    'Console.Write("Cod. Respuesta: ")
                    'Console.WriteLine(resp)
                    Log("Cod. Respuesta: " + resp)

                    'Console.Write("Cant. Transacciones: ")
                    'Console.WriteLine(cant)
                    Log("Cant. Transacciones: " + cant)

                    If (resp.Equals("5858")) Then
                        _status = ""
                        cierreSinTransac()
                        _1isACK = False
                        _2isACK = False

                    Else
                        _status = "2"
                        _2isACK = False
                    End If

                Else
                    If (IsACK(strReply)) Then
                        _1isACK = True
                    Else

                    End If
                End If
            Case "2"
                Dim lon As Integer
                lon = strReply.Length
                ACKtoPOS_Local()                    ' ACK
                If (lon > 80) Then                  ' Mas transacciones

                Else                                ' No hay mas transacciones
                    cierreConTransac()
                    _1isACK = False
                    _2isACK = False

                End If

        End Select
    End Sub

  
    Private Sub FlujoInicializar(strReply As String)
        Select Case _status
            Case "1"
                If (_1isACK) Then                   ' Respuesta del host
                    ACKtoPOS_Local()                ' ACK
                    cierreInicializar()
                    _1isACK = False


                Else
                    If (IsACK(strReply)) Then
                        _1isACK = True
                    Else

                    End If
                End If


        End Select
    End Sub

    Private Sub CierreTransaccionChip(strReply As String)
        _pos.LoadedLRC_Variable(strReply)                       ' -- dll --
        Dim codes As New List(Of Integer)
        codes = _pos.UnpackingFieldName                         ' -- dll --
        Dim indexAUto As Integer = 0
        Dim indexReply As Integer = 0
        Dim indexMonto As Integer = 0
        Dim indexRec As Integer = 0
        Dim indexBin As Integer = 0
        Dim indexPan As Integer = 0
        Dim indexRRN As Integer = 0
        Dim indexTerm As Integer = 0
        Dim indexError As Integer = 0
        Dim indexFecha As Integer = 0
        Dim indexHora As Integer = 0
        Dim indexCountCierres As Integer = 0
        Dim index As Integer = 0

        For Each c As Integer In codes
            Select Case c
                Case 1
                    indexAUto = index
                Case 48
                    indexReply = index
                Case 61
                    indexError = index
                Case 40
                    indexmonto = index
                Case 43
                    indexRec = index
                Case 75
                    indexBin = index
                Case 54
                    indexPan = index
                Case 44
                    indexRRN = index
                Case 45
                    indexTerm = index
                Case 46
                    indexFecha = index
                Case 47
                    indexHora = index
                Case 90
                    indexCountCierres = index
            End Select
            index = index + 1
        Next

        Dim codRespuesta As String = _pos._DPackageData_POS(_pos.BufferFieldData(indexReply), codes(indexReply))
        Dim codAutorizacion As String = _pos._DPackageData_POS(_pos.BufferFieldData(indexAUto), codes(indexAUto))
        Dim recibo As String = _pos._DPackageData_POS(_pos.BufferFieldData(indexRec), codes(indexRec))
        Dim monto As String = _pos._DPackageData_POS(_pos.BufferFieldData(indexMonto), codes(indexMonto))
        Dim terminalId As String = _pos._DPackageData_POS(_pos.BufferFieldData(indexTerm), codes(indexTerm))
        Dim fechaTransac As String = _pos._DPackageData_POS(_pos.BufferFieldData(indexFecha), codes(indexFecha))
        Dim horaTransac As String = _pos._DPackageData_POS(_pos.BufferFieldData(indexHora), codes(indexHora))
        Dim cuatroDigitos As String = _pos._DPackageData_POS(_pos.BufferFieldData(indexPan), codes(indexPan))
        Dim binTarjeta As String = _pos._DPackageData_POS(_pos.BufferFieldData(indexBin), codes(indexBin))
        Dim rrnTransac As String = _pos._DPackageData_POS(_pos.BufferFieldData(indexRRN), codes(indexRRN))
        Dim msgError As String = _pos._DPackageData_POS(_pos.BufferFieldData(indexError), codes(indexError))

        'Console.Write("Respuesta:")
        'Console.WriteLine(codRespuesta)
        Log("---- CIERRE TARJETA CHIP ----")
        Log("Respuesta: " + codRespuesta)
        Log("Autorizacion: " + codAutorizacion)
        Log("RRN: " + rrnTransac)
        Log("Monto: " + monto)

        'Console.Write("Recibo:")
        'Console.WriteLine(recibo)
        Log("Recibo: " + recibo)
        Log("Fecha: " + fechaTransac)
        Log("Hora: " + horaTransac)
        Log("Ult.4 digitos: " + cuatroDigitos)
        Log("Bin tarjeta: " + binTarjeta)
        Log("Terminal Id: " + terminalId)
        Log("Error: " + msgError)

        _status = -1
        _pagoChip = False
        ClosePort_Local()

    End Sub

    Private Sub CierreTransaccionCtl(strReply As String)
        _pos.LoadedLRC_Variable(strReply)                       ' -- dll --
        Dim codes As New List(Of Integer)
        codes = _pos.UnpackingFieldName                         ' -- dll --
        Dim indexAUto As Integer = 0
        Dim indexReply As Integer = 0
        Dim indexMonto As Integer = 0
        Dim indexRec As Integer = 0
        Dim indexBin As Integer = 0
        Dim indexPan As Integer = 0
        Dim indexRRN As Integer = 0
        Dim indexTerm As Integer = 0
        Dim indexError As Integer = 0
        Dim indexFecha As Integer = 0
        Dim indexHora As Integer = 0
        Dim indexCountCierres As Integer = 0
        Dim index As Integer = 0

        For Each c As Integer In codes
            Select Case c
                Case 1
                    indexAUto = index
                Case 48
                    indexReply = index
                Case 61
                    indexError = index
                Case 40
                    indexMonto = index
                Case 43
                    indexRec = index
                Case 75
                    indexBin = index
                Case 54
                    indexPan = index
                Case 44
                    indexRRN = index
                Case 45
                    indexTerm = index
                Case 46
                    indexFecha = index
                Case 47
                    indexHora = index

            End Select
            index = index + 1
        Next

        Dim codRespuesta As String = _pos._DPackageData_POS(_pos.BufferFieldData(indexReply), codes(indexReply))
        Dim codAutorizacion As String = _pos._DPackageData_POS(_pos.BufferFieldData(indexAUto), codes(indexAUto))
        Dim recibo As String = _pos._DPackageData_POS(_pos.BufferFieldData(indexRec), codes(indexRec))
        Dim monto As String = _pos._DPackageData_POS(_pos.BufferFieldData(indexMonto), codes(indexMonto))
        Dim terminalId As String = _pos._DPackageData_POS(_pos.BufferFieldData(indexTerm), codes(indexTerm))
        Dim fechaTransac As String = _pos._DPackageData_POS(_pos.BufferFieldData(indexFecha), codes(indexFecha))
        Dim horaTransac As String = _pos._DPackageData_POS(_pos.BufferFieldData(indexHora), codes(indexHora))
        Dim cuatroDigitos As String = _pos._DPackageData_POS(_pos.BufferFieldData(indexPan), codes(indexPan))
        Dim binTarjeta As String = _pos._DPackageData_POS(_pos.BufferFieldData(indexBin), codes(indexBin))
        Dim rrnTransac As String = _pos._DPackageData_POS(_pos.BufferFieldData(indexRRN), codes(indexRRN))
        Dim msgError As String = _pos._DPackageData_POS(_pos.BufferFieldData(indexError), codes(indexError))

        'Console.Write("Respuesta:")
        'Console.WriteLine(codRespuesta)
        Log("---- CIERRE TARJETA CONTACTLESS ----")
        Log("Respuesta: " + codRespuesta)
        Log("Autorizacion: " + codAutorizacion)
        Log("RRN: " + rrnTransac)
        Log("Monto: " + monto)

        'Console.Write("Recibo:")
        'Console.WriteLine(recibo)
        Log("Recibo: " + recibo)
        Log("Fecha: " + fechaTransac)
        Log("Hora: " + horaTransac)
        Log("Ult.4 digitos: " + cuatroDigitos)
        Log("Bin tarjeta: " + binTarjeta)
        Log("Terminal Id: " + terminalId)
        Log("Error: " + msgError)

        _status = -1
        _pagoCtl = False
        ClosePort_Local()

    End Sub

    Private Sub cierreSinTransac()
        'Console.WriteLine("Cierre sin transacciones")
        Log("Cierre sin transacciones")
        _status = -1
        _cierrePOS = False
        ClosePort_Local()
    End Sub

    Private Sub cierreConTransac()
        'Console.WriteLine("Cierre con transacciones")
        Log("Cierre con transacciones")
        _status = -1
        _cierrePOS = False
        ClosePort_Local()
    End Sub

    Private Sub cierreAnulacionNoEncont()
        'Console.WriteLine("Cierre Anulacion no encontrada")
        Log("Cierre Anulacion no encontrada")
        _status = -1
        _anularTrans = False
        ClosePort_Local()
    End Sub

    Private Sub cierreAnulacionOk()
        'Console.WriteLine("Cierre Anulacion exitosa")
        Log("Cierre Anulacion exitosa")
        _status = -1
        _anularTrans = False
        ClosePort_Local()
    End Sub

    Private Sub cierreInicializar()
        'Console.WriteLine("Cierre Inicializacion exitosa")
        Log("Cierre Inicializacion exitosa")
        _status = -1
        _inicializarPOS = False
        ClosePort_Local()
    End Sub

    Private Sub ReqConnectionToPOS_Local()
        _status = "1"
        _1isACK = False
        _pos._SendConecction_POS()              ' -- dll --
        'Console.WriteLine("CAJA: Se envio Conexion Chip")
        Log("Se envio Conexion Chip")
    End Sub

    Private Sub ReqConnectionCTLToPOS_Local()
        _status = "1"
        _1isACK = False
        _pos._SendConecctionCTL_POS()              ' -- dll --
        'Console.WriteLine("CAJA: Se envio Conexion CTL")
        Log("Se envio Conexion CTL")
    End Sub

    Private Sub RevTransactionNtoPOS_Local()
        _pos._RevTransNO_POS()
        'Console.WriteLine("CAJA: Se envio TransRevNo")
        Log("Se envio TransRevNo")
    End Sub

    Private Sub DataToPOS_Local()
        Dim dataHex As String
        Dim mpk As Integer
        If Integer.TryParse(txtMpk.Text, mpk) AndAlso mpk > 0 AndAlso mpk < 32000 Then
            'Console.WriteLine("Mpk:" & mpk)
            dataHex = _pos._DataToPOS(mpk, montoBOB, txtPnr.Text, 1)
            'Console.Write("Se envio DatosTransac:")
            'Console.WriteLine(dataHex)
            Log("CAJA: Se envio DatosTransac:" + dataHex)
        Else
            MessageBox.Show("El numero de caja debe ser un numero entero.")
        End If


    End Sub

    Private Sub TipoLecturaCTLtoPOS_Local()
        _pos._TipoTarjetaCTL_POS()                  ' -- dll --
        'Console.WriteLine("Se envio Tipo Lectura CTL")
        Log("CAJA: Se envio Tipo Lectura CTL")
    End Sub

    Private Sub ReqCierreToPOS_Local()
        _status = "1"
        _1isACK = False
        _pos._SolCierre_POS()                       ' -- dll --
        'Console.WriteLine("Se enviio solicitud de Cierre")
        Log("CAJA: Se enviio solicitud de Cierre")
    End Sub

    Private Sub ReqConfirmAnulToPOS_Local()
        _pos._ConfirmarAnulacion_POS()
        'Console.WriteLine("Se envio confirmacion de Anulacion")
        Log("CAJA: Se envio confirmacion de Anulacion")
    End Sub

    Private Sub ReqInicializarToPOS_Local()
        _status = "1"
        _1isACK = False
        _pos._SolInicializ_POS()                       ' -- dll --
        'Console.WriteLine("Se envio solicitud de Inicializacion")
        Log("CAJA: Se envio solicitud de Inicializacion")
    End Sub

    Private Sub ACKtoPOS_Local()
        _pos._ACK_POS()
        'Console.WriteLine("Se envio ACK")
        Log("CAJA: ACK")
    End Sub

    Private Sub ClosePort_Local()
        If (Not _pos._ClosePort_POS()) Then
            MsgBox("No se puede cerrar el puerto COM.")
        End If
    End Sub

    Private Sub Log(line As String)
        txtLog.AppendText(line + Environment.NewLine)
    End Sub

    Private Function validarMonto() As Boolean
        Dim monto As String
        Dim n() As String
        monto = txtMonto.Text
        If (monto = "0.00") Then
            MsgBox("Debe agregar un producto a la lista de compras.")
            Return False
        Else
            n = monto.Split(".")
            Dim montoint As String = n(0) & n(1)
            montoBOB = CInt(montoint)
            'Console.Write("montoBOB:")
            'Console.WriteLine(montoBOB)
            Return True
        End If

    End Function

    Private Function validarDatosTransac() As Boolean
        Dim mpk As Integer
        If Integer.TryParse(txtMpk.Text, mpk) AndAlso mpk > 0 AndAlso mpk < 32000 Then
            Return True
        Else
            MessageBox.Show("El numero de caja debe ser un numero entero.")
            Return False
        End If
    End Function

    Private Function validarAnulacion() As Boolean
        Dim ref As Integer
        If Integer.TryParse(txtAnular.Text, ref) AndAlso ref > 0 AndAlso ref < 32000 Then
            Return True
        Else
            MessageBox.Show("El numero de recibo para anular, debe ser un numero entero.")
            Return False
        End If
    End Function

    Private Function IsACK(strReply As String) As Boolean
        If (strReply.Equals("06")) Then
            Return True
        Else
            Return False
        End If
    End Function

    Private Sub DemoCajasPOS_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    End Sub
End Class
Responder Con Cita
  #2  
Antiguo 04-11-2021
Avatar de Neftali [Germán.Estévez]
Neftali [Germán.Estévez] Neftali [Germán.Estévez] is offline
[becario]
 
Registrado: jul 2004
Ubicación: Barcelona - España
Posts: 18.272
Poder: 10
Neftali [Germán.Estévez] Es un diamante en brutoNeftali [Germán.Estévez] Es un diamante en brutoNeftali [Germán.Estévez] Es un diamante en bruto
Personalmente no he entendido lo que necesitas.
¿La librería LibraryPOS.dll ya está creada? ¿Es tuya? ¿Las funciones están definidas para ser exportables?
¿Sabemos cómo están definidas esas funciones?
No entiendo qué son las instrucciones que has puesto y el código en VisualBasic que también has puesto.
__________________
Germán Estévez => Web/Blog
Guía de estilo, Guía alternativa
Utiliza TAG's en tus mensajes.
Contactar con el Clubdelphi

P.D: Más tiempo dedicado a la pregunta=Mejores respuestas.
Responder Con Cita
  #3  
Antiguo 04-11-2021
CrazySoft CrazySoft is offline
Miembro
 
Registrado: abr 2005
Posts: 96
Poder: 20
CrazySoft Va por buen camino
Gracias por responder

La librería no es mía me dieron para poder usarla

Las funciones están definidas para exportación tengo un código en vb que las usa


No se como están definidas las funciones solo tengo el ejemplo de uso

No entiendo mucho de vb

Pero lo que necesito es poder usar esa librería
Responder Con Cita
  #4  
Antiguo 05-11-2021
Avatar de Neftali [Germán.Estévez]
Neftali [Germán.Estévez] Neftali [Germán.Estévez] is offline
[becario]
 
Registrado: jul 2004
Ubicación: Barcelona - España
Posts: 18.272
Poder: 10
Neftali [Germán.Estévez] Es un diamante en brutoNeftali [Germán.Estévez] Es un diamante en brutoNeftali [Germán.Estévez] Es un diamante en bruto
Habría que saber la firma de las DLL's que está exportando la librería de VisualBasic.
También el tipo de DLL (estoy pensando en un ActiveX). en ese caso hay que registrarla y desde Delphi puedes importar.

Es dar un poco palos de ciego, porque no estás concretando y faltan muchos datos, para algo que no es simple como esto.
También puedes probar:
Component/Import component/
Import Type Library
Import ActiveX control

También puedes revisar estos hilos que hablan sobre cómo llamar a DLLs en otros lenguajes (VB) entre ellos:
http://clubdelphi.com/foros/showthread.php?t=10532
https://www.clubdelphi.com/foros/sho...d.php?p=533852
__________________
Germán Estévez => Web/Blog
Guía de estilo, Guía alternativa
Utiliza TAG's en tus mensajes.
Contactar con el Clubdelphi

P.D: Más tiempo dedicado a la pregunta=Mejores respuestas.
Responder Con Cita
  #5  
Antiguo 05-11-2021
CrazySoft CrazySoft is offline
Miembro
 
Registrado: abr 2005
Posts: 96
Poder: 20
CrazySoft Va por buen camino
No es un Activex, ya intente registrarla e importarla, no me permite registrar


creo que es una clase que esta incluida en la DLL, con funciones y variables, no son simples funciones las que tiene la DLL



no se como hacer la definicion para exportar la clase de la DLL, definir el tipo en Delphi para poderla crear y usar


o estoy equivocado
Responder Con Cita
  #6  
Antiguo 05-11-2021
CrazySoft CrazySoft is offline
Miembro
 
Registrado: abr 2005
Posts: 96
Poder: 20
CrazySoft Va por buen camino
Esto es lo que entieno, pero no se como definir la clase que esta en la "LibraryPOS.dll" para poderla usar

Código:
// Crear una instancia de la clase _POSLibrary
Dim _pos As New _POSLibrary._LibraryPOS  <- crea una clase que esta en la DLL

// Crear una instancia de la clase SerialPort
Dim _portPOS As New IO.Ports.SerialPort   

// Conexión al puerto serial e inicio de conexión

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles btnPagarChip.Click
  If (validarDatosTransac() And validarMonto()) Then
    _pagoChip = True
    Dim isConnected As Boolean = False

    If (Not _portPOS.IsOpen) Then
      ActivePorts = _pos._ListActivePorts_POS() ' -- dll --   <- lista los puertos mediante la clase
    For Each puerto As String In ActivePorts
     _NumPort = puerto
     Next
    isConnected = _pos._OpenPort_POS(_NumPort) ' -- dll --  <- abre el puerto con una funcion en la clase
    If (isConnected) Then
      _status = "0"
      _portPOS = _pos.PortUSB
      AddHandler _portPOS.DataReceived, AddressOf PortCOM_DataReceived  <- no entiendo que es lo que hace pero asigna el puerto 
    End If
  Else
    isConnected = True
  _status = "0"
  End If
  If (Not isConnected) Then
    MsgBox("No hay conexion al puerto COM.")
    Return
    End If
  ReqConnectionToPOS_Local()
  End If
End Sub
Responder Con Cita
  #7  
Antiguo 05-11-2021
CrazySoft CrazySoft is offline
Miembro
 
Registrado: abr 2005
Posts: 96
Poder: 20
CrazySoft Va por buen camino
lo que necesitaria hacer seria algo asi con la DLL que tengo
https://www.clubdelphi.com/foros/showthread.php?t=93148

gracias

Última edición por Neftali [Germán.Estévez] fecha: 05-11-2021 a las 14:39:12.
Responder Con Cita
  #8  
Antiguo 05-11-2021
Avatar de Neftali [Germán.Estévez]
Neftali [Germán.Estévez] Neftali [Germán.Estévez] is offline
[becario]
 
Registrado: jul 2004
Ubicación: Barcelona - España
Posts: 18.272
Poder: 10
Neftali [Germán.Estévez] Es un diamante en brutoNeftali [Germán.Estévez] Es un diamante en brutoNeftali [Germán.Estévez] Es un diamante en bruto
El problema es que no hay forma de importar esa DLL desde Delphi. De todas las formas en que lo he probado me da error.

Habría que saber si esta gente tienen algo más para integrar.
Desde .NET si se puede importar la referencia.

Ver si tienen un SDK, un ActiveX o algo que no se refiera sólo a .NET.
__________________
Germán Estévez => Web/Blog
Guía de estilo, Guía alternativa
Utiliza TAG's en tus mensajes.
Contactar con el Clubdelphi

P.D: Más tiempo dedicado a la pregunta=Mejores respuestas.

Última edición por Neftali [Germán.Estévez] fecha: 05-11-2021 a las 14:12:58.
Responder Con Cita
  #9  
Antiguo 05-11-2021
Avatar de Neftali [Germán.Estévez]
Neftali [Germán.Estévez] Neftali [Germán.Estévez] is offline
[becario]
 
Registrado: jul 2004
Ubicación: Barcelona - España
Posts: 18.272
Poder: 10
Neftali [Germán.Estévez] Es un diamante en brutoNeftali [Germán.Estévez] Es un diamante en brutoNeftali [Germán.Estévez] Es un diamante en bruto
Cita:
Empezado por CrazySoft Ver Mensaje
lo que necesitaria hacer seria algo asi con la DLL que tengo
https://www.clubdelphi.com/foros/showthread.php?t=93148

El problema es que eso está pensado para una DLL realizada en Delphi.
__________________
Germán Estévez => Web/Blog
Guía de estilo, Guía alternativa
Utiliza TAG's en tus mensajes.
Contactar con el Clubdelphi

P.D: Más tiempo dedicado a la pregunta=Mejores respuestas.
Responder Con Cita
  #10  
Antiguo 18-11-2021
Avatar de delphi.com.ar
delphi.com.ar delphi.com.ar is offline
Federico Firenze
 
Registrado: may 2003
Ubicación: Buenos Aires, Argentina *
Posts: 5.932
Poder: 26
delphi.com.ar Va por buen camino
Cita:
Empezado por CrazySoft Ver Mensaje
Esto es lo que entieno, pero no se como definir la clase que esta en la "LibraryPOS.dll" para poderla usar

Código:
// Crear una instancia de la clase _POSLibrary
Dim _pos As New _POSLibrary._LibraryPOS  <- crea una clase que esta en la DLL

La DDL está exportando una clase, no métodos/funciones, por lo tanto no es una DLL "plana", por el contrario es un objeto COM, y si no quieres reimplementar COM en Delphi, debes importarla como tal con las funciones específicas del IDE de Delphi para importar COM / ActiveX. (No dispongo de un Delphi instalado como para guiarte, pero hay mucha info en el foro como aquí)

¡Saludos!
__________________
delphi.com.ar

Dedique el tiempo suficiente para formular su pregunta si pretende que alguien dedique su tiempo en contestarla.
Responder Con Cita
  #11  
Antiguo 20-11-2021
CrazySoft CrazySoft is offline
Miembro
 
Registrado: abr 2005
Posts: 96
Poder: 20
CrazySoft Va por buen camino
Gracias, pero no me permite registrar la DLL para luego importa


---------------------------
RegSvr32
---------------------------
Se cargó el módulo "C:\WINDOWS\system32\LibraryPOS.dll", pero no se encontró el punto de entrada DllRegisterServer.

Asegúrese de que "C:\WINDOWS\system32\LibraryPOS.dll" es un archivo DLL u OCX válido e inténtelo de nuevo.
---------------------------
Aceptar
---------------------------
Responder Con Cita
  #12  
Antiguo 20-11-2021
Avatar de mamcx
mamcx mamcx is offline
Moderador
 
Registrado: sep 2004
Ubicación: Medellín - Colombia
Posts: 3.911
Poder: 25
mamcx Tiene un aura espectacularmamcx Tiene un aura espectacularmamcx Tiene un aura espectacular
Aqui tienes es que ir con la gente que hizo esa DLL y que te den la info de como se integra.

O es un COM, o es una DLL "plana". En el caso segundo, necesitas los "headers" que se deben pasar como un archivo de C .h y una documentacion de como son las estructuras.
__________________
El malabarista.
Responder Con Cita
  #13  
Antiguo 22-11-2021
Avatar de Neftali [Germán.Estévez]
Neftali [Germán.Estévez] Neftali [Germán.Estévez] is offline
[becario]
 
Registrado: jul 2004
Ubicación: Barcelona - España
Posts: 18.272
Poder: 10
Neftali [Germán.Estévez] Es un diamante en brutoNeftali [Germán.Estévez] Es un diamante en brutoNeftali [Germán.Estévez] Es un diamante en bruto
Cita:
Empezado por delphi.com.ar Ver Mensaje
La DDL está exportando una clase, no métodos/funciones, por lo tanto no es una DLL "plana", por el contrario es un objeto COM, y si no quieres reimplementar COM en Delphi, debes importarla como tal con las funciones específicas del IDE de Delphi para importar COM / ActiveX. (No dispongo de un Delphi instalado como para guiarte, pero hay mucha info en el foro como aquí)

Yo también intenté registrarla y da error.
Por lo tanto, tal y como comenta [mamcx], sólo queda hablar con quien la ha diseñado y ver qué están diseñando y cómo.
__________________
Germán Estévez => Web/Blog
Guía de estilo, Guía alternativa
Utiliza TAG's en tus mensajes.
Contactar con el Clubdelphi

P.D: Más tiempo dedicado a la pregunta=Mejores respuestas.
Responder Con Cita
  #14  
Antiguo 23-11-2021
Avatar de delphi.com.ar
delphi.com.ar delphi.com.ar is offline
Federico Firenze
 
Registrado: may 2003
Ubicación: Buenos Aires, Argentina *
Posts: 5.932
Poder: 26
delphi.com.ar Va por buen camino
El tema es simple, si en VB se usan directamente clases de la librería, se trata de un objeto COM, si el código VB importa funciones y procedimientos, se trata de una "DLL Plana", y se debe importar al igual que en Delphi, haciendo la definición de cada función a utilizar, por ejemplo:

Código:
Declare Function FormatMessage Lib "kernel32" Alias "FormatMessageA" _
    (ByVal dwFlags As Long, lpSource As Any, ByVal dwMessageId As Long, _
     ByVal dwLanguageId As Long, ByVal lpBuffer As String, _
     ByVal nSize As Long, Arguments As Long) As Long
En ese ejemplo se está importando la función exportada como "FormatMessageA" de la librería "kernel32".

Cita:
Empezado por CrazySoft Ver Mensaje
---------------------------
RegSvr32
---------------------------
Se cargó el módulo "C:\WINDOWS\system32\LibraryPOS.dll", pero no se encontró el punto de entrada DllRegisterServer.

Asegúrese de que "C:\WINDOWS\system32\LibraryPOS.dll" es un archivo DLL u OCX válido e inténtelo de nuevo.
---------------------------
Aceptar
---------------------------
Quienes hemos tenido la desgracia de utilizar objetos COM, nos ha sucedido mas de una vez que los errores informados no son siempre del todo cierto, por ejemplo recuerdo intentar registrar librerías, que tenían dependencias no satisfechas, y el error siempre era el mismo. Una forma de saber si se trata de un objeto COM, que también sirve para descubrir dependencias insatisfechas, es explorar la librería con herramientas como Dependency Walker. Si la librería exporta las funciones DllCanUnloadNow, DllGetClassObject, DllRegisterServer y DllUnregisterServer, casi seguro se trata de una DLL COM. Si no es así, el proveedor de la librería te debe entregar la documentación de las funciones y procedimientos exportados, dado que las librerías "planas" no exportan ese tipo de información.

Si la librería fue desarrollada en VB, seguramente dependa del runtime de Visual Basic, y de MSCOMM32 para usar el puerto serie.

Ver:
http://www.clubdelphi.com/foros/showthread.php?t=94393


Cita:
Empezado por Neftali [Germán.Estévez] Ver Mensaje
Yo también intenté registrarla y da error.
Por lo tanto, tal y como comenta [mamcx], sólo queda hablar con quien la ha diseñado y ver qué están diseñando y cómo.
¿La DLL es pública?... ¿de dónde se puede descargar?
__________________
delphi.com.ar

Dedique el tiempo suficiente para formular su pregunta si pretende que alguien dedique su tiempo en contestarla.

Última edición por delphi.com.ar fecha: 23-11-2021 a las 22:33:42.
Responder Con Cita
  #15  
Antiguo 24-11-2021
Avatar de Neftali [Germán.Estévez]
Neftali [Germán.Estévez] Neftali [Germán.Estévez] is offline
[becario]
 
Registrado: jul 2004
Ubicación: Barcelona - España
Posts: 18.272
Poder: 10
Neftali [Germán.Estévez] Es un diamante en brutoNeftali [Germán.Estévez] Es un diamante en brutoNeftali [Germán.Estévez] Es un diamante en bruto
Cita:
Empezado por delphi.com.ar Ver Mensaje
¿La DLL es pública?... ¿de dónde se puede descargar?

Adjunto la DLL.
Archivos Adjuntos
Tipo de Archivo: zip LibraryPOS.zip (23,4 KB, 6 visitas)
__________________
Germán Estévez => Web/Blog
Guía de estilo, Guía alternativa
Utiliza TAG's en tus mensajes.
Contactar con el Clubdelphi

P.D: Más tiempo dedicado a la pregunta=Mejores respuestas.
Responder Con Cita
  #16  
Antiguo 24-11-2021
Avatar de mamcx
mamcx mamcx is offline
Moderador
 
Registrado: sep 2004
Ubicación: Medellín - Colombia
Posts: 3.911
Poder: 25
mamcx Tiene un aura espectacularmamcx Tiene un aura espectacularmamcx Tiene un aura espectacular
La otra es hacer un puente: Creas un proyecto en VB.NET donde puedas controlar como "exportar" la funcionalidad. El proyecto seria cualquier cosa que te parezca: Una linea de comandos, servicio web, libreria COM, etc.
__________________
El malabarista.
Responder Con Cita
  #17  
Antiguo 24-11-2021
Avatar de delphi.com.ar
delphi.com.ar delphi.com.ar is offline
Federico Firenze
 
Registrado: may 2003
Ubicación: Buenos Aires, Argentina *
Posts: 5.932
Poder: 26
delphi.com.ar Va por buen camino
Cita:
Empezado por Neftali [Germán.Estévez] Ver Mensaje
Adjunto la DLL.
¡Ahora si!... Es una DLL .NET compilada para el framework v4.0.30319. (El uso del objeto IO.Ports.SerialPort ya daba una pista de eso)

Si bien .NET es la evolución de COM+, terminó siendo algo totalmente distinto y mucho mas grande. Y por lo que estuve leyendo, para usar librerías .NET en Delphi no es tan transparente y tenés que hacer un proyecto intermedio como dice mamcx.

¡Saludos!
__________________
delphi.com.ar

Dedique el tiempo suficiente para formular su pregunta si pretende que alguien dedique su tiempo en contestarla.
Responder Con Cita
  #18  
Antiguo 25-11-2021
CrazySoft CrazySoft is offline
Miembro
 
Registrado: abr 2005
Posts: 96
Poder: 20
CrazySoft Va por buen camino
Muchas gracias, Neftali [Germán.Estévez], mamcx, Federico Firenze, ya lo tengo más claro, estaba perdido, estoy poniéndome a investigar la importación de .Net con los enlaces que indicaron y comenzare a subir el código que realice



Cita:
Empezado por delphi.com.ar Ver Mensaje
¡Ahora si!... Es una DLL .NET compilada para el framework v4.0.30319. (El uso del objeto IO.Ports.SerialPort ya daba una pista de eso)

Si bien .NET es la evolución de COM+, terminó siendo algo totalmente distinto y mucho mas grande. Y por lo que estuve leyendo, para usar librerías .NET en Delphi no es tan transparente y tenés que hacer un proyecto intermedio como dice mamcx.

¡Saludos!

Saludos
Responder Con Cita
Respuesta



Normas de Publicación
no Puedes crear nuevos temas
no Puedes responder a temas
no Puedes adjuntar archivos
no Puedes editar tus mensajes

El código vB está habilitado
Las caritas están habilitado
Código [IMG] está habilitado
Código HTML está deshabilitado
Saltar a Foro

Temas Similares
Tema Autor Foro Respuestas Último mensaje
Implementar Trigger o no? golf2008 MySQL 7 07-11-2008 23:24:09
ayuda para Implementar el sudoku gulder Varios 5 25-02-2008 17:37:24
Implementar GnuPG Henryoh Varios 2 17-01-2007 21:10:18
ayuda!!! como implementar sql en delphi diablorojo1886 SQL 3 04-12-2006 02:02:25
Implementar un CVS menavas Varios 1 03-10-2006 22:48:01


La franja horaria es GMT +2. Ahora son las 19:22:48.


Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi
Copyright 1996-2007 Club Delphi