#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/eeprom.h>
#include <string.h>

#include <avr/sleep.h>
#include "macro.h"
//#include "trh033m.h"
#include "cc1100.h"
#include "cc1100_globals.h"
//#include <avr/iomx8p.h>
#include "spi1.h"

#include <stdint.h>
#include <avr/wdt.h>
//#include <avr/i2c.h>
#include <util/twi.h>




#define B_CTL				REGISTER_BIT(PORTB,0)
#define CS_CC1101			REGISTER_BIT(PORTB,2)

#define CS_CC1101_LOW			CS_CC1101 =0
#define CS_CC1101_HIGH			CS_CC1101 =1


#define B_CTL_LOW			B_CTL =0
#define B_CTL_HIGH			B_CTL =1

#define OUTPUT_HIGH			OUTPUT = 1
#define OUTPUT_LOW			OUTPUT = 0


#define SCLR_HIGH			SCLR = 1
#define SCLR_LOW			SCLR = 0






enum {
	CA_WAVE_CH5=0xC0,
	CA_WAVE_CH9=0x80,
	CA_WAVE_CH13=0x40,
	CA_WAVE_CH17=0x00
};



enum {
	AD_PIN_TEMPERATURE=0x02,
	AD_PIN_TAMPA=0x06,
	AD_PIN_BATT_LOW=0x07
};


enum {
	AD_VAL_FROM_R=0,
	AD_VAL_FROM_L
};






void cc1101_carrier_wave_setup(void);
void cc1101_8PATABLE_write_reg(u8 * reg);
void led_flasher(u8 count,u16 msec);
uint16_t cc1101_rx(cc1101_client * client);
void cc1101_tx(cc1101_client * client);
void temperature_chk(void);

void rtc_alarm_disenable(void);
void init_ad(void);
void ad_diseable(void);
void reg_slave_eeprom2reg(void);
u8 reg_slave_num_serch(void);
void rtc_set_next_alarm(u8 alarm);
void add_batt_low(void);
void sig_set(void);



uint8_t status;
uint8_t	test_cnt02;
volatile cc1101_client gClient;
//u8 rx_data[100];

u8 chk_state=0;



u8 sleep_time_cnt=0;
u8 test_cnt=0;
u8 temp_user_data=0;


u8 temp_user_data_new=0;
u8 temp_user_data_old=0;


rxfifo_data temp_fifo;

u8 led_cnt=0;

u8 cnt_char=0;
u8 rx_char[40];
u8 cmd_length=0;


char words[6][10]; 

enum {
	WAIT_IVENT=0,
	WAIT_2SEC,
	TEST_CARRIER_WAVE,
	WAIT_RX,
	SEND_COMPLETE,
	TEST_CLK,
	SLEEP_TIME,
	SLEEP_TIME_END,
	TEST_1DAY_SIG,
	REG_DEVICE_ERR,
	REG_DEVICE_NEW_ENTRY,
	REG_SLAVE_VIA_UART
};


enum {
	SR_RESET=0,
	SR_SET
};



enum {
	ALARM_2SEC,
	ALARM_30SEC,
	ALARM_1MIN,
	ALARM_2MIN,
	ALARM_3MIN,
	ALARM_5MIN,
	ALARM_30MIN,
	ALARM_1hour,
	ALARM_24hour
};



enum {
	SLEEP_2SEC = 0,
	SLEEP_1MIN = 1,
	SLEEP_2MIN = 3,
	SLEEP_5MIN = 9
};



enum {
	SERACH_SLAVE_OK=0,
	SERACH_SLAVE_NG
};


#if 1		//OSC 8MHz

void udelay(u16 usec)
{
	register u8 i;

	for(i = 0 ;   i < usec ; i++){
		asm volatile("NOP");
		//asm volatile("NOP");
		//asm volatile("NOP");
		//asm volatile("NOP");
	}
}


#endif









/*
 	mili second  Delay
*/



#if 1		//OSC 8MHz


void mdelay(u16 msec)
{
	register u16 i;


	for(i = 0 ; i < msec  ; i++)
	{
		udelay(250);
		udelay(250);
		udelay(250);
		udelay(50);
	}

}


#endif

void sdelay(u16 msec)
{
	register u16 i;

	for(i=0;i<msec;i++)
	{
		mdelay(1000);
	}
}







/*
 	mili second  Delay
*/




#if 1

void putc(u8 data)
{
	while(!(UCSR0A & (1<<UDRE0)));
	UDR0 = data;
}

void putb(u8 data)
{
	if(data < 0x0a)
		putc('0' + data);
	else 
		putc('a' + (data-10));
}




void puthex(u8 data)
{
	putb(data/16);
	putb(data%16);
}




u8 putchr2hex(u8 data)
{
	if(data&0x60)
		data - 0x60;
	else
		data - 0x30;

	return data;
}



u8 chr2hex(u8 data_h,u8 data_l)
{
	u8 test;
	//u8 test2;
	//u8 test3;

	data_h = putchr2hex(data_h);
	data_l = putchr2hex(data_l);
	
	test=(data_l&0x0F)|((data_h<<4)&0xF0);
	
	return test;	
}




void timer_init()
{
	TCCR1A = 0x00;
	TCCR1B = 0x0a;
	TCCR1C = 0x00;
	OCR1A  = 0xffff;
	TCNT1  = 0x0000;

	TCCR0B=(1<<CS02)|(1<<CS00);		//clkI/O/1024 (From prescaler)		(15625hz) 		1/(1000000/64)  = 	64us..
	TCNT0=0;

}

#endif


void inituart()
{
	#if 0			//OSC 128kHz
	UCSR0A = 0x02;	//U2X = 1
	UCSR0B = 0x00; // Rx/Tx enable
	UCSR0C = 0x06; // 8bit, 1 stop bit, no parity
	UBRR0H = 0x00; 
	UBRR0L = 0x0c; // Baudrate 1200
	UCSR0B = 0x98; // rx / tx enable , rx int enable 0x98
	#endif

	#if 0			//OSC 8MHz
	UCSR0A = 0x02;	//U2X = 1
	UCSR0B = 0x00; // Rx/Tx enable
	UCSR0C = 0x06; // 8bit, 1 stop bit, no parity
	UBRR0H = 0x00; 
	UBRR0L = 0x67; // Baudrate 9600
	UCSR0B = 0x98; // rx / tx enable , rx int enable 0x98

	#endif

	#if 1			//OSC 4MHz
	UCSR0A = 0x02;	//U2X = 1
	UCSR0B = 0x00; // Rx/Tx enable
	UCSR0C = 0x06; // 8bit, 1 stop bit, no parity
	UBRR0H = 0x00; 
	UBRR0L = 0x33; // Baudrate 9600
	UCSR0B = 0x98; // rx / tx enable , rx int enable 0x98

	#endif

}


unsigned char ctrl[3]={0x00,0x00,0x00};





#define OVERFLOW 256  

#define TICKS_PER_SEC 1000  

#define Prescaler 64  


volatile unsigned int tic_time;  
volatile unsigned int c_read_time;
    

char ms33=0;
ISR(TIMER0_OVF_vect)
{
	test_cnt02++;


}  

ISR(TIMER2_OVF_vect)
{

	test_cnt02++;

	TCNT2=0;


	if(gClient.status.status==TEST_CLK)
	{
		if(test_cnt02>30)
		{
			led_cnt=~led_cnt;
			test_cnt02=0;
			if(led_cnt&0x01)
				B_CTL_LOW;
			else
				B_CTL_HIGH;
		}
	}

}  


