Serial data crazy (help !)



Hello all, 
I'm developing an aplication that makes serial communication with a
device (LCD terminal) that has a specific protocol (it's simple), I made
a gdk_input_add with the file descriptor pointing to a function named
le_serial, in that function it write a GtkText in front-end and send
this data to another function that "assembly" one complete frame and
send this frame to another function that interprets and answer the
device, the problem occurs when the GtkText is "filled" with text,
appears many (not randomnly) strange characters appears in variable and
when I click in some button in Gtk interface the label of button is
passed to this variable buffer that has the serial data assembled by
other function and printed in xterm (I put some printf's in program to
see that happens),
I send part of the source of program to you, I put printf's behind
simular_plc is called and as the first command inside simular_plc and
the variable has the correct value behind the function, but inside
function the value is incorrect,
If I comment gtk_text_insert( ) that writes GtkText the problem of wrong
data is fixed (almost fixed) (but I don't see nothing in GtkText ), but
if I pass the cursor in some button in my window program, I see the
label writed in xterm that I called the program, I don't konw what to do
and nothing that Imake it seems make sense, What I do ?

Any help or tip are fully appreciated
Thanks a lot


-- 
Flavio Alberto Lopes Soares
flavio maqplas com br
Linux User n. 257636

MAQPLAS INDÚSTRIA E COMÉRCIO DE MÁQUINAS LTDA.
www.maqplas.com.br
maqplas maqplas com br
#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

#include <gdk/gdk.h>
#include <gnome.h>

#include "callbacks.h"
#include "interface.h"
#include "support.h"

#include "plecsimul.h"
#include "serial.h"

int ind_le;

gboolean stop_bits = FALSE;
gboolean parity = FALSE;
gboolean paridade_par = FALSE;
gboolean cts_rts = FALSE;
gboolean xonxoff = FALSE;
char caminho_serial[32] = {"/dev/ttyS0"}; 
int databits = 8;
int veloc_serial = 6;
int fd; /* DESCRITOR DE ARQUIVOS PARA A PORTA SERIAL */

char mess_to_send[258] = {""};
int acende_led = 0;
int apaga_led = 0;

/*char comando[2048];*/
/*char *comando;*/

int num_plc;

char modelo_plc[32];

gboolean le_num = TRUE;
gboolean envia_num = TRUE;
gboolean le_hex = TRUE;
gboolean envia_hex = TRUE;
gboolean send_CR = FALSE;
gboolean ja_iniciado = FALSE;
gboolean simula_plc = FALSE;

extern  GtkWidget *window_plc_princ;

void
on_entry_envia_changed                 (GtkEditable     *editable,
                                        gpointer         user_data)
{

  strcpy(mess_to_send, gtk_entry_get_text(GTK_ENTRY(editable)));

}


void
on_button_le_inicia_clicked            (GtkButton       *button,
                                        gpointer         user_data)
{
  if(fd > 0)
    {
      if((ind_le <= 0) && (ja_iniciado == FALSE))
	{
	  apaga_com(fd);
	  ind_le = gdk_input_add(fd, GDK_INPUT_READ,  (GdkInputFunction) le_serial, user_data);
	  ja_iniciado = TRUE;
	}
    }
  else ind_le = 0;
}


void
on_button_le_para_clicked              (GtkButton       *button,
                                        gpointer         user_data)
{
  if(ja_iniciado == TRUE)
    {
      apaga_com(fd);
      gdk_input_remove(ind_le);
      ind_le = 0;
      ja_iniciado = FALSE;
    }
}


void
on_button_file_clicked                 (GtkButton       *button,
                                        gpointer         user_data)
{

}


void
on_radiobutton_numero_toggled          (GtkToggleButton *togglebutton,
                                        gpointer         user_data)
{

  GtkWidget *toggle1;
  GtkWidget *toggle2;

  toggle1 = lookup_widget(window_plc_princ, "radiobutton_num_hexa");
  toggle2 = lookup_widget(window_plc_princ, "radiobutton_num_dec");

    gtk_widget_show(toggle1);
    gtk_widget_show(toggle2);

  envia_num = TRUE;

}


void
on_radiobutton_ascii_toggled           (GtkToggleButton *togglebutton,
                                        gpointer         user_data)
{

  GtkWidget *toggle1;
  GtkWidget *toggle2;

  toggle1 = lookup_widget(window_plc_princ, "radiobutton_num_hexa");
  toggle2 = lookup_widget(window_plc_princ, "radiobutton_num_dec");

    gtk_widget_hide(toggle1);
    gtk_widget_hide(toggle2);

  envia_num = FALSE;

}


void
on_radiobutton_num_hexa_toggled        (GtkToggleButton *togglebutton,
                                        gpointer         user_data)
{

  envia_hex = TRUE;

}


void
on_radiobutton_num_dec_toggled         (GtkToggleButton *togglebutton,
                                        gpointer         user_data)
{

  envia_hex = FALSE;

}


void
on_radiobutton_leitura_hex_toggled     (GtkToggleButton *togglebutton,
                                        gpointer         user_data)
{

  le_hex = TRUE;

}


void
on_radiobutton_leitura_dec_toggled     (GtkToggleButton *togglebutton,
                                        gpointer         user_data)
{

  le_hex = FALSE;

}


void
on_togglebutton_simula_plc_toggled     (GtkToggleButton *togglebutton,
                                        gpointer         user_data)
{
  GtkWidget *editable;

  if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(togglebutton)) == TRUE)
    simula_plc = TRUE;
  else
    simula_plc = FALSE;

  editable = lookup_widget(window_plc_princ, "combo_entry_plc_model");

  strcpy(modelo_plc, gtk_entry_get_text(GTK_ENTRY(editable)));
}


