Thread: A Full Program to analyze.

  1. #1
    Registered User
    Join Date
    Nov 2008
    Location
    Santa Catarina - Brasil
    Posts
    184

    A Full Program to analyze.

    I was coded a c program to control a industry using balance rs-232, led display RS-485, e thernet, and buttons using DIgital Input/Outputs.

    All this, using a Turbo C++ 3.0 compiled to run in a ICP-i7188E3 (80186 Instruction Set)

    Somebody can anayze, and report possible bugs, ou wrong codes ?

    Code:
    #include <string.h>
    #include <stdio.h>
    #include <conio.h>
    #include <stdlib.h>
    #include <process.h>
    
    #include "..\lib\7188e.h"
    #include "..\lib\vxcomm.h"
    
    #if (__BORLANDC__ <= 0x460) || !defined(__cplusplus)	// Define o Tipo Booleano para o C
      typedef enum { false, true } bool;
    #endif
    
    #define SUCCESS 1					// Retorno OK
    #define WARNING 0					// Retorno Com Aviso
    #define ERROR -1					// Retorno Erro
    
    #define STX 2			  			// Valor Númerico do Caractere de Inicio de pacote (2)
    #define CR 13		  				// Valor Númerico do Caractere de Finalização de pacote (13)
    #define LF 10		  				// Valor Númerico do Caractere de Finalização de pacote (10)
    #define TAB 9						// Valor Númerico do TAB (Separador de Dados em Pacote)
    
    #define VER 0						// Verifica (Função: Fila)
    #define ADD 1						// Adiciona (Função: Fila)
    #define REM 2						// Remove  (Função: Fila)
    
    /*
    /************************************************************************\
    				Controle de Váriaves 
    /************************************************************************\
    */
    
    // Váriaveis e Funções Globais do Sistema
    void ProcessaBuffer (void);
    void AcaoBotaoConfirma (void);
    void AcaoBotaoCancela (void);
    void EscreveDisplay (unsigned char *pMensagem);
    
    char cSTX;								// Caractere de Inicio de pacote (2)
    char cCR;								// Caractere de Finalização de pacote (13)
    char cLF;								// Caractere de Finalização de pacote (10)
    char cTab;								// TAB (Separador de Dados em Pacote)			
    
    // Váriaveis de Controle da Serial
    unsigned int iComBalanca = 1;			//  Porta Serial da Balança
    unsigned int iComDisplay = 2;			// Porta Serial do Display
    int iComBalOn;							// Status da Serial da Balança (Ativo = 1 / Inativo = 0)
    int iComDispOn;							// Status da Serial do Display (Ativo = 1 / Inativo = 0)
    int iComBalRx = 0;						// Recebendo Dados da Serial
    int iMaxBuffer = 300;					// Tamanho máximo do Buffer de Recebimento
    unsigned char *InBuf;	   				// Buffer de Recebimento.
    int iTempoDisplay = 0;
    	
    // Váriaveis de Controle Socket
    int iUserSocket;						// Váriavel Que armazena o Socket da PortUser
    bool iSckRx = false;					// Indica se Está processando alguma coisa pelo Socket.
    int iSckMaxBuffer = 128;				// Tamanho máximo do Buffer de Recebimento do Socket
    int iContGlobal = 0;
    
    // Váriaveis de Controle de I/O Digitais
    int iInput0 = 0;						// Botão Verde. Confirma) | Indica o Status de Cada Porta do Input (1 = Ativada / 0 = Desativada)
    int iInput1 = 0;						// Botão Preto. (Cancela)
    int iStepInput0 = 0;					// Identifica o Passo (Ação) Acumulada para o Botão Verde no momento da chamada
    int iStepInput1 = 0;					// Identifica o Passo (Ação) Acumulada para o Botão Preto no momento da chamada
    int iStepTimer = 0;
    
    // Várioveis de Controle de Erro
    int iErroID = 0;						// ID do Erro
    char strErro [50];						// Mensagem de Erro
    
    // Váriaveis de Pesagem
    unsigned char *cStatus;					// Indica se o Peso atual está em movimento ou é estabilizado
    unsigned int iEstavel=0;				// Indica se o Peso Atual da Balança é Peso EStabilizado (1) ou Em movimento (0)
    long lPeso = 0;							// Peso Atual da Balança
    long lPesoAtendido = 0;					// Cumulativo do Peso da Balança Para o Item
    long lPesoTara = 0;						// Tara Da Balança
    long lPesoDecrescente;					// Peso que é mostrado no Display Lamix, Descrescente, mostrando o que falta para concluir o Item
    long lPesoTotal;						// Peso Total contando a Tara (Pesagens Antecedentes) + Peso Atual
    long lPesoRequerida;					// Peso Requerido do Item contando com a Umidade
    long lTolMinima;						// Percentual Mínimo de Tolerância do Item na fórmula
    long lTolMaxima;						// Percentual Máximo de Tolerância do Item na fórmula
    int iTolerancia = -2;					// Identifica se o Peso está na tolerância permitida
    int iItemID = 0;						// Identifica a contagem do Item que está processando.
    int iPesaItem = 0;						// Pega Pesagem
    
    //unsigned char CD_FABRICA [5], BATCH_ID [11], CD_PESAGEM [9], CD_BALANCA [5], ITEM_DESC1 [12];		// Váriaveis do Pacote Ordem de Pesagem
    //unsigned char MATERIAL_DETAIL_ID [11], NR_SEQ_PESAGEM [3], CD_MATERIA_PRIMA [11], DS_ABREVIADA [11];	// Váriaveis do Pacote do Item da Ordem de Pesagem
    //unsigned char QT_REQUERIDA [12], PR_TOLERANCIA_MIN [6], PR_TOLERANCIA_MAX[6], ID_PESAR [2];			// .........
    
    unsigned char *CD_FABRICA, *BATCH_ID, *CD_PESAGEM, *CD_BALANCA, *ITEM_DESC1;			// Váriaveis do Pacote Ordem de Pesagem
    unsigned char *MATERIAL_DETAIL_ID, *NR_SEQ_PESAGEM, *CD_MATERIA_PRIMA, *DS_ABREVIADA;	// Váriaveis do Pacote do Item da Ordem de Pesagem
    unsigned char *QT_REQUERIDA, *PR_TOLERANCIA_MIN, *PR_TOLERANCIA_MAX, *ID_PESAR;			// .........
    unsigned char *PESOTOTAL;
    
    /*
    /************************************************************************\
    				Inicio das Funções do Aplicativo
    /************************************************************************\
    */
    
    /*
    void SckDebug (char *cMsgFinal)
    {
    	int iLen;
    		
    	if (iUserSocket){
    		sprintf (cMsgFinal, "[DEBUG]: %s", cMsgFinal);
    		VcomSendSocket(iUserSocket, cMsgFinal, iLen);	
    		
    		iLen = strlen (cMsgFinal);
    	}
    }
    */
    void TrataErros (void){
    	// Verifica a Ocorrência de Erro, exibe na saída e para aplicação
    	
    	if (iErroID != 0){
    		//printCom1 ("%d - %s", iErroID, strErro);
    		
    		RestoreCom(iComBalanca);
    		RestoreCom(iComDisplay);
    		
    		EscreveDisplay ("ERRO AO ABRIR SERIAL!");
    		
    		exit (EXIT_FAILURE);
    	}
    }
    
    void ClearStr ( char * pString )
    {
       *pString = '\0';
    }
    
    char *substr(const char *pstr, int start, int numchars) 
    {
    	char *pnew = malloc(numchars+1);
    	
    	strncpy(pnew, pstr + start, numchars);
    	pnew[numchars] = '\0';
    	return pnew;
    }
    
    int strpos (unsigned char *pStrText, char pChar){	// Última ocorrência do caractere.
    	
    	int iLen, iCont;
    	iLen = strlen (pStrText);
    
    	if (iLen > 0){
    		for (iCont=0; iCont<iLen; iCont++){
    			if (pStrText[iCont] ==  pChar)
    				return iCont;
    		}
    		return ERROR;	// Não houve ocorrências
    	}
    	else { return ERROR; }	// String Nula
    }
    
    int strrpos (unsigned char *pStrText, char pChar){	// Última ocorrência do caractere.
    	
    	int iLen, iCont;
    	iLen = strlen (pStrText);
    
    	if (iLen > 0){
    		for (iCont=iLen - 1; iCont>=0; iCont--){
    			if (pStrText[iCont] ==  pChar)
    				return iCont;
    		}
    		return ERROR;	// Não houve ocorrências
    	}
    	else { return ERROR; }	// String Nula
    }
    
    /*
    /************************************************************************\
    				Inicio das Funções de Comunicação
    /************************************************************************\
    */
    
    void IniciaSerial (void){	// Inicia (conecta) as portas Seriais do Equipamento
    	//
    	SetBaudrate(iComBalanca, 9600);
    	SetDataFormat(iComBalanca, 8, 0, 2);
    	//
    	InBuf = malloc (iMaxBuffer);	// Aloca Memória pra armazenar buffer;
    	//
    	iComBalOn  = InstallCom(iComBalanca, 9600, 8, 0, 2); 
    	if (iComBalOn == 0){
    		
    		ClearCom(iComBalanca);		// Limpa qualquer Buffer anteriormente Armazenado na Balança.
    		//printCom1 ("Conectado\n");
    		
    		SetBaudrate(iComDisplay, 2400);
    
    		iComDispOn = InstallCom(iComDisplay, 2400, 8, 0, 1); 
    		if (iComDispOn != 0){
    			iErroID = 2; strcpy (strErro, "Erro ao Conectar no Display.");
    		}
    	}
    	else { iErroID = 1; strcpy (strErro, "Erro ao Conectar na Balança."); }
    	
    	TrataErros ();
    }
    
    void IniciaMemoria (void){
    	CD_FABRICA = malloc (5);
    	BATCH_ID = malloc (11);
    	CD_PESAGEM = malloc (9);
    	CD_BALANCA = malloc (5);
    	ITEM_DESC1 = malloc (12);
    	MATERIAL_DETAIL_ID = malloc (11);
    	NR_SEQ_PESAGEM = malloc (3);
    	CD_MATERIA_PRIMA = malloc (11);
    	DS_ABREVIADA = malloc (11);
    	QT_REQUERIDA = malloc (6);
    	PR_TOLERANCIA_MIN = malloc (6);
    	PR_TOLERANCIA_MAX = malloc (6);
    	ID_PESAR = malloc (2);
    	PESOTOTAL = malloc (6);
    }
    
    int RecebeSerial(void){
    
        int iLenBuf, iMaxLocal, iReadReturn;
    	
    	if(IsCom(iComBalanca)){
    		iComBalRx = 1;
    		
    		if (strlen (InBuf) >= iMaxBuffer - 1){	// Limpa Buffer se Estiver Cheio
    			ClearStr (InBuf);
    		}
    		
    		iLenBuf = DataSizeInCom (iComBalanca);	
    		
    		if (iLenBuf +  strlen (InBuf) >= iMaxBuffer - 1){
    			ClearStr (InBuf);
    		}
    		if (iLenBuf >= iMaxBuffer - 1){
    			iLenBuf = iMaxBuffer - 1;
    		}
    		
    		iReadReturn = ReadComn(iComBalanca, InBuf, iLenBuf);
    		
    		InBuf [iLenBuf] = '\0';
    		
    		if (iReadReturn >= 0){	
    			iComBalRx = 0;
    			if (iLenBuf == 17)
    			{
    				ProcessaBuffer ();
    			}
    		}
    		
    		return SUCCESS;
    	}
    	
    	return ERROR;
    }
    
    void VerificaBotoes (void){			// Verifica o Pressionamento de Algum botão através das I/O Digitais
    	unsigned char DI;
    	char lc_botao [1];
    	
    	DI = inportb(0);
    	sprintf (lc_botao, "%x", DI);	// Converte para Hexadecimal o Valor. 
    	
    	switch (lc_botao[0]){
    		case 'e':					// Pressionado Botão 1 (Verde)
    			iInput0 = 1;
    			AcaoBotaoConfirma ();
    			break;
    		case 'd':					// Pressionado Botão 2 (Preto)
    			iInput1 = 1;
    			AcaoBotaoCancela ();
    			break;
    		default:
    			break;
    	}	
    }
    
    void EnviaPedidoPC (unsigned char *pChar, int pTamanho){
    	
    	unsigned char *cMsgFinal = malloc(pTamanho + 1);
    	int iLen;
    		
    	if (iUserSocket){
    		sprintf(cMsgFinal, "%c%s%c%c", cSTX, pChar, cCR, cLF);	// Formata Pacote
    	
    		iLen = strlen (cMsgFinal);
    		
    		VcomSendSocket(iUserSocket, cMsgFinal, iLen);	
    		//printCom1 ("EnviaPedidoPC: %s", pChar);
    	}
    }
    
    void Fila (unsigned int pFuncao){		// Controle do Enfileiramento de Comunicação
    	switch (pFuncao){
    		case VER:
    			break;
    		case ADD:
    			break;
    		case REM:
    			break;
    	}
    }
    
    /*
    /************************************************************************\
    				Inicio das Funções de Processamento
    /************************************************************************\
    */
    
    int DevolvePesagem (void){
    	unsigned char *cStr = malloc (30);
    	
    	lPesoTotal = lPesoRequerida;
    	
    	sprintf (cStr, "OIRS\t%s\t%s\t%d", MATERIAL_DETAIL_ID, CD_MATERIA_PRIMA, lPesoTotal);
    	
    	//printCom1 (cStr);
    	
    	EnviaPedidoPC (cStr, strlen(cStr));		
    	
    	return SUCCESS;
    }
    
    void Validatolerancia (void){
    	
    	if (ID_PESAR[0]=='1'){	
    	
    		if (lPesoAtendido >= lTolMinima && lPesoAtendido <= lTolMaxima){
    			iTolerancia = 0;	// OK
    			//EscreveDisplay ("PESO OK");
    			//iStepInput0 = 4;
    		}
    		else if (lPesoAtendido < lTolMinima){
    			iTolerancia = -1;	// Faltando
    			EscreveDisplay ("PESO ABAIXO");
    		}
    		else if (lPesoAtendido > lTolMaxima){
    			iTolerancia = 1;	// Sobrando
    			EscreveDisplay ("PESO ACIMA");
    		}
    	}
    	else
    	{
    		iTolerancia = 0;
    	}
    }
    
    int VerificaBalancaVazia (void){		// Verifica se a Balança está preparada pra Pesagem. -1 Negativo | 1 - OK  | 0 Esvazie Balança (WARNING)
    	
    	return SUCCESS;
    
    	/*
    	if (lPeso >= -10 && lPeso <= 10){	// Peso 0
    		//EscreveDisplay ("BALANCA VAZIA");
    		return SUCCESS;
    	}
    	else if (lPeso < -10){
    		EscreveDisplay ("PESO NEGATIVO");
    		return ERROR;
    	}
    	else{
    		EscreveDisplay ("ESVAZIE A BALANCA");
    		return WARNING;
    	}
    	*/
    }
    
    void AcaoBotaoConfirma (void){
    	if (iInput0 == 1){
    		if (iStepTimer>=10)
    			iStepTimer = 0;
    			
    		if (iStepTimer==0){	
    			iStepTimer++;
    			switch (iStepInput0){
    				case 0:
    					// Requisição de OP
    					EnviaPedidoPC ("OPSL", 4);
    					break;
    				case 1:
    					// Valida Tolerância / Conclui Pesagem de Item
    					Validatolerancia ();
    					break;
    				case 2: 
    					//  Confirma Cancelar Item
    					iStepInput0 = 1;
    					iStepInput1 = 0;
    					EnviaPedidoPC ("OISL", 4);	
    					break;
    				case 3: 
    					// Confirma Cancelar Carga
    					iStepInput0 = 0;
    					iStepInput1 = 0;
    					EnviaPedidoPC ("OPCN", 4);
    					EscreveDisplay ("ORDEM CANCELADA");
    					break;
    				case 4: 
    					// Ordem Concluída.
    					iStepInput0 = 0;
    					EscreveDisplay ("ORDEM CONCLUIDA");
    					break;
    				case 5:
    					iStepInput0 = 1;
    					break;
    				default:
    					break;
    			}
    		}
    	}
    	iInput0 = 0;
    }
    
    void AcaoBotaoCancela (void){
    	if (iInput1 == 1){
    		switch (iStepInput1){
    			case 0:
    				// Pede Para Cancela Item
    				iStepInput0 = 2;
    				iStepInput1 = 1;
    				iPesaItem = 0;
    				EscreveDisplay ("CANCELAR ITEM");
    				break;
    			case 1:
    				// Cancelar Ordem ?
    				iStepInput0 = 3;
    				iStepInput1 = 2;
    				EscreveDisplay ("CANCELAR ORDEM");
    				break;
    			case 2: 
    				// Anula Cancelamento.
    				iStepInput0 = 1;
    				iStepInput1 = 0;
    				iPesaItem = 1;
    				break;
    			case 3:
    				// Cancela Produto Extra
    				iStepInput0 = 0;
    				iStepInput1 = 0;
    				EscreveDisplay ("ORDEM CONCLUIDA");
    				break;
    			default:
    				break;
    		}
    	}
    	iInput1 = 0;
    } 
    
    void PesaItem (void){
    
    	unsigned char *PacotePeso;
    	unsigned char *PesoDisplay;
    	
    	if (ID_PESAR[0]=='1'){	
    		lPesoAtendido    = lPeso - lPesoTara;
    		lPesoTotal       = lPesoTara + lPeso;
    		lPesoDecrescente = lPesoRequerida - lPesoAtendido;
    		sprintf (PesoDisplay,  "PESO: %d", lPesoDecrescente);
    	
    		if (iTempoDisplay >= 25){
    			EscreveDisplay (PesoDisplay);
    			iTempoDisplay= 0;
    		}
    	}
    	else{
    		lPesoAtendido = lPesoRequerida;
    	}
    	
    	if (iTolerancia == 0){
    		iPesaItem = 0;
    		iTolerancia = -2;
    		if (DevolvePesagem () == 1){
    		}
    		//break;
    	}
    }
    
    void OrdemProducao (unsigned char *pOP){	//OP	CD_FABRICA	BATCH_ID	CD_PESAGEM	CD_BALANCA	ITEM_DESC1
    	
    	unsigned char *cValor = NULL;
    	int iTab, iCont=1;
    	
    	ClearStr (CD_FABRICA);
    	ClearStr (CD_PESAGEM);
    	ClearStr (CD_BALANCA);
    	ClearStr (ITEM_DESC1);
    	
    	cValor = strtok(pOP, "\t"); 	// Procura Pelo TAB
    	
    	while (cValor){
    			switch (iCont){
    				case 1:
    					strcpy (CD_FABRICA, cValor);
    					//printCom1("CD_FABRICA %s",CD_FABRICA);
    					break;
    				case 2:
    					strcpy (BATCH_ID,cValor);
    					//printCom1("BATCH_ID %s",BATCH_ID);
    					break;
    				case 3:
    					strcpy (CD_PESAGEM,cValor);
    					//printCom1("CD_PESAGEM %s",CD_PESAGEM);
    					break;
    				case 4:
    					 strcpy (CD_BALANCA,cValor);
    					 //printCom1("CD_BALANCA %s",CD_BALANCA);
    					 break;
    				case 5:
    					strcpy (ITEM_DESC1,cValor);
    					//printCom1("ITEM_DESC1 %s", ITEM_DESC1);
    					break;
    				default:
    					//printCom1("valor %s", cValor);
    					break;
    			}
    			cValor = strtok(NULL, "\t");
    			iCont++;
    	}
    	
    	iStepInput0 = 1;
    	EnviaPedidoPC ("OKOP", 4);
    	//EscreveDisplay (ITEM_DESC1);	
    }
    
    void OrdemProducaoItem (unsigned char *pOPItem){	//MATERIAL_DETAIL_ID / NR_SEQ_PESAGEM / CD_MATERIA_PRIMA/ DS_ABREVIADA / QT_REQUERIDA / PR_TOLERANCIA_MIN / PR_TOLERANCIA_MAX / ID_PESAR
    	
    	unsigned char *cValor = NULL;
    	int iTab, iCont=1;
    	
    	/*
    	ClearStr (MATERIAL_DETAIL_ID);
    	ClearStr (NR_SEQ_PESAGEM);
    	ClearStr (CD_MATERIA_PRIMA);
    	ClearStr (DS_ABREVIADA);
    	ClearStr (QT_REQUERIDA);
    	ClearStr (PR_TOLERANCIA_MIN);
    	ClearStr (PR_TOLERANCIA_MAX);
    	ClearStr (ID_PESAR);
    	*/
    	
    	cValor = strtok(pOPItem, "\t"); 	// Procura Pelo TAB
    	
    	while (cValor){
    			switch (iCont){
    				case 1:
    					strcpy (MATERIAL_DETAIL_ID, cValor);
    					break;
    				case 2:
    					strcpy (NR_SEQ_PESAGEM,cValor);
    					break;
    				case 3:
    					strcpy (CD_MATERIA_PRIMA,cValor);
    					break;
    				case 4:
    					strcpy (DS_ABREVIADA,cValor);
    					break;
    				case 5:
    					 strcpy (QT_REQUERIDA,cValor);
    					 lPesoRequerida = strtol (QT_REQUERIDA, NULL, 10);
    					 break;
    				case 6:
    					strcpy (PR_TOLERANCIA_MIN,cValor);
    					lTolMinima = strtol (PR_TOLERANCIA_MIN, NULL, 10);
    					break;
    				case 7:
    					strcpy (PR_TOLERANCIA_MAX,cValor);
    					lTolMaxima = strtol (PR_TOLERANCIA_MAX, NULL, 10);
    					break;
    				case 8:
    					strcpy (ID_PESAR,cValor);
    					break;
    				default:
    					break;
    			}
    			cValor = strtok(NULL, "\t");
    			iCont++;
    	}
    	
    	iItemID++;
    	
    	EnviaPedidoPC ("OKOI", 4);
    	EscreveDisplay (DS_ABREVIADA);	
    }
    
    int ProcessaChamado (unsigned char *pPacote, int pLen){
    	
    	unsigned char *cFuncao;
    	unsigned char *cSubFuncao;
    	unsigned char *cPacote = malloc(pLen);
    	unsigned char *strDisplay;
    	
    	int iPosStart, iPosEnd, iPosTam;
    	
    	if (cPacote == NULL)
    		//printCom1 ("Não foi Possível Alocar Memória: ProcessaChamado");
    	
    	iComBalRx = 1;
    	
    	//Separa o Pacote
    	iPosStart = strpos (pPacote, cSTX);
    	iPosStart++;
    	
    	iPosEnd = strpos (pPacote, cCR);
    	
    	iPosTam = iPosEnd - iPosStart;
    	
    	////printCom1 ("CHAMADO %s", pPacote);
    	
    	if((iPosStart >= 0) && (iPosEnd)){
    		cPacote = substr(pPacote, iPosStart, iPosTam);
    	
    		if(strlen (cPacote) > 0){
    						
    			cFuncao = substr(cPacote, 0, 2);
    			
    			if (strcmp (cFuncao, "OP") == 0){								// Recebe Ordem de Pesagem
    				OrdemProducao (substr (cPacote, 3, iPosTam - 2));
    			}
    			else if (strcmp (cFuncao, "OI") == 0){							// Recebe Ordem de Pesagem Item
    				OrdemProducaoItem (substr (cPacote, 2, iPosTam - 2));
    			}
    			else if (strcmp (cFuncao, "OK") == 0){							// Tratamento de Confirmações
    				cSubFuncao = substr (cPacote,2, 2);	
    				if (strcmp (cSubFuncao, "OP") == 0)	{						// Recebe Confirmação de Ordem de Pesagem
    					EnviaPedidoPC ("OISL", 4);		
    				}
    				else if (strcmp (cSubFuncao, "OI") == 0){					// Recebe Confirmação de Ordem de Pesagem Item
    					if (iItemID == 1)
    						while (VerificaBalancaVazia () != 1){
    						}
    					lPesoTara = lPeso;
    					iPesaItem = 1;
    				}
    				else if (strcmp (cSubFuncao, "IR") == 0){					// Recebe Confirmação de Entrega de Resposta de Item 
    					EnviaPedidoPC ("OISL", 4);
    				}
    			}
    			else if (strcmp (cFuncao, "FI") == 0){							// Recebe Finaliza Item Indicando que Recebeu Todos Itens da OP
    					iStepInput0 = 4;
    					EnviaPedidoPC ("OPFI", 4);
    					EscreveDisplay ("PRODUTO EXTRA");
    					//Limpa Váriaveis
    			}
    			else if (strcmp (cFuncao, "ER") == 0){							// Erro do Objeto de Comunicação
    				//sprintf (strDisplay, "ERRO: %s", cPacote);
    				EscreveDisplay (substr (cPacote, 3, iPosTam - 2));
    				iStepInput0 = 0;
    			}
    			else if (strcmp (cFuncao, "CC") == 0){							// Check Connection
    				////printCom1 ("CheckConnection");
    			}
    			else{
    				////printCom1 ("\n[PACOTE N IDENTIFICADO] %s", cPacote);
    			}
    		} 
    		else { 
    			iSckRx = false;
    			return 0;
    		}
    	}
    	else { } ////printCom1 ("[PACOTE][STX]: %d [CR] %d [PACOTE]: %s", iPosStart, iPosEnd, pPacote); }
    	
    	iComBalRx = 0;
    	iSckRx = false;
    	
    	return 1;
    }
    
    void EscreveDisplay (unsigned char *pMensagem){
    	unsigned char cPacote [51];
    	unsigned int iLims;
    	unsigned int iLenMsg, iLenCont, iContIndex;
    	int iBcc;
    
    	iLims  = 46;
    	
    	cPacote [0] = 129;
    	cPacote [1] = 126;
    	cPacote [2] = iLims % 256;
    	cPacote [3] = iLims / 256;
    	cPacote [4] = 1 % 256;
    	cPacote [5] = 1 / 256;
    	cPacote [6] = 0 % 256;
    	cPacote [7] = 0 / 256;
    	cPacote [8] = 76;
    	cPacote [9] = 202;
    		
    	iLenMsg = strlen (pMensagem);
    
    	if (iLenMsg > 40)
    		iLenMsg = 40;
    
    	if (iLenMsg < 40){
    		for(iLenCont=iLenMsg; iLenCont<40; iLenCont++)
    			strcat (pMensagem, ".");
    	}
    
    	
    	for(iLenCont=0; iLenCont<40; iLenCont++){
    		iContIndex = iLenCont + 10;
    		cPacote [iContIndex] = pMensagem [iLenCont];
    	}
    	
    	iBcc = cPacote [4];
    	cPacote [50] = iBcc;
    	cPacote [51] = '\0';
    	
    	for(iContIndex=0; iContIndex<=51; iContIndex++){
    		ToCom (iComDisplay, cPacote[iContIndex]);
    	}
    
    	////printCom1 (pMensagem);
    	//ClearStr (cPacote);
    }
    
    void ProcessaBuffer (){
    
    	//int iFlag;
    	//char cMovto, cNegativo, cResolucao;
    	unsigned char *cPacote, *cPeso;
    	//unsigned char cByte;
    	int iCont;
    	int iPosStart, iPosEnd, iPosTam; 
    
    	//strcpy (pInBuf, InBuf);		// Transfere para Buffer Local
    	//strcpy (InBuf, "");			// Limpa Buffer Global
    
    	iPosStart = strrpos (InBuf, cSTX);
    	if(iPosStart >= 0) 
    		iPosStart++;
    	
    	iPosEnd = strrpos (InBuf, cCR);
    	
    	iPosTam = iPosEnd - iPosStart;
    		
    	if((iPosStart >= 0) && (iPosEnd) && (iPosTam == 15)){
    
    		cPacote = substr(InBuf, iPosStart, iPosTam);
    		cStatus = substr(cPacote, 1, 1);
    		cPeso   = substr(cPacote, 3, 6);
    												
    		lPeso = strtod (cPeso, NULL);
    
    	}
    	
    	ClearStr (InBuf);
    }
    
    /*
    /************************************************************************\
    				Inicio da Estrutura X-Server (Main do Programa)
    /************************************************************************\
    */
    
    void UserCount(void)
    {
    
    	if(iComBalRx == 0){
    		RecebeSerial ();
    	}
    	
    	VerificaBotoes ();
    	
    	if (iPesaItem == 1){
    		PesaItem ();
    	}
    	
    	if (iStepTimer >= 1 && iStepTimer < 10)
    		iStepTimer++;
    	
    	iTempoDisplay++;
    }
    
    void UserInit(void)
    {
    	InitLib();
    
    	IniciaSerial ();
    	IniciaMemoria();
    	
    	PortUser = 5050;	// Habilita porta 5050 para Controle do Usuário (Aplicação Objeto de Comunicação (Listener))
    	
    	// Transforma os Int em Char (ASCII)
    	cSTX = STX;
    	cCR  = CR;
    	cLF  = LF;
    	cTab = TAB;
    	
    	EscreveDisplay ("LENKE AUTOMACAO");
    	
        AddUserTimerFunction(UserCount, 200); // Adiciona  Timer para Chamar Função UserCount a cada 100 ms
    	
    }
    
    void UserLoopFun(void)
    {
    	// Loop Principal do Programa
    }
    
    int UserCmd(unsigned char *Cmd,unsigned char *Response)
    {
    	// Ao Receber qualquer comando na porta 10000, Responde com o que Recebeu
    	strcpy (Response, Cmd);
        return 1;
    }
    
    
    int VcomUserBinaryCmd(TCPREADDATA *p)
    {
    	VcomSendSocket(p->Socket,p->ReadUartChar,p->Length);
        return 1;
    }
    
    int VcomCmdUser(TCPREADDATA *p)  	// Processa as Entradas Recebidas Pelo Usuário. (Obj. Comunicação
    { 	
    	if (!iSckRx){
    		if (p->Length >= 4 && p->Length <= iSckMaxBuffer){	// Pelo Menos 4 Caracteres [STX]XX[13][10]
    			
    			iSckRx = true;	
    			if (ProcessaChamado (p->ReadUartChar, p->Length)){
    				if (!iSckRx)
    					ClearStr (p->ReadUartChar);
    			}
    		}		
    	}
    	return 1;  
    }
    
    void PortUserStart(int skt)
    {
    	// Procedimentos a serem executados
    	// Quando for iniciado a Porta definida pelo usuário
    	iUserSocket = skt;
        skt=skt; //do nothing 
    	
    }
      
    void Port9999Start(int skt)
    {
        skt=skt; //do nothing
    }
     
    void Port502Start(int skt)
    { 
        skt=skt; //do nothing
    }

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    We don't "analyze programs for wrong codes".

    We help programmers who can tell us what is going wrong with their code. It saves both of us a lot of time and work, that way.

    Are you getting a wrong result from the program? What is the wrong result, and what should the right result be? What input produced in your program, the wrong result?

  3. #3
    Registered User
    Join Date
    Nov 2008
    Location
    Santa Catarina - Brasil
    Posts
    184
    the result is ok,

    but i'm not know if the memory (pointers, strings, etc) is the better way, and will run all time ok.

    (sorry for my english)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can someome help me with a program please?
    By WinterInChicago in forum C++ Programming
    Replies: 3
    Last Post: 09-21-2006, 10:58 PM
  2. Making Program Launch Full Screen
    By mrtechguy in forum C++ Programming
    Replies: 19
    Last Post: 03-15-2006, 02:06 AM
  3. I need some help with my program please.
    By agentxx04 in forum C Programming
    Replies: 9
    Last Post: 09-26-2004, 07:51 AM
  4. simple frontend program problem
    By gandalf_bar in forum Linux Programming
    Replies: 16
    Last Post: 04-22-2004, 06:33 AM
  5. My program, anyhelp
    By @licomb in forum C Programming
    Replies: 14
    Last Post: 08-14-2001, 10:04 PM