#include <18f4431.h>
#include <string.h>
#fuses intrc,nomclr,t1lowpower,noprotect,noput,nowdt,nobrownout,nolvp
#use delay (clock=4Mhz)
#use rs232 (baud=9600,xmit=pin_c6,rcv=pin_c7,parity=n,bits=8)

int const lenbuff=100;
int pregunta=0;
int xbuff=0x00,flagcommand=0,final=0,a=0,v=0;
char cbuff[lenbuff];
char rcvchar=0x00;
char pos_sms=0x00;
char telefono[10];
void inicbuff(void);
void procesa_comando(void);


#int_rda
void comunica()
{
rcvchar=0x00;
if (kbhit())
   {
   rcvchar=getc();
   if(rcvchar!=0x0a){
   if (xbuff<100){
   cbuff[xbuff++]=rcvchar;
   printf("introduce en cbuff=%s\n\r",cbuff);
   }
   }
   if(rcvchar==0x0d){
   final++;
   if(pregunta){
   printf("pregunta=1");
   if(final==4){
   flagcommand=1;
   final=0;
   pregunta=0;
   }}else{
   printf("pregunta=0");
      if(final==2){
   flagcommand=1;
   final=0;
   }}
   }
   }
}
void main ()
{
inicbuff();
for (a=0;a<10;a++){
telefono[a]='\0';
}

enable_interrupts(int_rda);
enable_interrupts(global);
delay_ms(5000);
printf("inicia");
do
   {
   if(flagcommand){
   flagcommand=0;
   disable_interrupts(int_rda);
   procesa_comando();
   inicbuff();
   printf("cbuff del while=%s\n\r",cbuff);
   enable_interrupts(int_rda);
   }
   }while(true);
}

void inicbuff(void)
{
int i;
for(i=0;i<lenbuff;i++)
   {
   cbuff[i]='\0';
   }
xbuff=0x00;
}

void procesa_comando(void){
char *retorno1;
char *retorno2;
char *coma;
char *clave;
char *numero;
char string1[10];
char string2[10];
char string3[10];
char s1[10];
char s2[10];
char s3[10];
int i=0;
for (i=0;i<10;i++){
s1[i]='\0';
s2[i]='\0';
s3[i]='\0';
numero[i]='\0';
string1[i]='\0';
string2[i]='\0';
string3[i]='\0';
}


//NUEVO MENSAJE RECIBIDO.........................

strcpy(string1,"+CMTI:");
retorno1=strchr(cbuff,0x0d);
retorno1++;
strncpy(s1,retorno1,6);
if (!stricmp(s1,string1)){
coma=strchr(cbuff,0x2c);
coma+=1;
pos_sms=*coma;
printf("AT+CMGR=%c\r",pos_sms);
pregunta=1;
goto fin;
}
// RESPUESTA AL LEER MENSAJE......................

strcpy(string2,"+CMGR:");
printf("valor de string2=%s\n\r",string2);
retorno2=strchr(cbuff,0x0d);
printf("valor de buff1=%s\n\r",cbuff);
retorno2++;
strncpy(s2,retorno2,6);
printf("valor de s2=%s\n\r",s2);
if (!stricmp(s2,string2)){
strcpy(string3,"paco");
printf("valor de string3=%s\n\r",string3);
clave=strchr(cbuff,0x70);
printf("valor de cbuff2=%s\n\r",cbuff);
strncpy(s3,clave,4);
printf("valor de s3=%s\n\r",s3);
if(!stricmp(s3,string3)){
numero=strchr(cbuff,0x2c);
numero=numero+5;
strncpy(telefono,numero,9);
printf("valor de telefono=%s\n\r",telefono);
printf ("el telefono es %s",telefono); // 
}
}
fin:
v=0;
}