void
on_radiobutton_1stopbits_toggled       (GtkToggleButton *togglebutton,
                                        gpointer         user_data)
{
  stop_bits = FALSE;
}


void
on_radiobutton_com3_toggled            (GtkToggleButton *togglebutton,
                                        gpointer         user_data)
{
  strcpy(caminho_serial, "/dev/ttyS2");
}


void
on_radiobutton_com4_toggled            (GtkToggleButton *togglebutton,
                                        gpointer         user_data)
{
  strcpy(caminho_serial, "/dev/ttyS3");
}


void
on_radiobutton_databits5_toggled       (GtkToggleButton *togglebutton,
                                        gpointer         user_data)
{
  databits = 5;
}


void
on_radiobutton_databits6_toggled       (GtkToggleButton *togglebutton,
                                        gpointer         user_data)
{
  databits = 6;
}


void
on_radiobutton_databits7_toggled       (GtkToggleButton *togglebutton,
                                        gpointer         user_data)
{
  databits = 7;
}


void
on_radiobutton_databits8_toggled       (GtkToggleButton *togglebutton,
                                        gpointer         user_data)
{
  databits = 8;
}


void
on_radiobutton_com1_toggled            (GtkToggleButton *togglebutton,
                                        gpointer         user_data)
{
  strcpy(caminho_serial, "/dev/ttyS0");
}


void
on_radiobutton_2stopbits_toggled       (GtkToggleButton *togglebutton,
                                        gpointer         user_data)
{
  stop_bits = TRUE;
}


void
on_radiobutton_paridade_no_toggled     (GtkToggleButton *togglebutton,
                                        gpointer         user_data)
{
  parity = FALSE;
}


void
on_radiobutton_paridade_par_toggled    (GtkToggleButton *togglebutton,
                                        gpointer         user_data)
{
  parity = TRUE;
  paridade_par = TRUE;
}


void
on_radiobutton_paridade_impar_toggled  (GtkToggleButton *togglebutton,
                                        gpointer         user_data)
{
  parity = TRUE;
  paridade_par = FALSE;
}


void
on_radiobutton_fluxo_rtscts_toggled    (GtkToggleButton *togglebutton,
                                        gpointer         user_data)
{
  cts_rts = TRUE;
  xonxoff = FALSE;
}


void
on_radiobutton_fluxo_XonXof_toggled    (GtkToggleButton *togglebutton,
                                        gpointer         user_data)
{
  cts_rts = FALSE;
  xonxoff = TRUE;
}


void
on_radiobutton_fluxo_no_toggled        (GtkToggleButton *togglebutton,
                                        gpointer         user_data)
{
  cts_rts = FALSE;
  xonxoff = FALSE;
}


void
on_togglebutton_send_CR_toggled        (GtkToggleButton *togglebutton,
                                        gpointer         user_data)
{

  if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(togglebutton)) == TRUE)
    send_CR = TRUE;
  else
    send_CR = FALSE;

}


