/*
 * $Id: radio_tx.c 173 2005-09-27 17:09:59Z anders $
 * 
 * Copyright (C) 2005 Anders Dubgaard <anders@dubgaard.net>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <avr/signal.h>
#include <stdio.h>
#include "radio.h"
#include "protocol.h"
#include "cc1000.h"
#include "cc1000registers.h"
#include <uart.h>

/* Client / transmitter */
volatile uint8_t package_sent = false;
volatile uint16_t tx_byte_cnt = 0; /* MSB is to be sent first, so shift */
volatile uint8_t tx_mask = 0x80;   /* tx_mask to the right.             */


/* Sends the joystick data on it's way in a straight forward manner,
 * as the data array has been prepared beforehand.
 *
 */
SIGNAL(SIG_INTERRUPT0) {  /* Transmit */
  if(tx_byte_cnt >= 0 && tx_byte_cnt < PACKAGE_LEN) {
    if(package[tx_byte_cnt] & tx_mask) {
      setbit(CC1000_PORT, DIO);
    } else {
      clrbit(CC1000_PORT, DIO);
    }
    tx_mask >>= 1;     /* Prepare mask for next bit */
    if(tx_mask < 1) {  /* mask=1 => sent one byte */ 
      tx_mask = 0x80;
      tx_byte_cnt++;
    }
  }
  else {  /* Package bytes sent */
    disable_radio_int();  /* Wait to be enabled */
    package_sent = true;  /* Tell main code to read new data from joystick */
    tx_byte_cnt = 0;
  }
}

/* Initialise the radio chip.
 * The CC1000 register variables in ConfigureCC1000() have been
 * generated with smartrf2header.pl from the output data of
 * Chipcon's SmartRF(C) programme.
 *
 * The step wise procedure below is described in Chipcon's AN009.
 */
void radio_init(void) {
	CC1000_PDIR |= 1<<PCLK | 1<<PALE | 1<<PDATA;
	ResetCC1000();

	ConfigureCC1000(tx_numregs, tx_regs);
	clrbit(MCUCR, ISC00);      // interrupt on falling edge
	setbit(MCUCR, ISC01);      // interrupt on falling edge
	
	CalibrateCC1000();

	setbit(CC1000_PDIR, DIO);
	clrbit(CC1000_PDIR, DCLK);
}

/* Starts the transmitting int. routine.
 *
 */
void send_package(void) {
	package_sent = false;
	enable_radio_int();
	while(!package_sent)
		;
}

void disable_radio_int(void) {
	clrbit(GICR, INT0);          /* disable interrupt on INT0 */
}

void enable_radio_int(void) {
	setbit(GICR, INT0);          /* enable interrupt on INT0 */
}

