                                
#include<reg51.h>
#include<string.h>

#define Buf_Max 200
#define delay_time 3000

sbit led1 = P0^0;
sbit led2 = P0^1;
sbit led3 = P0^2;
sbit led4 = P0^3;
sbit led5 = P0^4;
sbit led6 = P0^5;
sbit led7 = P0^6;
sbit led8 = P0^7;

unsigned char i=0;
unsigned char Rec_Buf[Buf_Max];

void serial_init(void);
void send_ASCII(unsigned char *b);
void delay_ms(unsigned int time);
void clr_Buf(void);
void send_Hex(unsigned char c);
bit hand(unsigned char *a);

void main(void)
{
	serial_init();
	clr_Buf();
	delay_ms(6000);
	while(!hand("OK"))
	{
		send_ASCII("AT");
		led6=~led6;
		send_Hex(0x0d);
		send_Hex(0x0a);
		delay_ms(6000);
	}
	clr_Buf();
    led1=0;

	delay_ms(delay_time);
	send_ASCII("AT+CLPORT=\"TCP\",\"8008\"\r\n");
	send_Hex(0x0d);
	send_Hex(0x0a);
	delay_ms(delay_time);
	while(!hand("OK"));
	clr_Buf();
	led2=0;

	delay_ms(delay_time);
	send_ASCII("AT+CIPHEAD=1\r\n");
	send_Hex(0x0d);
	send_Hex(0x0a);
	delay_ms(delay_time);
	while(!hand("OK"));
	clr_Buf();
	led3=0;

	delay_ms(delay_time);
	send_ASCII("AT+CIPSTART=\"TCP\",\"111.15.144.6\",\"8008\"\r\n");	//change the 111.15.144.6 and 8008 to your ip and port 
	send_Hex(0x0d);		
	send_Hex(0x0a);
	delay_ms(delay_time);	//delay
	while(!hand("OK"));
	//clr_Buf();
	led4=0;
    delay_ms(delay_time);
	while(!hand("CONNECT OK"));	//wait until connecting the server
	clr_Buf();
	led5=0;

	while(1)
	{
		if(strstr(Rec_Buf,"+IPD,1:1"))	//if the sim900 module reveived +IPD,1:1 
			{
				clr_Buf();
				delay_ms(delay_time);
				send_ASCII("AT+CIPSEND");	//send LED7 ON to the server
				send_Hex(0x0d);
				send_Hex(0x0a);
				delay_ms(delay_time);
				send_ASCII("LED7 ON\r\n");
				send_Hex(0x1a);
				led7=0;
				led8=1;
			}

		if(strstr(Rec_Buf,"+IPD,1:2"))	//if the sim900 module reveived +IPD,1:2 
			{
				clr_Buf();
				delay_ms(delay_time);
				send_ASCII("AT+CIPSEND");
				send_Hex(0x0d);
				send_Hex(0x0a);
				delay_ms(delay_time);
				send_ASCII("LED8 ON\r\n");	//send LED8 ON to the server
				send_Hex(0x1a);
				led8=0;
				led7=1;
			}
	}

}

void serial_init(void)
{
	SCON = 0X50;
	TMOD = 0X20;
	TH1 = 0XFD;
	TL1 = 0XFD;
	TR1 = 1;
	ES = 1;
	EA = 1;
}

void serial_int() interrupt 4
{
	ES = 0;
	if(TI)
	{
		TI=0;
	}
	if(RI)
	{
		RI=0;
		Rec_Buf[i]=SBUF;
		i++;
		if(i>200)
			{
				i=0;
			}	
	}
    ES=1;	
}

void send_ASCII(unsigned char *b)
{
	ES=0;
	for(b;*b!='\0';b++)
	{
		SBUF=*b;
		while(TI!=1);
		TI=0;
	}
ES=1;
}

void delay_ms(unsigned int time)
{
	unsigned char j;
	for(;time>0;time--)
	{
		j=1500;
		while(j--);
	}
}

void clr_Buf(void)
{
    unsigned char k;
	for(k=0;k<Buf_Max;k++)
	{
		Rec_Buf[k]=0;
	}
i=0;
}

void send_Hex(unsigned char c)
{
	ES=0;
    SBUF=c;
	while(TI!=1);
	TI=0;
	ES=1;
}

bit hand(unsigned char *a)
{
    if(strstr(Rec_Buf,a)!=NULL)
        return 1;
	else
		return 0;
}