void
on_button_serial_abre_clicked          (GtkButton       *button,
                                        gpointer         user_data)
{
  if(fd <= 0)
    {
      fd = abre_com (caminho_serial, veloc_serial, cts_rts, xonxoff, databits, stop_bits, parity, paridade_par);
      gtk_label_set_text(GTK_LABEL(user_data), "SERIAL ABERTA");

      troca_pixmap(window_plc_princ, "pixmap_serial_on", "plecsimul/led_verde.xpm", FALSE, NULL);
      write(fd, "PORTA SERIAL ABERTA", strlen("PORTA SERIAL ABERTA"));
    }
}


void
on_button_serial_fecha_clicked         (GtkButton       *button,
                                        gpointer         user_data)
{

  /* write(fd, "FECHANDO PORTA SERIAL", strlen("FECHANDO PORTA SERIAL"));*/

  /*apaga_com(fd);*/

  if(fd > 0)
    {
      gdk_input_remove(ind_le);
      fd = fecha_com(fd);
      ind_le = 0;
    }

  if(fd <= 0)
    {
      gtk_label_set_text(GTK_LABEL(user_data), "SERIAL FECHADA");
      troca_pixmap(window_plc_princ, "pixmap_serial_on", "plecsimul/led_vermelho.xpm", FALSE, NULL);
    }

  ja_iniciado = FALSE;

}


void
on_radiobutton_com2_toggled            (GtkToggleButton *togglebutton,
                                        gpointer         user_data)
{
  strcpy(caminho_serial, "/dev/ttyS1");
}


void
on_radiobutton_le_num_toggled          (GtkToggleButton *togglebutton,
                                        gpointer         user_data)
{
  GtkWidget *toggle1;
  GtkWidget *toggle2;

  toggle1 = lookup_widget(window_plc_princ, "radiobutton_leitura_hex");
  toggle2 = lookup_widget(window_plc_princ, "radiobutton_leitura_dec");

    gtk_widget_show(toggle1);
    gtk_widget_show(toggle2);

  le_num = TRUE;

}


void
on_radiobutton_le_text_toggled         (GtkToggleButton *togglebutton,
                                        gpointer         user_data)
{

  GtkWidget *toggle1;
  GtkWidget *toggle2;

  toggle1 = lookup_widget(window_plc_princ, "radiobutton_leitura_hex");
  toggle2 = lookup_widget(window_plc_princ, "radiobutton_leitura_dec");

    gtk_widget_hide(toggle1);
    gtk_widget_hide(toggle2);

  le_num = FALSE;

}


void
on_combo_entry_plc_model_activate      (GtkEditable     *editable,
                                        gpointer         user_data)
{
  strcpy(modelo_plc, gtk_entry_get_text(GTK_ENTRY(editable)));
}


void
on_combo_entry_plc_model_changed       (GtkEditable     *editable,
                                        gpointer         user_data)
{
  strcpy(modelo_plc, gtk_entry_get_text(GTK_ENTRY(editable)));
}


void
on_button_envia_clicked                (GtkButton       *button,
                                        gpointer         user_data)
{
  /* char data_send[257]; */

  char *data_send;
  int tamanho = 0;
  GtkWidget *label;
  unsigned char chks;
  char chks_char[4];

  data_send = (char *)malloc(sizeof(char) * 256);

  tamanho = strlen(mess_to_send);

  if(envia_num == TRUE)
    {
      separa_num (mess_to_send, data_send, &tamanho, envia_hex);
      // tamanho--;
    }
  else
    strcpy(data_send, mess_to_send);

  label = lookup_widget(window_plc_princ, "entry_chksum_envia");

  chks = checksum(data_send, tamanho);

  sprintf(chks_char,"%d", chks);

  gtk_entry_set_text(GTK_ENTRY(label), chks_char);

  sprintf(chks_char, "%X", chks);

  envia_string(data_send, tamanho, fd);

  if(send_CR == TRUE)
    {
      if(chks > 0x0F) /* SE O CHECKSUM FOR MAIOR QUE 0x0F ENVIA NA ORDEM NORMAL */
	{
	  envia_um_byte(chks_char[0], fd);
	  envia_um_byte(chks_char[1], fd);
	}
      /* SE O CHECKSUM FOR MENOR QUE 0x0F ENVIA PRIMEIRO O CARACTER 0 (ZERO) DEPOIS O BYTE MENOS SIGNIFICATIVO */
      else 
	{
	  envia_um_byte('0', fd);
	  envia_um_byte(chks_char[0], fd);
	}

      envia_um_byte(0x0D, fd);
    }

  free(data_send);

}