void hw_setup(void)
{

	#if 1

	CLKPR = _BV(CLKPCE);	// CLKPCEビットを1にする
	CLKPR = 0b0001;			// 2分周にする
	#endif



    DDRC=0x00;      
	DDRD=0x00;
	DDRB=0x0D;

	/*pull_up*/
	PORTC = (1<<PC0) | (1<<PC1);
	PORTD = 0xf3;


	PORTB = 0x01;	//for yellow LED



	#if 1

	/*Timer2 test*/
	TCCR2B=(1<<CS22)|(1<<CS21)|(1<<CS20);		//clkI/O/1024 (From prescaler)		(15625hz) 		1/(1000000/64)  = 	64us..
	TCNT2=0;
	TIMSK2 |= (1<<TOIE2);

	#endif



	EICRA &= ~(1<<ISC00);	//INT0の割り込み発生条件を立下り検知でトリガで固定
	EICRA &= ~(1<<ISC01);

	EICRA &= ~(1<<ISC10);	//INT1の割り込み発生条件を立下り検知でトリガで固定
	EICRA &= ~(1<<ISC11);


	#if 0
	EIMSK |= (1<<INT0);
	EIMSK |= (1<<INT1);
	#endif

}





uint8_t cc1100_read_reg_uartout(uint8_t addr)
{
	uint8_t reg;

	reg = cc1100_read_reg(addr);

	#if 1

	puthex(addr);
	putc(0x5c);
	puthex(reg);
	putc(0x0d);
	putc(0x0a);

	#endif

	return reg;
}



//u8 pt_data[] = {0xC5,0xC0,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7};		\\10dB
//u8 pt_data[] = {0xC5,0x60,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7};		//0dB
//u8 pt_data[] = {0xC5,0xC5,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7};
u8 pt_data[] = {0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x00};		//10dB
//u8 pt_data[] = {0x60,0x60,0x00,0x00,0x00,0x00,0x00,0x00};		//0dB
//u8 pt_data[] = {0x60,0x60,0x00,0x00,0x00,0x00,0x00,0x00};		//0dB
//u8 pt_data[] = {0x34,0x34,0x00,0x00,0x00,0x00,0x00,0x00};		//-10dB



#if 1

void cc1101_init_tx(void)
{


	#if 1
	cc1100_cfg_append_status(CC1100_APPEND_STATUS_ENABLE);
	cc1100_cfg_crc_autoflush(CC1100_CRC_AUTOFLUSH_DISABLE);
	cc1100_cfg_white_data(CC1100_DATA_WHITENING_ENABLE);
	cc1100_cfg_crc_en(CC1100_CRC_CALCULATION_ENABLE);
	cc1100_cfg_freq_if(0x0C);
	cc1100_cfg_fs_autocal(CC1100_AUTOCAL_NEVER);
	//cc1100_cfg_mod_format(CC1100_MODULATION_GFSK);
	cc1100_cfg_mod_format(CC1100_MODULATION_2FSK);
    //cc1100_cfg_mod_format(CC1100_MODULATION_MSK);
	cc1100_cfg_sync_mode(CC1100_SYNCMODE_30_32);
	cc1100_cfg_manchester_en(CC1100_MANCHESTER_DISABLE);
	#endif


	cc1100_cfg_white_data(CC1100_DATA_WHITENING_DISABLE);
	cc1100_cfg_sync_mode(CC1100_SYNCMODE_30_32);



	cc1101_carrier_wave_setup();
	//cc1101_8PATABLE_write_reg(pt_data);
	cc1100_write_reg(CC1100_REG_MDMCFG3,0x83);	//DATA rate 9.6kbps
	cc1100_write_reg(CC1100_REG_MDMCFG4,0x88);	//

	//cc1100_write_reg(CC1100_REG_DEVIATN,0x27);		//Deviation 11.901855kHz
	cc1100_write_reg(CC1100_REG_DEVIATN,0x17);		//Deviation 5.950928kHz


	cc1100_write_reg(CC1100_REG_MDMCFG4,0xF8);
}




void cc1101_init_rx(void)
{


	#if 1
	cc1100_cfg_append_status(CC1100_APPEND_STATUS_ENABLE);
	cc1100_cfg_crc_autoflush(CC1100_CRC_AUTOFLUSH_DISABLE);
	cc1100_cfg_white_data(CC1100_DATA_WHITENING_ENABLE);
	cc1100_cfg_crc_en(CC1100_CRC_CALCULATION_ENABLE);
	cc1100_cfg_freq_if(0x0C);
	cc1100_cfg_fs_autocal(CC1100_AUTOCAL_NEVER);
	//cc1100_cfg_mod_format(CC1100_MODULATION_GFSK);
	cc1100_cfg_mod_format(CC1100_MODULATION_2FSK);
    //cc1100_cfg_mod_format(CC1100_MODULATION_MSK);
	cc1100_cfg_sync_mode(CC1100_SYNCMODE_30_32);
	cc1100_cfg_manchester_en(CC1100_MANCHESTER_DISABLE);
	#endif


	cc1100_cfg_crc_autoflush(CC1100_CRC_AUTOFLUSH_ENABLE);
	cc1100_cfg_white_data(CC1100_DATA_WHITENING_DISABLE);
	cc1100_cfg_sync_mode(CC1100_SYNCMODE_30_32);
	cc1100_write_reg(CC1100_REG_MDMCFG3,0x83);	//DATA rate 9.6kbps
	cc1100_write_reg(CC1100_REG_MDMCFG4,0x88);	//
	//cc1100_write_reg(CC1100_REG_DEVIATN,0x27);		//Deviation 11.901855kHz
	cc1100_write_reg(CC1100_REG_DEVIATN,0x17);		//Deviation 5.950928kHz

	//cc1100_cfg_txoff_mode(CC1100_TXOFF_MODE_RX);

	#if 0
	pt_data[0] = 0xC0;			//10dB
	pt_data[1] = 0x00;			//
	#endif
	//cc1101_data_waveoutput_setup(gClient.status.input_data,pt_data);
	cc1101_carrier_wave_setup();
	//cc1101_8PATABLE_write_reg(pt_data);


	cc1100_write_reg(CC1100_REG_MDMCFG4,0xF8);

}




#endif





void cc1101_8PATABLE_read_reg(void)
{
	u8 i;
	u8 reg[10];

	spi1_select(SPI1_CC1100);
	spi1_write_single(0x3e | CC1100_ACCESS_READ_BURST);
	for(i=0;i<8;i++)
	{
		reg[i] = spi1_read_single();
	}
	spi1_deselect(SPI1_CC1100);


	for(i=0;i<8;i++)
	{
		putc(0x54);
		puthex(i);
		putc(0x5c);
		puthex(reg[i]);
		putc(0x0d);
		putc(0x0a);
	}
}



void cc1101_8PATABLE_write_reg(u8 * reg)
{
	u8 i;


	spi1_select(SPI1_CC1100);
	spi1_write_single(0x3e | CC1100_ACCESS_WRITE_BURST);
	for(i=0;i<8;i++)
	{
		spi1_write_single(reg[i]);
	}
	spi1_deselect(SPI1_CC1100);

}




void spi_signalpin_opendrain_active(void)
{
	SPCR &= ~(1<<SPE);	//SPI non active
	//DDRB &= ~(1<<PB0);	//B_CTL
	DDRB &= ~(1<<PB2);	//CSn
	DDRB &= ~(1<<PB3);	//MOSI
	DDRB &= ~(1<<PB5);	//SCK

	PORTB &= ~(1<<PB2);	//CSn

	//PORTC &= ~(1<<PC0);
	//PORTC &= ~(1<<PC1);
	PORTC = 0x00;
	PORTD = 0x00;

	#if 0
	CLKPR = _BV(CLKPCE);	// CLKPCEビットを1にする
	//CLKPR = 0b0111;		// 128分周にする
	CLKPR = 0b0110;     	// 64分周にする
	#endif
}


