#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/eeprom.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 TEST				REGISTER_BIT(PORTC,0)

#define OUTPUT				REGISTER_BIT(PORTC,1) 
#define SCLR				REGISTER_BIT(PORTC,3) 
#define SCLK				REGISTER_BIT(PORTC,2) 
#define CLK					REGISTER_BIT(PORTC,4) 
#define S_DATA				REGISTER_BIT(PORTC,5) 

#define BUZZER				REGISTER_BIT(PORTD,4) 
#define TX_EN				REGISTER_BIT(PORTD,3) 


#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

#define S_CLK_HIGH			SCLK = 1
#define S_CLK_LOW			SCLK = 0

#define CLK_HIGH			CLK = 1
#define CLK_LOW				CLK = 0

#define S_DATA_HIGH			S_DATA = 1
#define S_DATA_LOW			S_DATA = 0


/*

#define CNT_SEC		0x00;
#define CNT_MINUTES	0x01;
#define CNT_HOUR	0x02;
#define CNT_DAY		0x03;
#define 
#define 
#define 
#define 
#define 
#define 

*/


void cc1101_carrier_wave_setup(u8 input_data);
void cc1101_8PATABLE_write_reg(u8 * reg);
void led_flasher(u8 count,u16 msec);
void rtc_set_1day_alarm(void);
void rtc_set_5sec_next_alarm(void);
void rtc_set_2sec_next_alarm(void);
uint16_t cc1101_rx(cc1101_client * client);
void cc1101_tx(cc1101_client * client);
//trh_card_t card;



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

u8 chk_state=0;

u8 test1;
u8 test2;
u8 test3;
volatile u8 input_data=0;
u8 new_input_data=0;

//u8 status=0;


u8 a;
u8 b;
u8 th[3]={0,0,0};
u8 tl[3]={0,0,0};
u8 t_temp[3]={0,0,0};
u8 test_temp;
u8 test_temp2;
u8 test_temp3;
u8 test_temp4;


u8 snnum00=0;
u8 snnum01=0;
u8 snnum02=0;
u8 master_rssi=0;
u8 master_lqi=0;

enum {
	KEY_CHK=0,
	CA_OUT_SETUP,
	DATA_OUT_SETUP,
	CA_WAVEOUT,
	DATA_WAVEOUT,
	FIFO_SETUP,
	DATA_WAVEOUT_WAIT_SYN_ACK_ACK_SETUP,
	DATA_WAVEOUT_WAIT_SYN_ACK,
	DATA_WAVEOUT_SYN_ACK_VERIFY,
	DATA_WAVEOUT_OK_CNT,
	DATA_WAVEOUT_QUIT,
	CA_KEY_CHANGE_CHK,
	DATA_KEY_CHANGE_CHK,
	RX_RSSI_SETUP,
	RX_RSSI_START,
	RX_RSSI_WAIT,
	RSSI_SEND_UART_RX_DATA,
	RX_SETUP,
	RX_START,
	RX_WAIT,
	RX_DATA_CNT,
	RX_DATA_TX_SYN_ACK_SETUP,
	RX_DATA_TX_SYN_ACK,
	SEND_UART_RX_DATA,
	RX_VERIFY_START,
	RX_VERIFY_WAIT,
	RX_VERIFY,
	LOOP_OUT
};


enum {
	WAIT_IVENT=0,
	WAIT_2SEC


};






#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,u8 osc_speed)
{
	register u16 i;

	if(osc_speed == OSC_8MHZ)
	{
		for(i = 0 ; i < msec  ; i++)
		{
			udelay(250);
			udelay(250);
			udelay(250);
			udelay(250);
		}
	}
	else
	{

		for(i = 0 ; i < msec  ; i++)		//for system_osc 1MHz
		{
		udelay(120);
		}



		#if 0
		for(i = 0 ; i < msec  ; i++)		//for system_osc 128kHz
		{
		udelay(16);
		}
		#endif
	}
}


#endif

void sdelay(u16 msec)
{
	register u16 i;

	for(i=0;i<msec;i++)
	{
		mdelay(1000,gClient.status.system_osc);
	}
}