void
on_button_sai_clicked                  (GtkButton       *button,
                                        gpointer         user_data)
{
  if(fd > 0)
  fecha_com(fd);
  gtk_main_quit();
}


void
on_combo_entry_serial_vel_activate     (GtkEditable     *editable,
                                        gpointer         user_data)
{
  char *string;
  string = gtk_entry_get_text(GTK_ENTRY(editable));
  define_veloc(string);
}


void
on_combo_entry_serial_vel_changed      (GtkEditable     *editable,
                                        gpointer         user_data)
{
  char *string;
  string = gtk_entry_get_text(GTK_ENTRY(editable));
  define_veloc(string);
}

int
define_veloc(char *palavra) 
{

  if(!strcmp(palavra, "300 bps")) 
    {
      veloc_serial = 1;
      return 0;
    }
  if(!strcmp(palavra, "600 bps")) 
    {
      veloc_serial = 2;
      return 0;
    }
  if(!strcmp(palavra, "1200 bps")) 
    {
      veloc_serial = 3;
      return 0;
    }
  if(!strcmp(palavra, "2400 bps")) 
    {
      veloc_serial = 4;
      return 0;
    }
  if(!strcmp(palavra, "4800 bps")) 
    {
      veloc_serial = 5;
      return 0;
    }
  if(!strcmp(palavra, "9600 bps")) 
    {
      veloc_serial = 6;
      return 0;
    }
  if(!strcmp(palavra, "19200 bps")) 
    {
      veloc_serial = 7;
      return 0;
    }
  if(!strcmp(palavra, "38400 bps")) 
    {
      veloc_serial = 8;
      return 0;
    }
  if(!strcmp(palavra, "57600 bps")) 
    {
      veloc_serial = 9;
      return 0;
    }
  if(!strcmp(palavra, "115200 bps")) 
    {
      veloc_serial = 10;
      return 0;
    }

  veloc_serial = 6; /* se nao for nenhum destes ficara o padrao 9600 bps */
  return -1;

}


gboolean
on_window_plc_princ_destroy_event      (GtkWidget       *widget,
                                        GdkEvent        *event,
                                        gpointer         user_data)
{
  gtk_widget_destroy(widget);

  on_button_sai_clicked  (NULL, NULL);

  return FALSE;
}


int
le_serial(gpointer data, gint source, GdkInputCondition condition)
{

  char *comando;
  char chk_char[8];
  static unsigned char chk_sum;
  GtkWidget *entry_chk;
  int readcont;
  unsigned char buff[2];
  char valor[4];

  comando = malloc(2048 * sizeof(char));
  if(!comando)
    exit(-1);

  acende_led = 0;
  apaga_led = 0;

  readcont = le_um_byte(&buff[0], fd);

  buff[1] = '\0';

  if(readcont < 0)
    {
      free(comando);
      return -1;
    }
  if (le_num == TRUE)
   {
     if(le_hex == FALSE)
       sprintf(&valor[0], " %d", buff[0]);
     else
       sprintf(&valor[0], " %X", buff[0]);
   }
  else
    {
      valor[0] = buff[0];

      valor[1] = buff[1];
    }

  chk_sum ^= buff[0];


  sprintf(&chk_char[0], "%d", chk_sum);

  // gtk_text_insert (GTK_TEXT (data), NULL, NULL, NULL, valor, -1);

  entry_chk = lookup_widget(window_plc_princ, "entry_chksum_recebe");

  gtk_entry_set_text(GTK_ENTRY(entry_chk), &chk_char[0]);
  
  if(simula_plc == TRUE)
    {  
      if(monta_comando_plc(&buff[0], &modelo_plc[0], comando, &num_plc))
	simular_plc(&modelo_plc[0], comando, &num_plc, fd);
    }
  /*  espera_time_pisca_led(20); */

  free(comando);
  return 0;
}


void
on_button_limpa_tela_clicked           (GtkButton       *button,
                                        gpointer         user_data)
{

  gtk_text_backward_delete        (GTK_TEXT(user_data), gtk_text_get_length(GTK_TEXT(user_data)));

}