void spi_signalpin_opendrain_nonactive(void)
{

	spi1_init();		
	//DDRB |= (1<<PB0);	//B_CTL
	PORTB &= ~(1<<PB2);	//CSn
	DDRB |= (1<<PB2);	//CSn output

	PORTC |= (1<<PC0);
	PORTC |= (1<<PC1);
	PORTC |= (1<<PC2);
	PORTC |= (1<<PC3);
	PORTC |= (1<<PC4);
	PORTC |= (1<<PC5);
	//PORTC = 0x00;
	PORTD = 0xf7;

	#if 0
	CLKPR = _BV(CLKPCE);	// CLKPCEビットを1にする
	CLKPR = 0b0000;      //	分周なしにする
	#endif
}






void ad_get_val(client_status * status,u8 ad_ch,u8 adlar)
{
	u8 i=0;
	u8 temp=0;
	u8 temp_data_h=0;
	u8 temp_data_l=0;

	init_ad();


	temp = 0xC0 | (ad_ch & 0x0F);					//select ad channel
	temp = (temp & 0xDF) | ((adlar << 5)&0x20);	//select adlar bit

	ADMUX = temp;       //AREF外部電圧

	for(i=0;i<5;i++)
	{
		ADCSRA |= _BV(ADSC);					//変換開始 要ﾙｰﾌﾟ内
		while((ADCSRA&0x10)==0x00);

		ADCSRA |= (1<<ADIF);					//ADIF clear

		#if 1
		temp_data_l = ADCL;
		temp_data_h = ADCH;

		#endif

		#if 0
		temp_data_h = ADCH;
		temp_data_l = ADCL;
		#endif

	}

	status->ad_data_h = temp_data_h;
	status->ad_data_l = temp_data_l;
	//gClient.status.reserve[1] = temp_data_h;
	//gClient.status.reserve[2] = temp_data_l;



	//a = ( ADC >> 4 );						//AD変換結果 4bitｼﾌﾄ= 6bit:0-64
	ad_diseable();
}









void alert_data_get(cc1101_client * client)
{
	u8 temp=0;
	//u8 i=0;
	//u8 temp_data_h=0;
	//u8 temp_data_l=0;

	mdelay(10);

	temp = (temp & 0xFF) | ((PINB >> 1) & 0x01);	//EMG
	temp = (temp & 0xFF) | ((PINB >> 6) & 0x02);	//S/R_RESET
	temp = (temp & 0xFF) | ((PINB >> 4) & 0x04);	//S/R_SET
	//temp = (temp & 0xFF) | ((PINA << 4) & 0x08);	//TAMPA




	ad_get_val(&(client->status),AD_PIN_TAMPA,AD_VAL_FROM_L);


	#if 1
	if(client->status.ad_data_h < 0x10)
		temp |= (1<<3); 	//TAMPA_set
	else
		temp &= ~(1<<3);		//TAMPA_reset
	#endif





	client->status.alert_old_temp = client->status.alert;

	client->status.alert = temp;


	add_batt_low();


}



u8 get_input_data(void)
{
	u8 reg = 0;

	reg = (reg & 0xFF) | (((PIND) << 2) & 0x80);	//F_SEL2
	reg = (reg & 0xFF) | (((PIND) << 2) & 0x40);	//F_SEL1

	reg = (reg & 0xFF) | (((PIND) >> 2) & 0x20);	//D_SEL2
	reg = (reg & 0xFF) | (((PIND) >> 2) & 0x10);	//D_SEL1

	reg = (reg & 0xFF) | (((PINC) << 2) & 0x08);	//M_SEL2
	reg = (reg & 0xFF) | (((PINC) << 2) & 0x04);	//M_SEL1


	return reg;
}



#if 1

u16 tx_fifo_set(txfifo_data * txfifo)
{
	volatile u16 i=0;
	volatile u16 temp=0;

	if(gClient.status.type == SLAVE)
	{
		i++;
		for(temp=0;temp<6;temp++)
		{
			//txfifo->data[i] = gClient.status.src_serial[i-1];
			txfifo->data[i++] = txfifo->src_serial[temp];
		}

		//temp=i;

		for(temp=0;temp<6;temp++)
		{
			//txfifo->data[i] = gClient.status.dest_serial[i];
			//txfifo->data[i++] = rxfifo->dest_serial[temp];
			txfifo->data[i++] = gClient.rxfifo.src_serial[temp];
		}

		//i=13;

		txfifo->data[i++] = gClient.status.sessionflag;

		txfifo->data[i++] = gClient.status.user_data1;
		txfifo->data[i++] = gClient.status.user_data2;
		txfifo->data[i++] = gClient.status.bat_val;
		txfifo->data[i++] = gClient.rxfifo.rx_rssi;
		txfifo->data[i++] = gClient.status.version_l;
		txfifo->data[i++] = gClient.status.reserve[0];
		//txfifo->data[i++] = gClient.status.reserve[1];
		//txfifo->data[i++] = gClient.status.reserve[2];
		txfifo->data[i++] = gClient.rxfifo.rx_lqi;
		txfifo->data[i++] = gClient.status.reserve[4];
		txfifo->data[i++] = gClient.status.reserve[5];
		txfifo->data[i++] = gClient.status.reserve[6];	
		txfifo->data[i++] = 0x01;			//crc01
		txfifo->data[i++] = 0x02;			//crc02

		//tx_length = i;
		txfifo->data[0] = i;
		txfifo->length = i;
		//return i;
	}
	else
	{
		i++;
		for(temp=0;temp<6;temp++)
		{
			//txfifo->data[i] = gClient.status.src_serial[i-1];
			txfifo->data[i++] = txfifo->src_serial[temp];
			//txfifo->dest_serial[temp];
		}

		for(temp=0;temp<6;temp++)
		{
			//txfifo->data[i] = gClient.status.dest_serial[i];
			txfifo->data[i++] = txfifo->dest_serial[temp];
		}

		//i=13;


		#if 1
		txfifo->data[i++] = gClient.status.sessionflag;

		txfifo->data[i++] = gClient.status.user_data1;
		txfifo->data[i++] = gClient.status.user_data2;
		txfifo->data[i++] = gClient.status.bat_val;
		txfifo->data[i++] = gClient.rxfifo.sl_rssi;
		txfifo->data[i++] = gClient.status.version_l;
		txfifo->data[i++] = gClient.status.reserve[0];
		//txfifo->data[i++] = gClient.status.reserve[1];
		//txfifo->data[i++] = gClient.status.reserve[2];
		txfifo->data[i++] = gClient.rxfifo.sl_lqi;
		txfifo->data[i++] = gClient.status.reserve[4];
		txfifo->data[i++] = gClient.rxfifo.rx_rssi;
		txfifo->data[i++] = gClient.rxfifo.rx_lqi;	
		txfifo->data[i++] = 0x01;			//crc01
		txfifo->data[i++] = 0x02;			//crc02



		txfifo->data[0] = i;
		txfifo->length = i;
		//return i;

		#endif

	}

	#if 1
	//cc1100_fifo_put(txfifo->length,1);
	cc1100_fifo_put(&i,1);
	cc1100_fifo_put(txfifo->data,txfifo->length);
	#endif



	return i;

}


#endif




void rx_fifo_get(rxfifo_data * rxfifo)
{
	u8 len; 
	u8 * data; 
	 
	data  = (u8 *) rxfifo; 
	 
	cc1100_fifo_get(data,1); 
	data[0] += 2; 
	 
	cc1100_fifo_get(&data[1],rxfifo->length);
}