/*
 	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);
}


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 1			//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
}


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)
{
//	u8 i;

	test_cnt02++;
	TCNT2=0;

	#if 0
	for(i=0;i<5;i++)
	{
		B_CTL_LOW;
		mdelay(100);
		B_CTL_HIGH;
		mdelay(100);
	}
	#endif


}  


void hw_setup(void)
{

    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,0xC0,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);

	pt_data[0] = 0xC0;			//10dB
	pt_data[1] = 0x00;			//
	pt_data[2] = 0x00;		//
	pt_data[3] = 0x00;		//
	pt_data[4] = 0x00;		//

	cc1101_carrier_wave_setup(input_data);
	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);
	pt_data[0] = 0xC0;			//10dB
	pt_data[1] = 0x00;			//
	//cc1101_data_waveoutput_setup(input_data,pt_data);
	cc1101_carrier_wave_setup(input_data);
	cc1101_8PATABLE_write_reg(pt_data);


	cc1100_write_reg(CC1100_REG_MDMCFG4,0xF8);

}




#endif






void reg_check(void)
{

	cc1100_read_reg_uartout(CC1100_REG_IOCFG2);
	cc1100_read_reg_uartout(CC1100_REG_IOCFG1);
	cc1100_read_reg_uartout(CC1100_REG_IOCFG0);
	cc1100_read_reg_uartout(CC1100_REG_FIFOTHR);
	cc1100_read_reg_uartout(CC1100_REG_SYNC1);
	cc1100_read_reg_uartout(CC1100_REG_SYNC0);
	cc1100_read_reg_uartout(CC1100_REG_PKTLEN);
	cc1100_read_reg_uartout(CC1100_REG_PKTCTRL1);
	cc1100_read_reg_uartout(CC1100_REG_PKTCTRL0);
	cc1100_read_reg_uartout(CC1100_REG_ADDR);
	cc1100_read_reg_uartout(CC1100_REG_CHANNR);
	cc1100_read_reg_uartout(CC1100_REG_FSCTRL1);
	cc1100_read_reg_uartout(CC1100_REG_FSCTRL0);
	cc1100_read_reg_uartout(CC1100_REG_FREQ2);
	cc1100_read_reg_uartout(CC1100_REG_FREQ1);
	cc1100_read_reg_uartout(CC1100_REG_FREQ0);
	cc1100_read_reg_uartout(CC1100_REG_MDMCFG4);
	cc1100_read_reg_uartout(CC1100_REG_MDMCFG3);
	cc1100_read_reg_uartout(CC1100_REG_MDMCFG2);
	cc1100_read_reg_uartout(CC1100_REG_MDMCFG1);
	cc1100_read_reg_uartout(CC1100_REG_MDMCFG0);
	cc1100_read_reg_uartout(CC1100_REG_DEVIATN);
	cc1100_read_reg_uartout(CC1100_REG_MCSM2);
	cc1100_read_reg_uartout(CC1100_REG_MCSM1);
	cc1100_read_reg_uartout(CC1100_REG_MCSM0);
	cc1100_read_reg_uartout(CC1100_REG_FOCCFG);
	cc1100_read_reg_uartout(CC1100_REG_BSCFG);
	cc1100_read_reg_uartout(CC1100_REG_AGCCTRL2);
	cc1100_read_reg_uartout(CC1100_REG_AGCCTRL1);
	cc1100_read_reg_uartout(CC1100_REG_AGCCTRL0);
	cc1100_read_reg_uartout(CC1100_REG_WOREVT1);
	cc1100_read_reg_uartout(CC1100_REG_WOREVT0);
	cc1100_read_reg_uartout(CC1100_REG_WORCTRL);
	cc1100_read_reg_uartout(CC1100_REG_FREND1);
	cc1100_read_reg_uartout(CC1100_REG_FREND0);
	cc1100_read_reg_uartout(CC1100_REG_FSCAL3);
	cc1100_read_reg_uartout(CC1100_REG_FSCAL2);
	cc1100_read_reg_uartout(CC1100_REG_FSCAL1);
	cc1100_read_reg_uartout(CC1100_REG_FSCAL0);
	cc1100_read_reg_uartout(CC1100_REG_RCCTRL1);
	cc1100_read_reg_uartout(CC1100_REG_RCCTRL0);
	cc1100_read_reg_uartout(CC1100_REG_FSTEST);
	cc1100_read_reg_uartout(CC1100_REG_PTEST);
	cc1100_read_reg_uartout(CC1100_REG_AGCTEST);
	cc1100_read_reg_uartout(CC1100_REG_TEST2);
	cc1100_read_reg_uartout(CC1100_REG_TEST1);
	cc1100_read_reg_uartout(CC1100_REG_TEST0);

}










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 = 0xf3;

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






void alert_data_get(cc1101_client * client)
{

	#if 0
	client->serial[0] = 0x4D;	//M
	client->serial[1] = 0x37;	//E
	client->serial[2] = 0x34;	//T
	client->serial[3] = 0x00;	//0
	client->serial[4] = 0x00;	//0
	client->serial[5] = 0x00;	//0


//	client->data01 = 0x4D;	//EMG_SIG data
//	client->data02 = 0x37;	//test_sig_timer_data
//	client->data03 = 0x37;	//BATT_data
	client->data04 = 0x37;	//RSSI_data
	#endif





}



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++] = txfifo->dest_serial[temp];
		}

		//i=13;

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

		txfifo->data[i++] = gClient.status.ivent_flag;
		txfifo->data[i++] = gClient.status.bat_val;
		txfifo->data[i++] = gClient.rxfifo.rx_rssi;
		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.ivent_flag;
		txfifo->data[i++] = gClient.status.bat_val;
		txfifo->data[i++] = gClient.rxfifo.sl_rssi;
		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 i=0;
	u8 len;

	#if 1

	cc1100_fifo_get(&(len),1);
	rxfifo->length  = len + 2;
	//rxfifo->length = (rxfifo->length + 0x0002);	//add RSSI and LQI
	//rxfifo->length = (rxfifo->length + 0x0002);	//add RSSI and LQI


	cc1100_fifo_get(rxfifo->data,rxfifo->length);
	for(i=0;i<6;i++)
	{
		rxfifo->src_serial[i] = rxfifo->data[i+1];


	}

	for(i=0;i<6;i++)
	{
		rxfifo->dest_serial[i] = rxfifo->data[i+7];

	}

	//cc1100_fifo_get(rxfifo->rssi,1);
	//cc1100_fifo_get(rxfifo->lqi,1);
	#endif

	#if 1
	rxfifo->rx_rssi = rxfifo->data[rxfifo->length-1-1];
	rxfifo->rx_lqi = rxfifo->data[rxfifo->length-1];

	rxfifo->sl_rssi = rxfifo->data[16];
	rxfifo->sl_lqi = rxfifo->data[20];
	rxfifo->sessionflag = rxfifo->data[13];
	rxfifo->ivent_flag = rxfifo->data[14];
	#endif



}







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


	if((input_data & 0xC0)==0xC0)
	{

		#if 0
		f_reg[2] = 0x10;					//429.2750MHz(Ch9) nearly 426.274933MHz
		f_reg[1] = 0x82;
		f_reg[0] = 0xB5;
		#endif

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

		#if 0
		f_reg[2] = 0x10;					//429.3750MHz(Ch17) nearly 429.374908MHz
		f_reg[1] = 0x83;
		f_reg[0] = 0xB1;
		#endif

		#if 1
		f_reg[2] = 0x10;					//426.4625MHz(Ch9) nearly 426.462128MHz
		f_reg[1] = 0x67;
		f_reg[0] = 0x03;
		#endif

	}else if((input_data & 0xC0)==0x40){

		#if 0
		f_reg[2] = 0x10;					//429.4750MHz(Ch25) nearly 429.474884MHz
		f_reg[1] = 0x84;
		f_reg[0] = 0xAD;
		#endif

		#if 1
		f_reg[2] = 0x10;					//426.5625MHz(Ch13)
		f_reg[1] = 0x68;
		f_reg[0] = 0x00;
		#endif

	}else if((input_data & 0xC0)==0x00){

		#if 0
		f_reg[2] = 0x10;					//429.5750MHz(Ch33)	nearly 429.574860MHz
		f_reg[1] = 0x85;
		f_reg[0] = 0xA9;
		#endif

		#if 1
		f_reg[2] = 0x10;					//426.6625MHz(Ch17)	nearly 426.662476MHz
		f_reg[1] = 0x68;
		f_reg[0] = 0xFC;
		#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 |= 1<<ACD;
	//mdelay(1000);
	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

}






u8 add_batt_low(void)
{
	u8 temp_data;

	#if 0
	u8 add_data;
	u8 temp_data;

	temp_data = (ACSR & 0x10);
	temp_data = (temp_data << 3);
	ACSR |= 1<<ACI;
	
	add_data = data + temp_data;
	return add_data;
	#endif

	B_CTL_HIGH;

	init_ad();
	ADCSRA |= _BV(ADSC);					//変換開始 要ﾙｰﾌﾟ内
	while((ADCSRA&0x10)==0x00);

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

	temp_data = ADCH;

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

	puthex(a);
	puthex(0x5C);
	puthex(b);
	putc(0x0d);
	putc(0x0a);
	putc(0x0d);
	putc(0x0a);

	return temp_data;
}






// エラー
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 = 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;



#if 1
uint16_t rx_length = 0;
uint8_t rx_data[100];
uint16_t verify_length=0;
uint8_t verify_data[200];
uint16_t verify_cnt=0;
u8 crc_ok_cnt=0;
#endif







#if 0

void rx_test(cc1101_client * client)
{
	uint16_t i;
	//uint8_t value;

	spi_signalpin_opendrain_nonactive();


    cc1100_init();
	cc1101_init_tx();

	status = RX_SETUP;


	while(1)
	{

		switch(status)
		{
			default:
				break;
			case RX_SETUP:
				cc1101_init_rx();
				reg_check();


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

				//sdelay(1);
				//reg_check();
				//sdelay(3);
				status = RX_START;
				break;
			case RX_START:
				cc1100_cmd_idle();
				mdelay(2,gClient.status.system_osc);
				cc1100_cmd_flush_rx();
				cc1100_cfg_gdo0(CC1100_GDOx_RX_OK);
				cc1100_cmd_calibrate();
				mdelay(2,gClient.status.system_osc);
				cc1100_cmd_rx();
				mdelay(2,gClient.status.system_osc);
				cc1100_read_reg(CC1100_REG_MARCSTATE | CC1100_ACCESS_STATUS);
				status = RX_WAIT;
				break;
			case RX_WAIT:
				B_CTL_LOW;	//LED_OFF
				while(status == RX_WAIT)
				{

					#if 1				


					if(PINC&0x04)
					{	
						cc1100_read_reg_uartout(CC1100_REG_RSSI | CC1100_ACCESS_STATUS);
						cc1100_read_reg(CC1100_REG_RXBYTES | CC1100_ACCESS_STATUS);
						cnt_recierve_cnt++;
						B_CTL_HIGH;	//LED_ON
						status = RX_DATA_TX_SYN_ACK_SETUP;
						break;
					}
					else
					{	
						if(cc1100_read_reg(CC1100_REG_MARCSTATE | CC1100_ACCESS_STATUS)!=0x0d)
						{
							cc1100_read_reg_uartout(CC1100_REG_RSSI | CC1100_ACCESS_STATUS);
							B_CTL_LOW;	//LED_OFF
							status = RX_START;
							break;
						}
					}

					//mdelay(100);
					mdelay(20,gClient.status.system_osc);
					#endif


				}
				break;
			case RX_DATA_TX_SYN_ACK_SETUP:

				rx_fifo_get(&(client->rxfifo));

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

				if(i!=3)
				{
					status = RX_SETUP;
					break;
				}


				if(client->rxfifo.sessionflag != 0x02)
				{
					status = RX_SETUP;
					break;
				}

				client->status.sessionflag = (client->rxfifo.sessionflag | 0x10); //set SYN+ACK
				for(i=0;i<6;i++)
				{
					client->txfifo.dest_serial[i] = client->rxfifo.src_serial[i];
				}

				cc1101_init_tx();
				cc1100_cmd_flush_tx();
				cc1100_cmd_idle();

				cc1100_cmd_calibrate();
				cc1100_cfg_gdo0(CC1100_GDOx_SYNC_WORD);
				mdelay(5,gClient.status.system_osc);

				



				//rx_data[(rx_length-2)-1] = client.status.;


				//tx_length = tx_fifo_set(&client);
				#if 1
				tx_fifo_set(&(client->txfifo));
				//tx_fifo_set(client);
				#endif

				//mdelay(50,gClient.status.system_osc);
				//mdelay(30,gClient.status.system_osc);
				mdelay(40,gClient.status.system_osc);

				status = RX_DATA_TX_SYN_ACK;
				break;
			case RX_DATA_TX_SYN_ACK:
				cc1100_cfg_gdo0(0x0e);
				while(PINC&0x04);		//Carrier sense
				cc1100_cfg_gdo0(CC1100_GDOx_SYNC_WORD);
				//mdelay(10);				//test delay for TX
				cc1100_cmd_tx();
				//mdelay(100);
				while(!(PINC&0x04));	//data send start
				while(PINC&0x04);		//data send end

				status = RX_DATA_CNT;
				break;
			case RX_DATA_CNT:



				#if 1
				for(i=0;i<client->rxfifo.length;i++)
				{

					putc(0x52);		//R
					putc(0x58);		//X
					puthex(i);		
					putc(0x5c);		//\
//					value = rx_data[i];
//					puthex(value);
					puthex(client->rxfifo.data[i]);
					putc(0x0d);
					putc(0x0a);
				}
				#endif



				putc(0x52);		//R
				putc(0x58);		//X
				puthex(cnt_recierve_cnt);
				putc(0x0d);
				putc(0x0a);
				status = RX_START;
				break;
		}
	}
}


#endif



void master_test(cc1101_client * client)
{

	spi_signalpin_opendrain_nonactive();


    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;
				//rtc_set_1day_alarm();
				break;
			}
		}
	
		cc1101_tx(client);

		if(gClient.status.status == WAIT_IVENT)
		{
			B_CTL_HIGH;
			sdelay(3);
			B_CTL_LOW;
		}
	}


}




















ISR(USART_RX_vect)
{
	test_cnt02++;
	test_cnt02=UDR0;
	puthex(test_cnt02);
	mdelay(100,gClient.status.system_osc);


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


	putc(0x52);		//R
	putc(0x58);		//X
	puthex(cnt_recierve_cnt);
	putc(0x0d);
	putc(0x0a);
	//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

 




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;
}


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

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

}









#if 0


void tx_test(cc1101_client * client)
{
	u8 i=0;
	u8 cnt_sent_packet=0;
	u8 cnt_wait_syn_ack=0;
	u8 cnt_sent_ok_packet=0;
	master_rssi=0;



    cc1100_init();
	cc1101_init_tx();



	#if 1
	status = KEY_CHK;
	PCICR = (1<<PCIE1);	//PCIE1 Enable

	while(1)
	{
		switch(status)
		{
			default:
				break;
			case KEY_CHK:

				input_data = ~get_input_data();


				if((input_data&0x0c)==0x04)
					status = CA_OUT_SETUP;
				else if((input_data&0x0c)==0x00)
					status = DATA_OUT_SETUP;
				else if((input_data&0x0c)==0x08)
					status = RX_RSSI_SETUP;
				else if((input_data&0x0c)==0x0c)
					status = LOOP_OUT;
				break;
			case CA_OUT_SETUP:
				cc1101_carrier_wave_setup(input_data);
				//cc1101_carrier_waveoutput_setup(input_data,pt_data);

				#if 1
				pt_data[0] = 0xC0;			//10dB
				//pt_data[0] = 0x00;
				//pt_data[1] = 0xC0;			//
				pt_data[1] = 0x00;			//
				#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,0x83);	
				cc1100_write_reg(CC1100_REG_MDMCFG3,0x33);
				cc1100_cfg_mod_format(CC1100_MODULATION_ASK);
				//cc1100_write_reg(CC1100_REG_FREND0,0x11);
				cc1100_write_reg(CC1100_REG_FREND0,0x10);
				//cc1100_write_reg(CC1100_REG_IOCFG2, CC1100_GDOx_CLK_XOSC_1);
				cc1100_cfg_gdo0(CC1100_GDOx_CLK_XOSC_1);

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

				status = CA_WAVEOUT;
				break;
			case CA_WAVEOUT:
				cc1100_cmd_idle();
				cc1100_cmd_flush_tx();
				cc1100_cmd_calibrate();
				mdelay(10,gClient.status.system_osc);
				cc1100_cmd_tx();


				status = CA_KEY_CHANGE_CHK;
				break;
			case DATA_OUT_SETUP:
				cc1101_init_tx();

				#if 1
				//if(cnt_sent_packet>100)
				if(cnt_sent_packet>7)
				{
					status = DATA_WAVEOUT_QUIT;
					break;
				}
				#endif

				status = FIFO_SETUP;
				break;
			case FIFO_SETUP:
				#if 0
				if(cnt_sent_packet > 100)
				{
					status = DATA_WAVEOUT_QUIT;
					break;
				}
				#endif				

				cc1100_cmd_flush_tx();
				cc1100_cmd_idle();

				cc1100_cmd_calibrate();
				cc1100_cfg_gdo0(CC1100_GDOx_SYNC_WORD);
				mdelay(5,gClient.status.system_osc);

				client->status.sessionflag = 0x02;	//SYN flag set
				client->status.ivent_flag = 0xa5;

				cc1100_read_reg_uartout((CC1100_REG_TXBYTES | CC1100_ACCESS_STATUS));

				tx_fifo_set(&(client->txfifo));

				#if 1
				cc1100_read_reg_uartout((CC1100_REG_TXBYTES | CC1100_ACCESS_STATUS));
				#endif

				status = DATA_WAVEOUT;
				break;
			case DATA_WAVEOUT:
				cc1100_read_reg_uartout(CC1100_REG_MARCSTATE | CC1100_ACCESS_STATUS);
				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
				//mdelay(1);
				cnt_sent_packet++;


				#if 0
				cc1100_read_reg_uartout((CC1100_REG_TXBYTES | CC1100_ACCESS_STATUS));
				#endif


				status = DATA_WAVEOUT_WAIT_SYN_ACK_ACK_SETUP;

				break;
			case DATA_WAVEOUT_WAIT_SYN_ACK_ACK_SETUP:
				cc1100_cmd_flush_tx();
				cc1100_cmd_idle();
				cc1101_init_rx();

				cc1100_cmd_idle();
				mdelay(2,gClient.status.system_osc);
				cc1100_cmd_flush_rx();
				cc1100_cfg_gdo0(CC1100_GDOx_RX_OK);
				cc1100_cmd_calibrate();
				mdelay(2,gClient.status.system_osc);
				cc1100_cmd_rx();
				mdelay(2,gClient.status.system_osc);
				cc1100_read_reg(CC1100_REG_MARCSTATE | CC1100_ACCESS_STATUS);

				status = DATA_WAVEOUT_WAIT_SYN_ACK;
				break;
			case DATA_WAVEOUT_WAIT_SYN_ACK:
				cnt_wait_syn_ack = 0;

				while(status == DATA_WAVEOUT_WAIT_SYN_ACK)
				{

					#if 1				


					if(PINC&0x04)
					{	
						cc1100_read_reg_uartout(CC1100_REG_RSSI | CC1100_ACCESS_STATUS);
						cc1100_read_reg(CC1100_REG_RXBYTES | CC1100_ACCESS_STATUS);
						B_CTL_HIGH;	//LED_ON
						status = DATA_WAVEOUT_SYN_ACK_VERIFY;
						break;
					}
					else
					{	
						if(cc1100_read_reg(CC1100_REG_MARCSTATE | CC1100_ACCESS_STATUS)!=0x0d)
						{
							cc1100_read_reg_uartout(CC1100_REG_RSSI | CC1100_ACCESS_STATUS);
							B_CTL_LOW;	//LED_OFF
							status = DATA_OUT_SETUP;
							break;
						}
					}


					mdelay(20,gClient.status.system_osc);
					#endif

					cnt_wait_syn_ack++;
					//if(cnt_wait_syn_ack>10)
					if(cnt_wait_syn_ack>20)
					{
						B_CTL_LOW;	//LED OFF
						status = DATA_OUT_SETUP;
						break;
					}
				}

				break;
			case DATA_WAVEOUT_SYN_ACK_VERIFY:

				rx_fifo_get(&(client->rxfifo));


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

				if(i!=3)
				{
					status = DATA_OUT_SETUP;
					break;
				}


				if(client->rxfifo.sessionflag != 0x12)
				{
					status = DATA_OUT_SETUP;
					break;
				}		


				status = DATA_WAVEOUT_QUIT;	



				#if 0
				for(i=0;i<8;i++)
				{
					if(client->txfifo.data[i] == client->rxfifo.data[i])
					{
						verify_cnt++;
					}
				}

				if(verify_cnt==8)
				{
					status = DATA_WAVEOUT_OK_CNT;
				}
				else{
					status = DATA_OUT_SETUP;
					//B_CTL_LOW;	//LED OFF
				}
				verify_cnt=0;
				#endif



				#if 1
				for(i=0;i<client->rxfifo.length;i++)
				{

					putc(0x52);		//R
					putc(0x58);		//X
					puthex(i);		
					putc(0x5c);		//\
//					value = rx_data[i];
//					puthex(value);
					puthex(client->rxfifo.data[i]);
					putc(0x0d);
					putc(0x0a);
				}
				#endif



				break;
			case DATA_WAVEOUT_OK_CNT:

				//cc1100_cmd_flush_rx();
				cnt_sent_ok_packet++;

				putc(0x4f);
				putc(0x5c);
				puthex(cnt_sent_ok_packet);
				putc(0x0d);
				putc(0x0a);

				B_CTL_HIGH;	//LED ON

				status = DATA_OUT_SETUP;
				break;
			case DATA_WAVEOUT_QUIT:

				putc(0x53);
				putc(0x5c);
				puthex(cnt_sent_packet);
				putc(0x0d);
				putc(0x0a);

				putc(0x4f);
				putc(0x5c);
				puthex(cnt_sent_ok_packet);
				putc(0x0d);
				putc(0x0a);
				sdelay(1);


				#if 0
				while(i<40)
				{

					B_CTL_HIGH;
					mdelay(100);
					B_CTL_LOW;
					mdelay(100);
					i++;

				}
				#endif

				sdelay(1);

				status = LOOP_OUT;
				break;
			case DATA_KEY_CHANGE_CHK:
				new_input_data = ~get_input_data();
				if(new_input_data != input_data)
					status = KEY_CHK;
				else
					status = FIFO_SETUP;
				break;						
			case CA_KEY_CHANGE_CHK:
				new_input_data = ~get_input_data();
				if(new_input_data != input_data)
					status = KEY_CHK;

				#if 1
				cc1100_read_reg_uartout(CC1100_REG_MARCSTATE | CC1100_ACCESS_STATUS);
				#endif
				break;
			#if 0
			case RX_RSSI_SETUP:
				break;
			case RX_RSSI_START:
				break;
			case RX_RSSI_WAIT:
				break;
			case RX_SETUP:
				break;
			case RX_START:
				break;
			case RX_WAIT:
				break;
			case RX_DATA_TX_SYN_ACK_SETUP:
				break;
			case RX_DATA_TX_SYN_ACK:
				break;
			case RX_DATA_CNT:
				break;
			case SEND_UART_RX_DATA:
				break;
			case RX_VERIFY_START:
				break;
			case RX_VERIFY_WAIT:
				break;
			case RX_VERIFY:
				break;
			#endif
		}

		if(status==LOOP_OUT)
			break;

	}
	#endif

	
}

#endif



void cc1101_tx_carrier(cc1101_client * client)
{

				cc1101_carrier_wave_setup(input_data);


				#if 1
				pt_data[0] = 0xC0;			//10dB
				pt_data[1] = 0x00;			//
				#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 1
				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,gClient.status.system_osc);
				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,gClient.status.system_osc);
	
	client->status.sessionflag = 0x02;	//SYN flag set
	client->status.ivent_flag = 0xa5;
	
	cc1100_read_reg_uartout((CC1100_REG_TXBYTES | CC1100_ACCESS_STATUS));
	tx_fifo_set(&(client->txfifo));
	
	cc1100_read_reg_uartout(CC1100_REG_MARCSTATE | CC1100_ACCESS_STATUS);
	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;

	cc1100_cmd_flush_tx();
	cc1100_cmd_idle();
	cc1101_init_rx();
	cc1100_cmd_idle();
	mdelay(2,gClient.status.system_osc);
	cc1100_cmd_flush_rx();
	cc1100_cfg_gdo0(CC1100_GDOx_RX_OK);
	cc1100_cmd_calibrate();
	mdelay(2,gClient.status.system_osc);
	cc1100_cmd_rx();
	mdelay(2,gClient.status.system_osc);
	cc1100_read_reg(CC1100_REG_MARCSTATE | CC1100_ACCESS_STATUS);
	cnt_wait_syn_ack = 0;

	while(1)
	{

		#if 1				


		if(PINC&0x04)
		{	
			cc1100_read_reg_uartout(CC1100_REG_RSSI | CC1100_ACCESS_STATUS);
			cc1100_read_reg(CC1100_REG_RXBYTES | CC1100_ACCESS_STATUS);
			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)
			{
				cc1100_read_reg_uartout(CC1100_REG_RSSI | CC1100_ACCESS_STATUS);
				B_CTL_LOW;	//LED_OFF
				client->rxfifo.length=0;
				//status = DATA_OUT_SETUP;
				break;
			}
		}


		mdelay(20,gClient.status.system_osc);
		#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;

	if(client->status.status != WAIT_IVENT) return;


	client->rxfifo.length=0;

	while(1)
	{
		cc1101_tx(client);

		client->rxfifo.length = cc1101_rx(client);
		if(client->rxfifo.length > 0)
		{
			client->status.status = WAIT_IVENT;
			rtc_set_1day_alarm();
			return;
		}
		else
		{
			if(temp_cnt>8)
			{
				client->status.status = WAIT_2SEC;
				rtc_set_2sec_next_alarm();
				return;

			}
			temp_cnt++;
			//return;
		}
	}
}






ISR(INT1_vect)
{
	u8 i=0;

	//DDRB |= (1<<PB0);	//B_CTL
	spi_signalpin_opendrain_nonactive();



	#if 1
	input_data = ~get_input_data();

	if((input_data&0x0c)==0x0c)
	{
		//spi_signalpin_opendrain_active();
		return;
	}
	#endif






	#if 1

	gClient.status.bat_val = add_batt_low();

	#endif


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




	#if 0
	tx_test(&gClient);
	#endif

	slave_test(&gClient);





	if(gClient.status.status == WAIT_IVENT)
	{
		B_CTL_HIGH;
		sdelay(3);
		B_CTL_LOW;
	}



	//rtc_set_5sec_next_alarm();
	//rtc_set_2sec_next_alarm();

	cc1100_cmd_idle();
	cc1100_cmd_pwd();

	input_data = ~get_input_data();

	spi_signalpin_opendrain_active();


}



ISR(INT0_vect)
{

	spi_signalpin_opendrain_nonactive();


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



	test_cnt02++;
	puthex(0x33);
	mdelay(100,gClient.status.system_osc);



	#if 1
	led_flasher(5,50);
	#endif
	slave_test(&gClient);


	if(gClient.status.status == WAIT_IVENT)
	{
		B_CTL_HIGH;
		sdelay(3);
		B_CTL_LOW;
	}



	//rtc_set_5sec_next_alarm();
	//rtc_set_2sec_next_alarm();
	//EIMSK |= (1<<INT0);
	//EIMSK &= (0<<INT1);		//INT1 disenable

	cc1100_cmd_idle();
	cc1100_cmd_pwd();



	spi_signalpin_opendrain_active();

}




void device_status_setup(void)
{
	u8 i=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;

}







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


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);
}



void rtc_set_1day_alarm(void)
{
	rtc_1byte_data_write(0x0E,0x00);		//Alarm enable disenable
	rtc_1byte_data_write(0x0E,0x40);		//Alarm enable enable

	//rtc_1byte_data_write(0x09,0x10);		//Alarm 10:00
	//rtc_1byte_data_write(0x08,0x00);


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

	
	rtc_1byte_data_write(0x02,0x10);		//current time 10:00:01
	rtc_1byte_data_write(0x01,0x00);
	rtc_1byte_data_write(0x00,0x01);

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


	#if 0
	test_temp = rtc_1byte_data_read(0x00);
	test_temp2 = rtc_1byte_data_read(0x01);
	test_temp3 = rtc_1byte_data_read(0x02);
	test_temp4 = rtc_1byte_data_read(0x0E);
	#endif

}


void rtc_set_5sec_next_alarm(void)
{
	rtc_1byte_data_write(0x0E,0x00);		//Alarm enable disenable
	rtc_1byte_data_write(0x0E,0x40);		//Alarm enable enable

	rtc_1byte_data_write(0x02,0x09);		//current time 9:59:55
	rtc_1byte_data_write(0x01,0x59);
	rtc_1byte_data_write(0x00,0x55);
}



void rtc_set_2sec_next_alarm(void)
{
	rtc_1byte_data_write(0x0E,0x00);		//Alarm enable disenable
	rtc_1byte_data_write(0x0E,0x40);		//Alarm enable enable

	rtc_1byte_data_write(0x02,0x09);		//current time 9:59:55
	rtc_1byte_data_write(0x01,0x59);
	rtc_1byte_data_write(0x00,0x58);
}



int main()
{
	u8 i;
	#if 1

	hw_setup();
	inituart();
	device_status_setup();
	i2c_init();
	#endif



	input_data = ~get_input_data();


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



	CS_CC1101_HIGH;

	B_CTL_LOW;
	mdelay(100,gClient.status.system_osc);

	//spi_signalpin_opendrain_nonactive();


	#if 0
	if(gClient.status.type == SLAVE)
	{
		CLKPR = _BV(CLKPCE);	// CLKPCEビットを1にする
		CLKPR = 0b0011;			// 8分周にする
	}
	#endif
	
	#if 0
	while(1)
	{
		B_CTL_HIGH;	//LED ON
		mdelay(1,gClient.status.system_osc);
		B_CTL_LOW;	//LED OFF
		mdelay(1,gClient.status.system_osc);
	}
	#endif



	#if 1
    cc1100_init();
	cc1101_init_tx();
	#endif

	#if 0
	reg_check();

	cc1100_read_reg_uartout(CC1100_PATABLE_ADDR);
	cc1101_8PATABLE_read_reg();

	#endif




	#if 1
	status = STARTUP;
	test_cnt02 = 0;
	set_sleep_mode(SLEEP_MODE_PWR_DOWN);
	//set_sleep_mode(SLEEP_MODE_PWR_SAVE);


	eeprom_chk();


	#endif




	//device_status_setup();
	
	#if 0
	led_flasher(20);
	sdelay(3);
	#endif

	for(i=0;i<2;i++)
	{
		B_CTL_HIGH;	//LED ON
		sdelay(1);
		B_CTL_LOW;	//LED ON
		sdelay(1);
	}

	#if 0
	led_flasher(20);
	#endif


	sei();

	spi_signalpin_opendrain_nonactive();


	#if 1
	if(gClient.status.type == SLAVE)
	{
		rtc_set_1day_alarm();
	}
	#endif


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


	gClient.status.status=WAIT_IVENT;


	cc1100_cmd_idle();
	cc1100_cmd_pwd();


	#if 0
	sdelay(3);
	led_flasher(20);
	#endif







	spi_signalpin_opendrain_active();


	/* Enter the infinite loop */
    while (1)
    {
		//input_data = ~get_input_data();

		if(gClient.status.type==MASTER)
		{
			//rx_test(&gClient);
			master_test(&gClient);
		}
		else
		{
			#if 1
			sleep_mode();
			#endif
		}




	}
}


