Página 1 de 3

Comunicação direta

Enviado: 27 Nov 2007 12:14
por leandrolinauer
-:] Bom dia caros colegas.
Eu já consegui compilar a HbComm com o harbour 1.0.0 ja compilei no programa ECF, mas no entanto estou com dúvida de como devo escrever os comandos para emitir para a ECF.
Se alguém que já fez puder postar um pequeno exemplo de um comando com a comunicação direta tipo: LeituraX, Venda de um item, etc.

Grato.

Bay :xau

Enviado: 27 Nov 2007 14:54
por sygecom
Trabalho com Comunicação Seriall com balanças Eletronicas e CLP,não trabalho com ECF, mas abaixo segue a lista de comandos da HBCOMM e como usar elas, o Read-me foi traduzido com uma ferramneta Gratuita ON-LINE, então não espere nenhuma correção ortografica.

Código: Selecionar todos

***********************
TRADUÇÃO PARA PORTUGUES
***********************
HBComm.Lib
Essa é a alteração mais recente da biblioteca HBComm.
As modificações feitas por mim refletem as necessidades de uma biblioteca
de porta serial que pode conversar com mais de uma porta serial de cada vez.
Além disso, as rotinas originais seriam lidar somente texto não criptografado
e não corretamente passariam Dados contendo caracteres nulos (Chr(0)).
Finalmente, acessar portas acima COM9 era um dever.

A principal diferença na sintaxe é a necessidade do usuário receber
o "Identificador" retornado pelo Init_Port() e passá-lo para todas as
outras rotinas sempre referenciar uma porta.
Isso equivale à variável nComm usado nas antigas rotinas seriais Clipper/Fivewin.

Informações das Funções:

Init_Port( cPort, nBaudrate, nDatabits, nParity, nStopbits, nBuffersize ) --> nHandle

*Inicialiazador da Porta Serial

     Where:

      cPort       Port que deve se conectar com a Porta Serial até a COM9

     nBaudrate   Exatamente como você está acostumado (por exemplo, 2400, 9600, 4800 etc..)

     nDatabits   No Geral é 8, mas pode ser 7 ou 4.
 
     nParity     codificados: 0,1,2,3-> nenhuma, ímpar, marcar, até mesmo

     nStopbits   codificados: 0,1,2 -> 1, 1.5, 2

     nBuffersize ESTA usando 8000 na transmissão 38.400.

     nHandle     identificador retornado instância.  Um numérico > = 256.  Se nHandle for negativo, a abertura falha.

OutBufClr( nHandle ) --> lSuccess

     Limpe o buffer de saída.  lSuccess será sempre TRUE, a menos que seja usada uma nHandle incorreto.


IsWorking( nHandle ) --> lSuccess

     Verifica se a porta é valida para uso. Falhas podem ocorrer se um nHandle incorreto
     é usado ou se a parte remota descarta a linha. Retorno ".T." ou ".F."

InChr( nHandle, @cBuff, nChar ) --> nBytesRead

     Busca dados do buffer de entrada. Observação o pelo argumento de referência passando para o buffer.
     nChar pode ser determinada chamando InBufSize(). nBytesRead é o número real de bytes carregados
     no cBuff (geralmente igual a nChar a menos que há um problema ou nChar é exagerada.)

InBufSize( nHandle ) --> nNumberofBytesInInputBuffer

     Obter a contagem dos bytes Aguardando no buffer de entrada.
     Geralmente, seguido por uma chamada DO Inchr() para buscar os bytes para processamento.


OutChr( nHandle, cBytesToWrite, nCount ) --> lSuccess

     envia os primeiros bytes nCount de cBytesToWrite de seqüência de caracteres.
     Geralmente, nCount == len(cBytesToWrite).


OutBufSize( nHandle ) --> nBytesInOutputBuffer

     Obter a contagem de bytes de caracteres aguardando transmissão.

UnInt_Port( nHandle ) --> lSuccess

     (Fechar) a porta e liberar o identificador.


SIMPLES EXEMPLO DE USO:

******************************************
STATIC nHandle
IF OpenOk()  // FAZ A ABERTURA DA PORTA 
   DOProcessing()
ELSE        // CASO CONTRARIO ELE DAH ERRO  
   ALERT( 'Erro ao abrir a Porta !!!' )
   QUIT
ENDIF

*****************
Function OpenOk()  // abre a porta serial
*****************
IF ( nHandle := Init_Port( 'COM1', 9600, 8, 0, 0, 8000 ) ) > 0   // pode mudar conforme a nescessidade
   OutBufClr( nHandle )   // limpa a porta
   Return IsWorking()     // retorna a leitura da porta