void cc1101_carrier_wave_setup(void)
{
	u8 f_reg[3] = {0,0,0};
	u8 temp;


	if((gClient.status.input_data & 0xC0)==CA_WAVE_CH5)
	{

		#if 1
		f_reg[2] = 0x10;					//426.3625MHz(Ch5) nearly 426.362152MHz
		f_reg[1] = 0x66;
		f_reg[0] = 0x07;
		#endif
	}
	else if((gClient.status.input_data & 0xC0)==CA_WAVE_CH9)
	{

		#if 1
		f_reg[2] = 0x10;					//426.4625MHz(Ch9) nearly 426.462128MHz
		f_reg[1] = 0x67;
		f_reg[0] = 0x03;
		#endif
	}
	else if((gClient.status.input_data & 0xC0)==CA_WAVE_CH13)
	{

		#if 1
		f_reg[2] = 0x10;					//426.5625MHz(Ch13)
		f_reg[1] = 0x67;
		f_reg[0] = 0xFF;
		#endif
	}
	else if((gClient.status.input_data & 0xC0)==CA_WAVE_CH17)
	{

		#if 1
		f_reg[2] = 0x10;					//426.6625MHz(Ch17)	nearly 426.662476MHz
		f_reg[1] = 0x68;
		f_reg[0] = 0xFB;
		#endif

	}


	temp = f_reg[0];
	//eeprom_busy_wait();

	if((gClient.ctl.add_sub==0x80))
	{
		//eeprom_busy_wait(); 
		f_reg[0] = f_reg[0]-gClient.ctl.adj_freq;
		if(f_reg[0] > temp)
			f_reg[1] -= 1;
	}
	else{
		//eeprom_busy_wait(); 
		f_reg[0] = f_reg[0]+gClient.ctl.adj_freq;
		if(f_reg[0] < temp)
			f_reg[1] += 1;
	}

	cc1100_write_reg(CC1100_REG_FREQ2, f_reg[2]);
	cc1100_write_reg(CC1100_REG_FREQ1, f_reg[1]);
	cc1100_write_reg(CC1100_REG_FREQ0, f_reg[0]);


}






void init_voltcomparator(void)
{
	ACSR = 0x4b;
	DIDR1 = 0x02;
}







void init_ad(void)
{
	ADCSRA = 0b10000100; // AD許可:1 AD開始:0 AD自動起動:0 AD割込:0 AD完了割込:0 ck/16
    //ADMUX = 0xE7;       //AREF外部電圧、入力PC0

}


void ad_diseable(void)
{
	ADCSRA = 0b00000100; // AD許可:0 AD開始:0 AD自動起動:0 AD割込:0 AD完了割込:0 ck/16
    //ADMUX = 0x00;       //AREF外部電圧、入力PC0

}






void add_batt_low(void)
{
	#if 1
	B_CTL_HIGH;
	#endif
	mdelay(1);


	ad_get_val(&(gClient.status),AD_PIN_BATT_LOW,AD_VAL_FROM_L);

	gClient.status.bat_val = gClient.status.ad_data_h;


	#if 1
	B_CTL_LOW;
	#endif

}






// エラー
void i2c_error(void)
{
    //putch('['); puthex2(TWSR); putch(']'); // TWSRの内容
    //putch(0x0d); putch(0x0a); // 改行
    //PORTB = 0x01; // LED点灯
    while(1) ;
}

// 通信速度の初期化
void i2c_init(void)
{
    TWSR = 0b00000000;  // 1分周
    TWBR = 0;          // 250k = 4MHz / (16 + 2 * TWBR * 1)
    //TWBR = 32;          // 100k = 8MHz / (16 + 2 * TWBR * 1)
	//TWBR = 5;          // 50k = 8MHz / (16 + 2 * TWBR * 1)
	//TWBR = 255;          // 50k = 8MHz / (16 + 2 * TWBR * 1)
}



// master 1byte送信
void i2c_write(u8 d)
{
    TWDR = d; // 送信データ
    TWCR = _BV(TWINT) | _BV(TWEN);
    while( !(TWCR & _BV(TWINT)) ) ; // データの送出完了待機
    if((TWSR & TW_STATUS_MASK) != TW_MT_DATA_ACK) i2c_error();
}

// master 1byte受信(ackを返す)
u8 i2c_read_ack(void)
{
    TWCR = _BV(TWINT) | _BV(TWEN) | _BV(TWEA);
    while( !(TWCR & _BV(TWINT)) ) ; // 受信完了待ち
    if((TWSR & TW_STATUS_MASK) != TW_MR_DATA_ACK) i2c_error();
    return TWDR; // データを返す
}

// master 1byte受信(noackを返す)
u8 i2c_read_nak(void)
{
    TWCR = _BV(TWINT) | _BV(TWEN);
    while( !(TWCR & _BV(TWINT)) ) ; // 受信完了待ち
    if((TWSR & TW_STATUS_MASK) != TW_MR_DATA_NACK) i2c_error();
    return TWDR; // データを返す
}

// master送信開始、IDはslave address ＜＜ 1
void i2c_start(u8 id)
{
    u8 s;

    // 開始条件を送る
    TWCR = _BV(TWINT) | _BV(TWSTA) | _BV(TWEN);
    while( !(TWCR & _BV(TWINT)) ) ; // 開始条件の送出完了待機
    s = TWSR & TW_STATUS_MASK;
    if(s != TW_START && s != TW_REP_START) i2c_error();

    // アドレスを送る
    TWDR = id;
    TWCR = _BV(TWINT) | _BV(TWEN);
    while( !(TWCR & _BV(TWINT)) ) ; // アドレスの送出完了待機
    s = TWSR & TW_STATUS_MASK;
    if(s != TW_MT_SLA_ACK && s != TW_MR_SLA_ACK) i2c_error();
}

// master送信終了
void i2c_stop(void)
{
    TWCR = _BV(TWINT) | _BV(TWSTO) | _BV(TWEN);
    while( !(TWCR & _BV(TWSTO)) ) ;
    // statusはTW_NO_INFOになる
}


#define RTC_R2223L (0x32 << 1)    // RICOH RTC R2223L/Tのslave address


void rtc_1byte_data_write(u8 addr,u8 data)
{
	/*write*/
	i2c_start(RTC_R2223L | TW_WRITE);
	i2c_write((addr<<4)&0xf0); // register 4
	i2c_write(data); // 14bit resolution
	i2c_stop();
}


u8 rtc_1byte_data_read(u8 addr)
{
	u8 data;

	i2c_start(RTC_R2223L | TW_WRITE);
	i2c_write((addr << 4)&0xF0); // register 0
	i2c_start(RTC_R2223L | TW_READ);
	data = i2c_read_nak(); // 下位読み込み(最後はNAKを返す)
	i2c_stop();
	return data;
}


void rtc_3byte_data_read(u8 start_addr,u8 * data)
{
	i2c_start(RTC_R2223L | TW_WRITE);
	i2c_write((start_addr << 4)&0xF0); // register 0
	i2c_start(RTC_R2223L | TW_READ);
	data[0] = i2c_read_ack(); // 上位読み込み
	data[1] = i2c_read_ack(); // 上位読み込み
	data[2] = i2c_read_nak(); // 下位読み込み(最後はNAKを返す)
	i2c_stop();
}



u8 cnt_recierve_cnt=0;