int
espera_time_pisca_led(gint32 lapso)
{
  acende_led = gtk_timeout_add(lapso,  (GtkFunction) led_on, NULL);

  return 0;
}

int
led_on(void)
{
 troca_pixmap(window_plc_princ, "pixmap_led_rx", "plecsimul/led_vermelho.xpm", FALSE, NULL);
  apaga_led = gtk_timeout_add(50, (GtkFunction) led_off, NULL);

 return FALSE;
}

int
led_off(void)
{
 troca_pixmap(window_plc_princ, "pixmap_led_rx", "plecsimul/led_apagado.xpm", FALSE, NULL);

 return FALSE;
}

/*
troca_pixmap - funcao quase toda baseada na funcao create_pixmap() do arquivo support.c fornecida pelo Glade, troca o arquivo de pixmap de um widget pixmap
*/

int
troca_pixmap(gpointer user_data, char *nome_pixmap, char *filename, gboolean use_pixmap_interno, GdkPixmap *pixmap_interno)
{

  GtkWidget *pixmap;
  GdkColormap *colormap;
  GdkPixmap *gdkpixmap;
  GdkBitmap *mask;
  gchar *pathname = NULL;

  pixmap = lookup_widget(user_data, nome_pixmap);

  if(use_pixmap_interno == FALSE)
    {
      if (!filename || !filename[0])
	return -1;

      pathname = gnome_pixmap_file (filename);
      if (!pathname)
	{
	  g_warning (_("Couldn't find pixmap file: %s"), filename);
	  return -1;
	}

      colormap = gtk_widget_get_colormap (user_data);

      gdkpixmap = gdk_pixmap_colormap_create_from_xpm (NULL, colormap, &mask, NULL, pathname);

      if (gdkpixmap == NULL)
	{
	  g_warning (_("Couldn't create pixmap from file: %s"), pathname);
	  g_free (pathname);
	  return -1;
	}
    }

   else
     {
      if (pixmap_interno == NULL)
	{
	  g_warning (_("Couldn't create pixmap from pixmap_interno"));
	  return -1;
	}

       gdkpixmap = pixmap_interno;
     }

  if(use_pixmap_interno == FALSE)
    {
      g_free (pathname);
      gtk_pixmap_set(GTK_PIXMAP(pixmap), gdkpixmap, mask);
    }
  else
    {
      gtk_widget_hide(GTK_WIDGET(pixmap));
      gtk_pixmap_set(GTK_PIXMAP(pixmap), gdkpixmap, NULL);
      gtk_widget_show(GTK_WIDGET(pixmap));
    }
   if(use_pixmap_interno == FALSE)
     {
       gdk_pixmap_unref (gdkpixmap);
       gdk_bitmap_unref (mask);
     }

  return 1;
}


/* procura pela ocorrencia de espacos em branco, separa os caracteres formadores dos numeros entre os espacos e tranforma estes em numeros definitivos */



int
separa_num (char *cadeia, char *destino, int *compr, gboolean is_hex)
{
  char geral[258];
  int i;
  int u;
  int d = 0;

  for(i = 0; i < *compr; i++)
    {
      u = 0;

      while(cadeia[i] == ' ')
	{
	  if(i >= *compr) break;
	  i++;
	}

      if(cadeia[i] == '\0') 
	  {
	    destino[u+1] = '\0';
	    *compr = d + 1;
	    return 0;
	  }

      while(cadeia[i] != ' ')
	{
          if(cadeia[i] == '\0') break;
	  if(i >= *compr) break;
	  geral[u] = cadeia[i];
          u++;
	  i++;
	}

      geral[u] = '\0';

      if(envia_hex == TRUE)
	destino[d] = (char)strtol(geral, NULL, 16);
      else
	destino[d] = atoi(geral);

      d++;

      if(cadeia[i] == '\0') 
	{
	  destino[d+1] = '\0';
	  *compr = d + 1;
	  return 0;
	}
    }

  destino[d+1] = '\0';
  *compr = d + 1;

  return 0;
}


char
checksum(char *buff, int compr)
{
  int i;

  char cks = 0;
    
  cks = buff[0];

  if (compr == 1) return cks;

  for (i = 1; i < compr; i++)
    cks ^= buff[i];

  return cks;
}
#include <gnome.h>
#include "plecsimul.h"
#include "callbacks.h"