ENDIF
Return FALSE

***********************
Function DOProcessing() // FAZ A VARREDURA NA PORTA
***********************
nChr := InBuffSize( nHandle )
cBuff := Space( nHandle )

IF nChr != InChr( nHandle, @cBuff, nChr )
   ALERT( 'ERRO NA LEITURA DA PORTA' )
   Return FALSE
ENDIF

IF ! OutChr( nHandle, cSomeStuff, Len( cSomeStuff ) )  // COMPARA A LEITURA COM OS BYTES RECEBIDOS
   ALERT("ERRO NA VERIFICAÇÃO")
   Return FALSE
ENDIF
UnInt_Port( nHandle )  // FECHA A PORTA
Return NIL


Tradução By Leonardo Machado (leonardo@sygecom.com.br).

Porto Alegre, 01 de Fevereiro de 2007


********************************************************************************************************
********************************************************************************************************
********************************************************************************************************
********************************************************************************************************
********************************************************************************************************
********************************************************************************************************
********************************************************************************************************
********************************************************************************************************

*********************
INFORMAÇÕES EM INGLES
*********************
HBComm Library

This is the latest iteration of the HBComm library.  The modifications made
by me reflect my needs for a serial port library that could talk to more than
one serial port at a time.  Further, the original routines would handle only
clear text and would not correctly pass data containing null characters
(Chr(0)).  Finally, accessing ports above COM9 was a must.

The major difference in syntax is the need for the user to receive the
"Handle" returned by Init_Port() and pass it to all other routines whenever
referencing a port.  This is equivalent to the nComm variable used in the
old Clipper/Fivewin serial routines.

Function Information:

Init_Port( cPort, nBaudrate, nDatabits, nParity, nStopbits, nBuffersize ) -->
   nHandle

   Port opener and initializer.

   Where:

     cPort      Port designator.  Can either be old form 'COMn' or the more
                general form '\\.\COMn'.  The general form is required for
                ports higher than COM9.

     nBaudrate  Just like you're used to (e.g., 2400, 4800, 9600, etc. )

     nDatabits  Usually 8, but can be 7 or 4.

     nParity    coded: 0,1,2,3 -> none, odd, mark, even

     nStopbits  coded: 0,1,2 -> 1, 1.5, 2

     nBuffersize I'm using 8000 at 38,400 baud.

     nHandle    returned instance identifier.  A numeric >= 256.  If nHandle
                is negative, the open failed.

OutBufClr( nHandle ) --> lSuccess

     Clear the output buffer.  lSuccess will always be TRUE unless a bad
     nHandle is used.

IsWorking( nHandle ) --> lSuccess

     Check to see if port is operative.  Failures can occur if a bad nHandle
     is used or if remote party drops the line.

InChr( nHandle, @cBuff, nChar ) --> nBytesRead

     Fetch data from the input buffer.  Note the by reference argument passing
     for the buffer.  nChar can be determined by calling InBufSize().
     nBytesRead is the actual number of bytes loaded into cBuff (usually
     equal to nChar unless there is a problem or nChar is overstated.)

InBufSize( nHandle ) --> nNumberofBytesInInputBuffer

     Get the count of bytes waiting in the input buffer.  Usually followed by
     a call to Inchr to fetch the bytes for processing.

OutChr( nHandle, cBytesToWrite, nCount ) --> lSuccess

     Write the first nCount bytes from the string cBytesToWrite.  Usually,
     nCount == Len( cBytesToWrite ).

OutBufSize( nHandle ) --> nBytesInOutputBuffer

     Get the byte count of characters awaiting transmission.

UnInt_Port( nHandle ) --> lSuccess

     Uninitialize (Close) the port and free the handle.

USAGE:

Here's how I do this stuff...

STATIC nHandle

...Mainline...


IF OpenOk()

   DOProcessing()

ELSE

   MsgStop( 'Cannot open port!' )

   QUIT

ENDIF

Function OpenOk()

// Open the port

IF ( nHandle := Init_Port( 'COM1', 9600, 8, 0, 0, 8000 ) ) > 0

   OutBufClr( nHandle )   // limpa a porta

   Return IsWorking()

ENDIF

Return FALSE

Function DOProcessing()

...

// Get a chunk from the COM port

nChr := InBuffSize( nHandle )
cBuff := Space( nHandle )

IF nChr != InChr( nHandle, @cBuff, nChr )

   MsgStop( 'Some kind of read failure on COM Port.' )

   Return FALSE

ENDIF

// process data in cBuff

// write some stuff to port

IF ! OutChr( nHandle, cSomeStuff, Len( cSomeStuff ) )

   MsgStop( 'Write error on COM Port.' )

   Return FALSE