void master_test(cc1101_client * client)
{
	u8 i=0;


    cc1100_init();
	cc1101_init_tx();

	while(1)
	{
		while(1)
		{
			client->rxfifo.length = cc1101_rx(client);
			if(client->rxfifo.length > 0)
			{
				client->status.status = WAIT_IVENT;
				break;
			}
			else if(gClient.status.status==REG_SLAVE_VIA_UART)
				return;
		}

		for(i=0;i<6;i++)
			client->txfifo.dest_serial[i] = client->rxfifo.src_serial[i];


		client->rxfifo.sessionflag = (client->status.sessionflag & 0xEF) | 0x10;	//SYN+ACK flag set	
		cc1101_tx(client);

		if(gClient.status.status == WAIT_IVENT)
		{
			
			if(reg_slave_num_serch()==SERACH_SLAVE_OK)
			{


				for(i=0;i<3;i++)
					puthex(client->rxfifo.src_serial[3+i]);

				putc(0x5c);		//\

				if((client->rxfifo.user_data1 & 0xF0)==0x10)
				{
					if((client->rxfifo.user_data1 & 0x05)==0x01)
						putc(0x31);									//S1 sensor
					else if((client->rxfifo.user_data1 & 0x05)==0x04)
						putc(0x54);									//Batt_low
					else
					{
						if(client->rxfifo.user_data1 & 0x08)			
							putc(0x32);								//S1 sensor and SR EMG active
						else
							putc(0x33);								//S1 sensor and SR EMG non_active
					}
				}


				putc(0x0d);
				putc(0x0a);

				#if 0
				B_CTL_HIGH;
				sdelay(3);
				B_CTL_LOW;
				#endif

			}
		}
	}


}



void reg_device_num_chk(void)
{
	u8 i=0;
	u8 j= 0;

	reg_slave_eeprom2reg();

	for(i=0;i<100;i++)
	{
		putc(0x45);
		putc(0x50);
		puthex(i);
		putc(0x5C);
		for(j=0;j<3;j++)
		{
			puthex(gClient.status.reg_slave[i].serial[j]);
		}
		putc(0x0d);
		putc(0x0a);
	}
}


void reg_slave_eeprom_del(void)
{
	u16 i;

	for(i=0;i<300;i++)					//Device Entry Delete on eeprom
	{
		eeprom_busy_wait(); 
		eeprom_write_byte((511-i),0xFF);
		//i++;
	}
}



u8 reg_slave_num_serch(void)
{
	u8 i=0;
	u8 j=0;
	u8 temp=0;

	for(i=0;i<100;i++)
	{
		for(j=0;j<3;j++)
		{
			if(gClient.status.reg_slave[i].serial[2-j]==gClient.rxfifo.src_serial[3+j])
				temp++;
		}

		if(temp==3)
		{
			//client->status.status = REG_DEVICE_ERR;
			//break;
			return SERACH_SLAVE_OK;
		}
		else
			temp=0;
	}
	return SERACH_SLAVE_NG;
}
	 
	 
u8 	my_eeprom_read(u16 addr)	 
{	 
	eeprom_busy_wait(); 
	eeprom_read_byte(addr); 
} 
	 
void 	my_eeprom_write(u16 addr,u8 data)	 
{	 
	eeprom_busy_wait(); 
	eeprom_write_byte(addr,data); 
	eeprom_read_byte(addr); 
} 


void reg_slave_eeprom2reg(void)
{
	u8 i=0;
	u8 j=0;
	u16 temp=0;

	for(i=0;i<100;i++)
	{
		for(j=0;j<3;j++)
	 	{
			gClient.status.reg_slave[i].serial[2-j] = my_eeprom_read(511-temp);
			temp++;
		}
	}
}



void reg_slave_reg2eeprom(void)
{
	u8 i=0;
	u8 j=0;
	u16 temp=0;

	for(i=0;i<100;i++)
	{
		for(j=0;j<3;j++)
	 	{
			my_eeprom_write(511-temp,gClient.status.reg_slave[i].serial[2-j]);
			temp++;
		}
	}
}


void reg_device_master_test(cc1101_client * client)
{
	u16 i=0;
	u8 j=0;
	u8 temp=0;


	if((client->status.input_data&0x30)==0x30)
	{

		reg_slave_eeprom_del();


		led_flasher(100,50);

		reg_device_num_chk();

		while(1);
	}



    cc1100_init();
	cc1101_init_tx();

	while(1)
	{
		while(1)
		{
			client->rxfifo.length = cc1101_rx(client);
			if(client->rxfifo.length > 0)
			{
				client->status.status = REG_DEVICE_NEW_ENTRY;
				break;
			}
		}
		client->status.sessionflag = (client->status.sessionflag & 0xEF) | 0x10;	//SYN+ACK flag set	
		cc1101_tx(client);

		if(client->status.status == REG_DEVICE_NEW_ENTRY)
		{
			if(reg_slave_num_serch()==SERACH_SLAVE_OK)
				client->status.status=REG_DEVICE_ERR;

		}


		if(client->status.status == REG_DEVICE_NEW_ENTRY)
		{
			for(i=0;i<100;i++)
			{
				for(j=0;j<3;j++)
				{
					if(client->status.reg_slave[i].serial[2-j]==0xFF)
						temp++;
					

				}

				if(temp==3)
				{
					for(j=0;j<3;j++)
					{
						client->status.reg_slave[i].serial[j]=client->rxfifo.src_serial[3+j];
					}
					break;
				}
				else
					temp=0;
			}

			reg_slave_reg2eeprom();

		}

		if(client->status.status == REG_DEVICE_NEW_ENTRY)
			led_flasher(50,10);
		else
			led_flasher(2,500);


		reg_device_num_chk();

		while(1);


	}
}















ISR(USART_RX_vect)
{
	u8 i=0;
	//test_cnt02++;
	test_cnt02=UDR0;
	putc(test_cnt02);
	//puthex(test_cnt02);


	//cnt_char=0;
	rx_char[cnt_char++]=test_cnt02;


	if(rx_char[cnt_char-1]==0x0d)
	{
		gClient.status.status=REG_SLAVE_VIA_UART;

		for(i=0;i<cnt_char;i++)
			if(rx_char[i]==0x20)break;

		cmd_length=i;

	}


	#if 0
	puthex(test_cnt02);
	mdelay(100);


	if(test_cnt02==0x63)		//"c"ancel
		cnt_recierve_cnt=0;


	putc(0x52);		//R
	putc(0x58);		//X
	puthex(cnt_recierve_cnt);
	putc(0x0d);
	putc(0x0a);
	#endif
	//puthex(0x55);
	//putc(0x47);
	//putc(0x4a);
}


//u8 rx_data[20];




u8 edge_val_gdo0;
u8 edge_val_gdo2;

u8 gdo0_status;
u8 gdo2_status;


#if 0
enum {
	LOW_EDGE=0,
	HIGH_EDGE
};

#endif

enum {
	GDO_OK=0,
	GDO_WAIT
};





#if 1
//#define GDO0_INT_SET_RISING()  P1IES &= ~GDO0_PIN
void GDO0_INT_SET_RISING(void)
{
	edge_val_gdo0 = HIGH_EDGE;
}
//#define GDO0_INT_SET_FALLING() P1IES |=  GDO0_PIN
void GDO0_INT_SET_FALLING(void)
{
	edge_val_gdo0 = LOW_EDGE;
}


//#define GDO2_INT_SET_RISING()  P1IES &= ~GDO2_PIN
void GDO2_INT_SET_RISING(void)
{
	edge_val_gdo2 = HIGH_EDGE;
}
//#define GDO2_INT_SET_FALLING() P1IES |=  GDO2_PIN
void GDO2_INT_SET_FALLING(void)
{
	edge_val_gdo2 = LOW_EDGE;
}

//#define GDO0_READ() (P1IN & GDO0_PIN)
u8 GDO0_READ(void)
{
	return (PINC & 0x04);
}
//#define GDO2_READ() (P1IN & GDO2_PIN)
u8 GDO2_READ(void)
{
	return (PINC & 0x08);
}
#endif

 

#if 0


ISR(PCINT1_vect)
{
	//u8 test;
	//send_byte(1);

	#if 1
	if((edge_val_gdo0==0x00)&&((PINC&0x04)==0x00))
		gdo0_status = GDO_OK;
	else if((edge_val_gdo0==0x01)&&((PINC&0x04)==0x00))
		gdo0_status = GDO_OK;
	else if((edge_val_gdo2==0x00)&&((PINC&0x08)==0x00))
		gdo2_status = GDO_OK;
	else if((edge_val_gdo2==0x01)&&((PINC&0x08)==0x00))
		gdo2_status = GDO_OK;		
	#endif




	//status = SEND_UART_RX_DATA;
}