//define DEBUG


struct memo_io_plc memo_io;

int
monta_comando_plc(char *buff, char *modelo_clp, char *command, int *num_int_plc)
{
  static gboolean ja_achou_inicio;
  static gboolean achou_1_num_plc;
  static gboolean achou_2_num_plc;
  static gboolean header_complete;
  static gboolean completo;

  static char last_char;
  static char penultimo_char;

  static int cont;

  static char num_plc[2];

  /*  if((ja_achou_inicio == FALSE) && (achou_1_num_plc == FALSE) && (achou_2_num_plc = FALSE) && (header_complete == FALSE))
      command[0] = '\0'; */

  //if(completo == TRUE)
  //{
  //int i;
  //printf("APAGA TUDO \n");
  //for(i = 0; i < 2048; i++)
  //command[i] = '\0'; 
  //}

   if(!strcmp(modelo_clp, "MATSUSHITA FT1"))
    {
      if(((buff[0] == '%') || (buff[0] == '<')) && (ja_achou_inicio == FALSE))
	{
	  cont = 0;
	  ja_achou_inicio = TRUE;
	  penultimo_char = last_char;
	  last_char = buff[0];
	  completo = FALSE; 
	  return 0;
	}
      if((achou_1_num_plc != TRUE) || (achou_2_num_plc != TRUE))
	{
	  if((ja_achou_inicio == TRUE) && ((last_char == '%') || (last_char == '<')))
	    {
	      num_plc[0] = buff[0];
	      penultimo_char = last_char;
	      last_char = buff[0];
	      achou_1_num_plc = TRUE;
	      return 0;
	    }
	  else
	    if((ja_achou_inicio == TRUE) && ((penultimo_char == '%') || (penultimo_char == '<')))
	      {
		num_plc[1] = buff[0];
		penultimo_char = last_char;
		last_char = buff[0];
		achou_2_num_plc = TRUE;
		return 0;
	      }
	}

      if((ja_achou_inicio == TRUE) && (buff[0] == '#') && (header_complete == FALSE))
	{

	  penultimo_char = last_char;
	  last_char = buff[0];
	  header_complete = TRUE;
	  /*	  *num_int_plc = ((strtoul(&num_plc[0], NULL, 10) * 10 ) + (strtoul(&num_plc[1], NULL, 10) * 1 ));
		  return *num_int_plc; */
	  return 0;

	}

      if(buff[0] != 0x0D)
	{
	  command[cont] = buff[0];
	  printf("cont = %d\n", cont);
	  printf("command = %c\n", command[cont]);
	  printf("vetor command = %p\n", &command[cont]);

	  cont++;
	}
      else
	{
          ja_achou_inicio = FALSE;
	  achou_1_num_plc = FALSE;
	  achou_2_num_plc = FALSE;
          header_complete = FALSE;
	  completo = TRUE; 

	  command[cont] = 0x0D;
	  cont++;

	  command[cont] = '\0';
          last_char = '\0';
          penultimo_char = '\0';
	  num_plc[0] = '\0';

#ifdef DEBUG
	  {
	    int i;
	    printf("COMANDO DO IHM : \n");
	    for(i = 0; i < cont; i++)
	      printf("%c", command[i]);
	    printf("\n");
	  }
#endif

	  return cont;
	}
    }

  return 0;

}