ENDIF

// ...etc

// and finally, when night is nigh...

// Close the port

UnInt_Port( nHandle )

Return NIL


Any further contributions to this library are most welcome.

Ned Robertson
XpertCTI, LLC
Richmond, VA  USA

July 21, 2003

Boa Sorte

Enviado: 27 Nov 2007 22:07
por leandrolinauer
Grato amigo, hoje a tarde eu havia feito um teste de leituraX e para minha felicidade, sucesso absoluto, peguei o manual de comunicação direta da bematech e testei com os comandos da HBComm e deu super certo, mas com este exemplo agora vou fazer ficar generico para varias impressoras fiscais.
Muito obrigado.
Abraços a todos aventureiros neste vasto mundo harbour.

Enviado: 28 Nov 2007 11:01
por momente
Muito boa esta tradução,

Parabéns pela iniciativa amigo Leonardo.

Valeu! :{

Enviado: 29 Nov 2007 01:39
por rochinha
Amiguinho,

De também uma olhada em *** PRESENTE DE ANO NOVO **** GERENCIAMENTO DE ECFS e de uma forcinha para melhora-la.

Enviado: 16 Jan 2008 15:20
por hilton_menezes
Estou utilizando o INIT_PORT, com as passagens de parametro segundo tudo como foi descrito acima e qdo estou no sistema e vai na quantidade sai do sistema na hora com o seguinte erro :

Abnormal program termination

alguma dica alguém ?

Enviado: 16 Jan 2008 15:31
por sygecom
Post a parte onde esta usando o INI_PORT

Enviado: 16 Jan 2008 15:38
por hilton_menezes
// Inicia a porta serial
vBalBauds := saBalConf[nScan, bal_bauds]
vBalBits := saBalConf[nScan, bal_databits]
vBalParid := 0
vBalStop := saBalConf[nScan, bal_stopbits]
snHSerial := INIT_PORT(sBalCom, ;
vBalBauds, ;
vBalBits, ;
vBalParid, ;
vBalStop, ;
8000)

IF snHSerial > 0 .AND. ISWORKING(snHSerial)
_PortaAberta(.T.)
_snTimeOut(20)
ELSE
Mensagem(15, "N„o foi poss¡vel abrir a "+sBalCom+"!")
BREAK
ENDIF

Enviado: 16 Jan 2008 16:49
por sygecom
hilton_menezes escreveu:// Inicia a porta serial
vBalBauds := saBalConf[nScan, bal_bauds]
vBalBits := saBalConf[nScan, bal_databits]
vBalParid := 0
vBalStop := saBalConf[nScan, bal_stopbits]
snHSerial := INIT_PORT(sBalCom, ;
vBalBauds, ;
vBalBits, ;
vBalParid, ;
vBalStop, ;
8000)

IF snHSerial > 0 .AND. ISWORKING(snHSerial)
_PortaAberta(.T.)
_snTimeOut(20)
ELSE
Mensagem(15, "N„o foi poss¡vel abrir a "+sBalCom+"!")
BREAK
ENDIF
Please, post os valores de:

Código: Selecionar todos

   snHSerial := INIT_PORT(sBalCom, ;
                         vBalBauds, ;
                         vBalBits, ;
                         vBalParid, ;
                         vBalStop, ;
                         8000)

Enviado: 16 Jan 2008 16:51
por hilton_menezes
snBalcom = "COM1"
vBalBauds=2400
vBalBits =8
vBalParid =0
vBalStop =1

Balança Filizola CS-15

Enviado: 16 Jan 2008 17:20
por sygecom
mude, vBalParid para 1 ou 2 ou 3.

Enviado: 16 Jan 2008 17:28
por hilton_menezes
não deu nenhum deles.....:(

Enviado: 16 Jan 2008 17:31
por sygecom
qual versão do seu xharbour ? e de onde pegou a HBCOMM ?

Enviado: 16 Jan 2008 17:38
por hilton_menezes
0.9950.... pq não consegui compilar em outro ainda...

olha, como estou dando continuidade eu não sei ao certo, ele usa hbcommx...

Enviado: 16 Jan 2008 18:04
por sygecom
hilton_menezes escreveu:0.9950.... pq não consegui compilar em outro ainda...
Pq não consegue ? alguma coisa lhe impede ? vc tem alguma LIB COMERCIAL que só aceita para essa versão...ou algo assim.
olha, como estou dando continuidade eu não sei ao certo, ele usa hbcommx...
Bom, seria idela vc dar uma olhada na versão da sua hbcomm, pq esse seu tipo de erro eu tinha e quando mudei a paridade para maior que zero ele foi embora sem dar esse erro.