#endif



void cc1101_gdo0_sig_wait(void)
{
	//gdo0_status = GDO_WAIT;

	//while(gdo0_status == GDO_WAIT);
	while(gdo0_status == 0x01);

}










void cc1101_tx_carrier(cc1101_client * client)
{

	cc1101_carrier_wave_setup();


	#if 0
	pt_data[0] = 0xC0;			//10dB
	pt_data[1] = 0xC0;			//
	#endif

	cc1101_8PATABLE_write_reg(pt_data);
	cc1100_cfg_txoff_mode(CC1100_TXOFF_MODE_STAY_TX);
	cc1100_cfg_manchester_en(CC1100_MANCHESTER_DISABLE);
	cc1100_write_reg(CC1100_REG_MDMCFG3,0x33);
	cc1100_cfg_mod_format(CC1100_MODULATION_ASK);
	cc1100_write_reg(CC1100_REG_FREND0,0x10);
	cc1100_cfg_gdo0(CC1100_GDOx_CLK_XOSC_1);

	#if 0
	reg_check();
	cc1100_read_reg_uartout(CC1100_PATABLE_ADDR);
	cc1101_8PATABLE_read_reg();
	#endif


	cc1100_cmd_idle();
	cc1100_cmd_flush_tx();
	cc1100_cmd_calibrate();
	mdelay(10);
	cc1100_cfg_gdo0(0x0e);
	while(PINC&0x04);		//Carrier sense
	cc1100_cmd_tx();


}









void cc1101_tx(cc1101_client * client)
{


	cc1101_init_tx();
	cc1100_cmd_flush_tx();
	cc1100_cmd_idle();
	cc1100_cmd_calibrate();
	cc1100_cfg_gdo0(CC1100_GDOx_SYNC_WORD);
	mdelay(5);
	

	#if 0
	cc1100_read_reg_uartout((CC1100_REG_TXBYTES | CC1100_ACCESS_STATUS));
	#endif
	tx_fifo_set(&(client->txfifo));
	
	#if 0
	cc1100_read_reg_uartout(CC1100_REG_MARCSTATE | CC1100_ACCESS_STATUS);
	#endif
	cc1100_cfg_gdo0(0x0e);
	while(PINC&0x04);		//Carrier sense
	cc1100_cfg_gdo0(CC1100_GDOx_SYNC_WORD);
	cc1100_cmd_tx();
	//mdelay(100);
	while(!(PINC&0x04))	//data send start
	{
		#if 0
		cc1100_read_reg_uartout((CC1100_REG_TXBYTES | CC1100_ACCESS_STATUS));
		cc1100_read_reg_uartout(CC1100_REG_MARCSTATE | CC1100_ACCESS_STATUS);
		sdelay(1);
		#endif
	}
	while(PINC&0x04);		//data send end

}


uint16_t cc1101_rx(cc1101_client * client)
{
	u8 cnt_wait_syn_ack;

	client->rxfifo.length=0;
	cc1100_cmd_flush_tx();
	cc1100_cmd_idle();
	cc1101_init_rx();
	cc1100_cmd_idle();
	mdelay(2);
	cc1100_cmd_flush_rx();
	cc1100_cfg_gdo0(CC1100_GDOx_RX_OK);
	cc1100_cmd_calibrate();
	mdelay(2);
	cc1100_cmd_rx();
	mdelay(2);

	#if 0
	cc1100_read_reg(CC1100_REG_MARCSTATE | CC1100_ACCESS_STATUS);
	#endif
	cnt_wait_syn_ack = 0;

	while(1)
	{

		#if 1				


		if(PINC&0x04)
		{	
			#if 0
			cc1100_read_reg_uartout(CC1100_REG_RSSI | CC1100_ACCESS_STATUS);
			cc1100_read_reg(CC1100_REG_RXBYTES | CC1100_ACCESS_STATUS);
			#endif
			//B_CTL_HIGH;	//LED_ON
			rx_fifo_get(&(client->rxfifo));
			//status = DATA_WAVEOUT_SYN_ACK_VERIFY;
			break;
		}
		else
		{	
			if(cc1100_read_reg(CC1100_REG_MARCSTATE | CC1100_ACCESS_STATUS)!=0x0d)
			{
				#if 0
				cc1100_read_reg_uartout(CC1100_REG_RSSI | CC1100_ACCESS_STATUS);
				#endif
				//B_CTL_LOW;	//LED_OFF
				client->rxfifo.length=0;
				//status = DATA_OUT_SETUP;
				break;
			}
		}


		mdelay(20);
		#endif

		cnt_wait_syn_ack++;
		//if(cnt_wait_syn_ack>10)
		if(cnt_wait_syn_ack>20)
		{
			client->rxfifo.length=0;
			break;
		}
	}

	
	if(client->rxfifo.length > 0)
		return client->rxfifo.length;
	else
		return 0;

}





void slave_test(cc1101_client * client)
{
	u8 temp_cnt=0;
	u8 i=0;

	client->rxfifo.length=0;
	client->status.sessionflag = 0x02;	//SYN flag set

	while(1)
	{
		cc1101_tx(client);

		client->rxfifo.length = cc1101_rx(client);
		if(client->rxfifo.length > 0)
		{
			for(i=0;i<3;i++)
			{
				if(client->status.serial[3+i]!=client->rxfifo.dest_serial[3+i])
					break;
			}


			if(i==3)
			{
				client->status.status = SEND_COMPLETE;
				client->status.send_err_cnt = 0;
				return;
			}
		}
		else
		{
			if(temp_cnt>6)
			{
				client->status.status = WAIT_2SEC;
				client->status.send_err_cnt++;
				if(client->status.send_err_cnt>8)
				{
					client->status.status = WAIT_IVENT;
					client->status.send_err_cnt=0;
					return;
				}
				//rtc_set_2sec_next_alarm();
				rtc_set_next_alarm(ALARM_2SEC);
				return;

			}
			temp_cnt++;
		}
	}
}



void temperature_test_enable(void)
{
	//cc1101_tx_carrier(&gClient);
	cc1100_write_reg(CC1100_REG_PTEST,0xBF);
	cc1100_cfg_gdo0(0x80);
}



void temperature_test_disenable(void)
{

	cc1100_cfg_gdo0(0x3F);
	cc1100_write_reg(CC1100_REG_PTEST,0x7F);

}




void temperature_get(void)
{

	PORTC &= ~(1<<PC2);	//pull-up disenable
	temperature_test_enable();
	mdelay(100);

	temperature_chk();
	#if 1
	temperature_test_disenable();
	#endif
	PORTC |= (1<<PC2);		//pull-up enable
	mdelay(100);

}


void temperature_chk(void)
{
	//u8 temp_data_h=0;
	//u8 temp_data_l=0;
	//u8 i=0;

	DIDR0 |= (1<<ADC2D);		//ADC2 Digital disable




	#if 0

	init_ad();

	ADMUX = 0xC2;       //AREF外部電圧、for PC2(ADC2)

	for(i=0;i<5;i++)
	{
		ADCSRA |= _BV(ADSC);					//変換開始 要ﾙｰﾌﾟ内
		while((ADCSRA&0x10)==0x00);

		ADCSRA |= (1<<ADIF);					//ADIF clear

		#if 1
		temp_data_l = ADCL;
		temp_data_h = ADCH;

		#endif
	}

	gClient.status.reserve[1] = temp_data_h;
	gClient.status.reserve[2] = temp_data_l;


	//a = ( ADC >> 4 );						//AD変換結果 4bitｼﾌﾄ= 6bit:0-64
	ad_diseable();

	#endif

	ad_get_val(&(gClient.status),AD_PIN_TEMPERATURE,AD_VAL_FROM_L);



	DIDR0 &= ~(1<<ADC2D);		//ADC2 Digital enable
	//return temp_data;

}




