
#include "ptrans.h"

void puerto_serial_event() interrupt 4 using 1{
	if(RI == 1){	                // if reception occur 
        switch(SBUF){               // check SBUF
            case CMD_INICIAR:{      // SBUF = start command
                estado=C_INICIANDO; // set status to starting
                ROk=0;              // set recieve software flag to 0
            }break;
            case CMD_CANCELAR:{     // SBUF = cancel command
                estado=C_LIBRE;     // set status to free
                ROk=0;              // set recieve software flag to 0
            }break;
            case CMD_FINALIZAR:{    // SBUF = finish command
                estado=C_LIBRE;     // set status to free
                ROk=0;              // set recieve software flag to 0
            }break;
            default:{                   // else
                switch(estado){         // check the status
                    case C_OCUPADO:{    // status = busy
                    }break;
                    case C_LIBRE:{      // status = free
                    }break;
                    case C_INICIANDO:{  // status = starting
                        if(SBUF&direccion_local==direccion_local){  // checking the address
                            ind_trama=0;            // set the index of the buffer to 0
                            estado=C_RECIBIENDO;    // set status to recieving
                            SBUF=CMD_ACK;           // send the ack command
                        }
                        else{
                            estado=C_OCUPADO;       // if the address is not mine set status to busy
                        }
                    }break;
                    case C_RECIBIENDO:{             // status = recieving
                        trama[ind_trama]=SBUF;      // put SBUF in the buffer
                        ind_trama++;                
                        if(ind_trama>3){            // check if the 3 data bytes are complete
                            ind_trama=0;            // set index to 0
                            ROk=1;                  // set the software recieve flag to 1
                        }
                        SBUF=CMD_ACK;               // send the ack command
                    }break;
                }
            }break;
        }
        RI = 0; 			        // clear reception flag for next reception 
	}
    if(TI==1){                      //if transmition occurs
        TI=0;                       //clears TI
    }
}