int
simular_plc(char *modelo_clp, char *comando, int *num_int_plc, int descritor)
{
  char *resp_envia = NULL;
  char resp_comand[3] = "";
  char *parametros = NULL;
  gboolean achou_comando = FALSE;
  gboolean ha_erro = FALSE;
  char contact_code = '\0';
  char N_contact_dec[4] = "";
  char N_contact_hex[2] = "";
  char start_word[5] = "";
  char end_word[5] = "";
  int start = 0;
  int end = 0;
  char contact_data = '\0';
  int N_dec = 0;
  int N_hex = 0;
  char cod_erro[2] = "";
  int mask_relay = 1;
  int *campo_bit_io = NULL;
  int *campo_bit_memo = NULL;
  char init_cstr[5] = "";
 
  printf("comando ---> %s\n", comando);

  parametros = malloc(2048 * sizeof(char));
  resp_envia = malloc(2048 * sizeof(char));
  if(!resp_envia || !parametros)
    exit(-1);

 
  if(!strcmp(modelo_clp, "MATSUSHITA FT1"))
    {
      size_t len_resp; /* COMPRIMENTO DA STRING DE RESPOSTA */
      int geral_c = 0;

      for(geral_c = 0; geral_c <= (L_STRING_COMMAND_MEWFP1 - 1); geral_c++)
	init_cstr[geral_c] = comando[geral_c];

      if((init_cstr[0] == 'W') && (init_cstr[1] == 'C'))
	{
	    
	  achou_comando = TRUE;
	  switch(init_cstr[2])
	    {
	      /* AQUI DEVE HAVER ALGO QUE PROCESSE OS ARGUMENTOS DO COMANDO */
	      /*  E DECIDA SE DEU CERTO OU NAO, SE SIM ENVIA RESPOSTA PARA O COMANDO */
	      /* SE NAO ENVIAR A MENSAGEM DE ERRO */

	        case 'S': /* WRITE CONTACT AREA (SINGLE POINT) */
		  {
		    contact_code = init_cstr[3];
		    copia_parametros(4, &parametros[0], &comando[0], 4);

		    switch(contact_code)
		      {
		      case 'X':
			{
			  strncpy(&N_contact_dec[0], &parametros[0], 3);
			  N_contact_dec[3] = '\0';
			  strncpy(&N_contact_hex[0], &parametros[3], 1);
			  N_contact_hex[1] = '\0';
			  strncpy(&contact_data, &parametros[4], 1);
			  N_dec = strtol(&N_contact_dec[0], NULL, 0);
			  N_hex = strtol(&N_contact_hex[0], NULL, 16);

			  if(N_dec > 0x0C) 
			    {
			      ha_erro = TRUE;
			      strncpy(&cod_erro[0], "60", 2); /* PARAMETRO INCORRETO */
			      break;
			    }

			  campo_bit_memo = (int *)&memo_io.memo_WX[N_dec];
			  campo_bit_io = (int *)&memo_io.rel_inX[N_dec];

			  mask_relay = mask_relay << N_hex;
			  if(contact_data == '1')
			    *campo_bit_io = *campo_bit_io | mask_relay;
			  else
			    *campo_bit_io = *campo_bit_io & ~mask_relay;

			  *campo_bit_memo = *campo_bit_io;

			  break;

			}
			
			
		      case 'Y':
			{
			  strncpy(&N_contact_dec[0], &parametros[0], 3);
			  N_contact_dec[3] = '\0';
			  strncpy(&N_contact_hex[0], &parametros[3], 1);
			  N_contact_hex[1] = '\0';
			  strncpy(&contact_data, &parametros[4], 1);
			  N_dec = strtol(&N_contact_dec[0], NULL, 0);
			  N_hex = strtol(&N_contact_hex[0], NULL, 16);
			  if(N_dec > 0x0C) 
			    {
			      ha_erro = TRUE;
			      strncpy(&cod_erro[0], "60", 2); /* PARAMETRO INCORRETO */
			      break;
			    }

			  campo_bit_memo = (int *)&memo_io.memo_WY[N_dec];

			  campo_bit_io = (int *)&memo_io.rel_outY[N_dec];

			  mask_relay = mask_relay << N_hex;
			  if(contact_data == '1')
			    *campo_bit_io = *campo_bit_io | mask_relay;
			  else
			    *campo_bit_io = *campo_bit_io & ~mask_relay;

			  *campo_bit_memo = *campo_bit_io;

			  break;
			}

		      case 'R':
			{
			  strncpy(&N_contact_dec[0], &parametros[0], 3);
			  N_contact_dec[3] = '\0';
			  strncpy(&N_contact_hex[0], &parametros[3], 1);
			  N_contact_hex[1] = '\0';
			  strncpy(&contact_data, &init_cstr[8], 1);
			  N_dec = strtol(&N_contact_dec[0], NULL, 0);
			  N_hex = strtol(&N_contact_hex[0], NULL, 16);
			  if(N_dec > 0x0C) 
			    {
			      ha_erro = TRUE;
			      strncpy(&cod_erro[0], "60", 2); /* PARAMETRO INCORRETO */
			      break;
			    }

			  campo_bit_memo = (int *)&memo_io.memo_WR[N_dec];

			  campo_bit_io = (int *)&memo_io.relay_internal_R[N_dec];

			  mask_relay = mask_relay << N_hex;
			  if(contact_data == '1')
			    *campo_bit_io = *campo_bit_io | mask_relay;
			  else
			    *campo_bit_io = *campo_bit_io & ~mask_relay;

			  *campo_bit_memo = *campo_bit_io;

			  break;
			}


		      }

		    if(ha_erro == FALSE)
		      {
			strncpy(&resp_comand[0], "WC", 3);
			strncpy(&parametros[0], "", 1);
		      }

		    break;
		  }
	        case 'P': /* WRITE CONTACT AREA (PLURAL POINTS) */
		  {
		    strncpy(&resp_comand[0], "WC", 3);
		    break;
		  }
	        case 'C': /* WRITE CONTACT AREA (WORD UNITS BLOCK) */
		  {
		    strncpy(&resp_comand[0], "WC", 3);
		    break;
		  }

	        default:  /* ERRO !!!! */
		  {
		    strncpy(&resp_comand[0], "WC", 3);
		    break;
		  }
		 
	    }

	}

      if((init_cstr[0] == 'R') && (init_cstr[1] == 'C'))
	{

	  achou_comando = TRUE;
	  strncpy(&contact_code, &init_cstr[3], 1);

	  switch(init_cstr[2])
	    {

	    case 'S':
	      {

		break;
	      }

	    case 'P':
	      {

		break;
	      }
	    case 'C':
	      {
		copia_parametros(4, &parametros[0], &comando[0], 8);
		contact_code = init_cstr[3];
		strncpy(&start_word[0], &parametros[0], 4);
		start_word[5] = '\0';
		strncpy(&end_word[0], &parametros[4], 4);
		end_word[5] = '\0';
		start = strtol(&start_word[0], NULL, 0);
		end = strtol(&end_word[0], NULL, 0);
		if((start > 0xD) || (end > 0xD) || ((end - start) < 0)) 
		  {
		    ha_erro = TRUE;
		    strncpy(&cod_erro[0], "60", 2); /* PARAMETRO INCORRETO */
		    break;
		  }

		strncpy(&resp_comand[0], "RC", 2);
		
		  switch(contact_code)
		    {
		    case 'X':
		      {

			break;
		      }
		    case 'Y':
		      {

			break;
		      }
		    case 'R':
		      {
			campo_bit_memo = (int *)&memo_io.memo_WR[N_dec];
			break;
		      }
		    default:		      
		      goto saida;
		    }


		break;
	      }



	    }

	}

      if(achou_comando == TRUE)
	{

    	  if(ha_erro == FALSE)
      	    {
	      len_resp = monta_resposta(&resp_comand[0], &parametros[0], 0, TRUE, "01", resp_envia);
 	      resp_envia[len_resp] = '\0';
   	      envia_string(resp_envia, len_resp, descritor);
	      goto saida;
      	    }
	  
      	}
 
     
    }

 saida:  
   comando[0] = '\0';
   free(parametros);
   free(resp_envia);
   return 0;
}


int
monta_resposta(char *resposta, char *parametros, int num_parm, gboolean ins_bcc_cr, char *num_clp, char *resp_p_env)
{
  int chksum;
  char schksum[3];
  size_t index = 0;
  size_t parm_len = 0;

  resp_p_env[index] = '%';
  index++;
  strncpy(&resp_p_env[index], num_clp, 2);
  index+=2;
  resp_p_env[index] = '$';
  index++;
  strncpy(&resp_p_env[index], resposta, 2);
  index+=2;

  parm_len = strlen(parametros);

  if(parm_len)
    {
      strncpy(&resp_p_env[index], parametros, parm_len);
      index+=parm_len;
    }

  if(ins_bcc_cr == TRUE)
    {
      chksum = checksum(resp_p_env, index);
      sprintf(schksum, "%X", chksum);
      strncpy(&resp_p_env[index], schksum, 2);
      index+=2;
      resp_p_env[index] = 0x0D;
    }

  return index;
}


void
copia_parametros(int inic, char *dest, char *orig, int compr)
{
	  int counter;

	  for(counter = inic; (orig[counter] != '\0') || (counter < compr); counter++)
	    dest[counter - inic] = orig[counter];

}





[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]