ISR(INT1_vect)
{

	spi_signalpin_opendrain_nonactive();

	if(gClient.status.status != SLEEP_TIME)
		rtc_alarm_disenable();

	gClient.status.input_data = ~get_input_data();
	alert_data_get(&gClient);


	sig_set();


	temp_user_data_new = gClient.status.make_alert;
	temp_user_data_old = gClient.status.make_alert_old;


	temp_user_data = ((gClient.status.make_alert_old ^ gClient.status.make_alert) & 0x0F);	//XOR


	if(temp_user_data & 0x04)	//S2 check
		gClient.status.status = WAIT_IVENT;


	if(temp_user_data & 0x02)	//TAMPA check
		gClient.status.status = WAIT_IVENT;




	#if 1
	led_flasher(5,50);
	#endif

}



ISR(INT0_vect)
{

	spi_signalpin_opendrain_nonactive();

	alert_data_get(&gClient);
	sig_set();

	#if 1
	if(gClient.status.status != SLEEP_TIME)
		rtc_alarm_disenable();
	#endif


	if(gClient.status.status == WAIT_IVENT)
		gClient.status.status=TEST_1DAY_SIG;


	if(gClient.status.status == SLEEP_TIME)
	{
		gClient.status.status = SLEEP_TIME_END;
		rtc_alarm_disenable();
	}

	#if 1
	led_flasher(5,50);
	test_cnt++;
	#endif
}








void device_status_setup(void)
{
	u8 i=0;
	//u8 j=0;
	//u16 temp=0;

	
	gClient.status.serial[0]=0x4d;	//M
	gClient.status.serial[1]=0x33;	//3
	gClient.status.serial[2]=0x33;	//3
	eeprom_busy_wait(); 
	gClient.status.serial[3]=eeprom_read_byte(0x02);	//serial no 01
	eeprom_busy_wait(); 
	gClient.status.serial[4]=eeprom_read_byte(0x03);	//serial no 02
	eeprom_busy_wait(); 
	gClient.status.serial[5]=eeprom_read_byte(0x04);	//serial no 03

	eeprom_busy_wait(); 
	gClient.ctl.adj_freq = eeprom_read_byte(0x00);	//value for adjust carrier frequency
	eeprom_busy_wait(); 
	gClient.ctl.add_sub = eeprom_read_byte(0x01);		//calc select ctl add or sub for adjust carrier frequeny

	for(i=0;i<8;i++)
	{
		gClient.status.reserve[i] =0x00; 
	}


	for(i=0;i<6;i++)
	{
		gClient.txfifo.src_serial[i] = gClient.status.serial[i];
	}

	gClient.txfifo.dest_serial[0]=0x4d;	//M
	gClient.txfifo.dest_serial[1]=0x33;	//3
	gClient.txfifo.dest_serial[2]=0x33;	//3
	gClient.txfifo.dest_serial[3]=0x04;	//3
	gClient.txfifo.dest_serial[4]=0x04;	//3
	gClient.txfifo.dest_serial[5]=0x04;	//3

	#if 0
	eeprom_busy_wait(); 
	gClient.status.system_osc=eeprom_read_byte(0x05);	//system_osc
	#endif
	//gClient.status.system_osc=0x00;
	gClient.status.send_err_cnt=0;

	gClient.status.version_l=0x1C;	//program version
	//gClient.status.reserve[0]=gClient.status.version_l;



	
	gClient.status.input_data = ~get_input_data();


	if((gClient.status.input_data&0x0c)==0x0c)
		gClient.status.type = MASTER;
	else
		gClient.status.type = SLAVE;


	#if 1
	if((gClient.status.input_data&0x30)==0x30)
		gClient.status.sleep_time = ALARM_5MIN;
	else if((gClient.status.input_data&0x30)==0x20)	
		gClient.status.sleep_time = ALARM_2MIN;
	else if((gClient.status.input_data&0x30)==0x10)	
		gClient.status.sleep_time = ALARM_1MIN;
	else
		gClient.status.sleep_time = ALARM_2SEC; 
	#endif




	#if 1

	reg_slave_eeprom2reg();


	#if 0

	for(i=0;i<100;i++)
	{
		putc(0x45);
		putc(0x50);
		puthex(i);
		putc(0x5C);
		for(j=0;j<3;j++)
		{
			puthex(gClient.status.reg_slave[i].serial[j]);
		}
		putc(0x0d);
		putc(0x0a);
	}
	#endif

	#endif


	gClient.status.reg_cmd[0].length = 2;
	gClient.status.reg_cmd[0].cmd[0] = 0x77;	//w
	gClient.status.reg_cmd[0].cmd[1] =0x72;		//r

	gClient.status.reg_cmd[1].length = 2;
	gClient.status.reg_cmd[1].cmd[0] = 0x72;	//r
	gClient.status.reg_cmd[1].cmd[1] = 0x64;	//d


	gClient.status.reg_param[0].length = 2;
	gClient.status.reg_param[0].param[0] = 0x69;		//i
	gClient.status.reg_param[0].param[1] = 0x64;	//d

	gClient.status.reg_param[1].length = 3;
	gClient.status.reg_param[1].param[0] = 0x63;	//c
	gClient.status.reg_param[1].param[1] = 0x74;	//t
	gClient.status.reg_param[1].param[2] = 0x6c;	//l

	gClient.status.reg_param[2].length = 3;
	gClient.status.reg_param[2].param[0] = 0x65;	//e
	gClient.status.reg_param[2].param[1] = 0x6d;	//m
	gClient.status.reg_param[2].param[2] = 0x67;	//g

}







void led_flasher(u8 count,u16 msec)
{
	u8 i=0;
	while(i<count)
	{
		B_CTL_HIGH;
		mdelay(msec);
		B_CTL_LOW;
		mdelay(msec);
		i++;
	}
}


#if 0

void eeprom_chk(void)
{

	putc(0x45);
	putc(0x50);
	puthex(0x00);
	eeprom_busy_wait(); 
	puthex(eeprom_read_byte(0x00));
	putc(0x0d);
	putc(0x0a);


	putc(0x45);
	putc(0x50);
	puthex(0x01);
	eeprom_busy_wait(); 
	puthex(eeprom_read_byte(0x01));
	putc(0x0d);
	putc(0x0a);
}

#endif


void rtc_set_next_alarm(u8 alarm)
{
	u8 hour=0;
	u8 min=0;
	u8 sec=0;

	rtc_1byte_data_write(0x0E,0x00);		//Alarm enable disenable


	rtc_1byte_data_write(0x0C,0x10);		//Alarm 10:00
	rtc_1byte_data_write(0x0B,0x00);



	if(alarm==ALARM_2SEC)
	{
		hour=0x09;
		min=0x59;
		sec=58;
	}
	else if(alarm==ALARM_30SEC)
	{
		hour=0x09;
		min=0x59;
		sec=30;
	}
	else if(alarm==ALARM_1MIN)
	{
		hour=0x09;
		min=0x59;
		sec=00;
	}
	else if(alarm==ALARM_2MIN)
	{
		hour=0x09;
		min=0x58;
		sec=00;		
	}
	else if(alarm==ALARM_3MIN)
	{
		hour=0x09;
		min=0x57;
		sec=00;		
	}
	else if(alarm==ALARM_5MIN)
	{
		hour=0x09;
		min=0x55;
		sec=00;	
	}
	else if(alarm==ALARM_30MIN)
	{
		hour=0x09;
		min=0x30;
		sec=00;	
	}
	else if(alarm==ALARM_1hour)
	{
		hour=0x09;
		min=0x00;
		sec=00;
	}
	else
	{
		hour=0x10;
		min=0x00;
		sec=01;
	}

	rtc_1byte_data_write(0x02,hour);		//current time 9:59:55
	rtc_1byte_data_write(0x01,min);
	rtc_1byte_data_write(0x00,sec);

	rtc_1byte_data_write(0x0E,0x40);		//Alarm enable enable
}





void rtc_alarm_disenable(void)
{
	rtc_1byte_data_write(0x0E,0x00);		//Alarm enable disenable
}


void sig_set(void)
{
	//temp = gClient.status.alert;
	//gClient.status.make_alert = temp;


	if((gClient.status.alert & 0x06) != (gClient.status.alert_old_temp & 0x06))
	{
		if((gClient.status.alert & 0x06)==0x02)
			gClient.status.make_alert |= (1<<2); 	//S2 & SR RESET
		else
			gClient.status.make_alert &= ~(1<<2); 	//S2 & SR SET

	}


	if(gClient.status.alert & 0x01)
		gClient.status.make_alert &= ~(1<<3);	//EMG reset 
	else
		gClient.status.make_alert |= (1<<3);	//EMG set 




	if(gClient.status.alert & 0x08)
		gClient.status.make_alert |= (1<<1);	//TAMPA set 			
	else
		gClient.status.make_alert &= ~(1<<1);		//TAMPA reset 



	if(gClient.status.bat_val < 0x50)
		gClient.status.make_alert |= (1<<0);	// BATT_LOW active
	else
		gClient.status.make_alert &= ~(1<<0);	// BATT_LOW non active



}










#if 0
u8 sai(void)
{
	u8 temp_sai;

	temp_sai = rand() % 6 + 1;
	return temp_sai;
}
#endif



int main()
{



	#if 1
	hw_setup();
	inituart();
	i2c_init();
	#endif

	device_status_setup();

    cc1100_init();

	cc1101_8PATABLE_write_reg(pt_data);

	#if 0
	reg_check();
	cc1100_read_reg_uartout(CC1100_PATABLE_ADDR);
	cc1101_8PATABLE_read_reg();
	#endif


	#if 1
	status = STARTUP;
	set_sleep_mode(SLEEP_MODE_PWR_DOWN);
	#endif

	led_flasher(2,100);



	#if 1
	if(gClient.status.type == SLAVE)
	{
		EIMSK |= (1<<INT0);
		EIMSK |= (1<<INT1);
	}
	#endif

	#if 1
	if((gClient.status.input_data&0x0c)==0x00)
		gClient.status.status=WAIT_IVENT;
	else if((gClient.status.input_data&0x0c)==0x04)
		gClient.status.status=TEST_CARRIER_WAVE;
	else if((gClient.status.input_data&0x0c)==0x0C)
		gClient.status.status=WAIT_RX;
	else
		gClient.status.status=TEST_CLK;
	#endif




	sei();

	spi_signalpin_opendrain_nonactive();


	#if 1

	if(gClient.status.type == SLAVE)
	{
		rtc_alarm_disenable();
		//rtc_set_1hour_next_alarm();
		//rtc_set_2sec_next_alarm();
		//rtc_set_1day_alarm();
		//rtc_set_1min_next_alarm();
	}
	#endif

	puthex(0x01);


	/* Enter the infinite loop */
    while (1)
    {
		#if 1

		if(gClient.status.status==WAIT_RX)
		{
			cc1101_tx_carrier(&gClient);
			sdelay(30);
			master_test(&gClient);

		}
		else if(gClient.status.status==TEST_CLK)
		{

		}
		else if(gClient.status.status==TEST_CARRIER_WAVE)
		{

		}
		else
		{


			if(gClient.status.status == WAIT_2SEC)
			{
				//rtc_set_2sec_next_alarm();
				rtc_set_next_alarm(ALARM_2SEC);
				#if 0
				led_flasher(WAIT_2SEC,500);
				#endif
			}
			else if(gClient.status.status == SLEEP_TIME_END)
			{
				#if 0
				led_flasher(SLEEP_TIME_END,500);
				#endif
				gClient.status.status = WAIT_IVENT;
				//EIMSK |= (1<<INT1);
				//rtc_set_1min_next_alarm();
				//rtc_set_5min_next_alarm();
			}
			else if(gClient.status.status == SLEEP_TIME)
			{
				//led_flasher(SLEEP_TIME,500);

			}


			if(gClient.status.status == WAIT_IVENT)
			{
				//rtc_set_1min_next_alarm();
				//rtc_set_1day_alarm();
				//rtc_set_5min_next_alarm();
				//rtc_set_1hour_next_alarm();
				//rtc_set_30min_next_alarm();
				rtc_set_next_alarm(ALARM_30MIN);
				
				#if 0
				led_flasher(WAIT_IVENT,500);
				#endif
			}

			#if 1
			cc1100_cmd_idle();
			cc1100_cmd_pwd();
			#endif
			spi_signalpin_opendrain_active();


			sleep_mode();
			
		}


		if(gClient.status.status==TEST_1DAY_SIG)
			gClient.status.user_data1 = ((gClient.status.make_alert & 0x1A) | 0x10);
			//gClient.status.make_alert = ((gClient.status.make_alert & 0x1A) | 0x10);	//TEST_SIG_SET

		
		if(gClient.status.status==WAIT_IVENT)
		{

			gClient.status.user_data1 = ((temp_user_data & 0x2F) | 0x20);	//EMG_SIG_SET

		}




		if(gClient.status.status==WAIT_IVENT || gClient.status.status==WAIT_2SEC || gClient.status.status==TEST_1DAY_SIG)
			slave_test(&gClient);


		if(gClient.status.status == SEND_COMPLETE)
		{
			led_flasher(1,700);
			#if 0
			B_CTL_HIGH;
			sdelay(3);
			B_CTL_LOW;
			#endif
			gClient.status.make_alert_old = (gClient.status.make_alert & 0x05);	//TAMPA and S1 reset
			gClient.status.status=SLEEP_TIME;
			rtc_set_next_alarm(gClient.status.sleep_time);
			//sleep_time_cnt = gClient.status.sleep_time;

		}
		

	
		//if(gClient.status.status == SLEEP_TIME)
		//	rtc_set_next_alarm(ALARM_30SEC);






		if(gClient.status.status==TEST_CARRIER_WAVE)
		{
			#if 0
			add_batt_low();
			temperature_get();
			cc1101_tx(&gClient);
			rtc_set_2sec_next_alarm();
			#endif


			#if 1
			add_batt_low();

			cc1101_tx(&gClient);
			#if 1
			cc1101_tx_carrier(&gClient);
			cc1100_cfg_gdo0(0x30);		//26MHz XOSC/1  output
			#endif

			while(1);
			#endif



		}



		if(gClient.status.status==TEST_CLK)
		{

			reg_device_master_test(&gClient);



			#if 0
			add_batt_low();

			cc1101_tx(&gClient);
			#if 1
			cc1101_tx_carrier(&gClient);
			cc1100_cfg_gdo0(0x30);		//26MHz XOSC/1  output
			#endif

			while(1);
			#endif
		}


		#if 0
		if(gClient.status.status==REG_SLAVE_VIA_UART)
		{
			switch(cmd_length)
			{
				case 2:
					for(i=0;i<2;i++)
					{
						cmd_ad
					}



					break;
				case 5:

					break;
				case 6:

					break;
				case 7:

					break;
				case 8:
					break;
				default:
					break;

			}

			for(i=0;i<cmd_select_cnt;i++)
			{
				for(j=0;j<cmd_length;j++)
					if
			}
		}
		#endif



	#endif
	}
}


