/* "Atari" style paddles to USB (Interrupt/Comparator version)
 * Copyright (C) 2014 Francis-Olivier Gradel, ing.
 *
 * Based on Raphaël Assénat's code. http://www.raphnet.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 Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * The author may be contacted at info@retronicdesign.com
 */
#include <avr/io.h>
#include <avr/delay.h>
#include <avr/pgmspace.h>
#include <avr/interrupt.h>
#include <string.h>
#include "usbconfig.h"
#include "ataripaddles.h"

#define SETUPDELAY	5
#define DIVIDER 64	// 64 for Atari(1Mohm) and 32 for Commodore(460Kohm)
#define TIMEOUT	65000

static char atariPaddlesInit(void);
static void atariPaddlesUpdate(void);
static char atariPaddlesChanged(char id);
static char atariPaddlesBuildReport(unsigned char *reportBuffer, char id);
static void atariPaddlesReadPort(char);

volatile unsigned int channel[2];
volatile unsigned int old_channel[2];
volatile int currentchannel;
volatile char flag;

static unsigned char button_state[2];
static unsigned char button_reported_state[2];

static char atariPaddlesInit(void)
{

	/* PIN1 = PB0 = nc
	 * PIN2 = PB1 = nc
	 * PIN3 = PB2 = BUT0 (I,1)
	 * PIN4 = PB3 = BUT1 (I,1)
	 * PIN5 = PC1 = POT1 (I,0) PC3 = (I,0)
	 * PIN6 = PB4 = nc
	 * PIN7 = PB5 = VCC  (O,1)
	 * PIN8 = PD7 = GND  (O,0)
	 * PIN9 = PC0 = POT0 (I,0) PC2 = (I,0)
	 */
	
	DDRB &= ~((1<<PB2)|(1<<PB3));
	DDRB |= (1<<PB5);
	PORTB |= ((1<<PB2)|(1<<PB3)|(1<<PB5));

	DDRD |= ((1<<PD7));
	PORTD &= ~(1<<PD7);

	DDRC &= ~((1<<PC2)|(1<<PC3));
	PORTC &= ~((1<<PC2)|(1<<PC3));

	DDRC &= ~((1<<PC0)|(1<<PC1));
	PORTC &= ~((1<<PC0)|(1<<PC1));

	old_channel[0]=channel[0]=0;
	old_channel[1]=channel[1]=0;

	button_state[0]=button_reported_state[0]=0;
	button_state[1]=button_reported_state[1]=0;

	ADCSRB |= (1<<ACME);	// Comparator negative input on ADC MUX.
	ADCSRA &= ~(1<<ADEN);	// ADC off, Comparator on.
	ACSR |= ((1<<ACBG)|(1<<ACIE)|(1<<ACIC)|(1<<ACIS1)); // Comparator positive input on BANDGAP. Interrupt enable on caparator

	TCCR1B |= ((1<<WGM12)|(1<<CS11));	// Timer1: CTC,XTAL/8

	return 0;
}

static void atariPaddlesUpdate(void)
{
	unsigned int i;

	button_state[0]=(PINB&(1<<PB2))?0:1; //Read paddle 0 button
	button_state[1]=(PINB&(1<<PB3))?0:1; //Read paddle 1 button

	i=0;
	atariPaddlesReadPort(0); // Read paddle 0 value
	while(i<TIMEOUT && flag)
		i++;

	i=0;
	atariPaddlesReadPort(1); // Read paddle 1 value
	while(i<TIMEOUT && flag)
		i++;
	
}

static char atariPaddlesChanged(char id)
{
	return ((button_state[(int)id-1] != button_reported_state[(int)id-1])||(old_channel[(int)id-1] != channel[(int)id-1]));		
}

#define REPORT_SIZE 3

static char atariPaddlesBuildReport(unsigned char *reportBuffer, char id)
{
	int a;

	a=((channel[(int)id-1])/DIVIDER);

	if(a>255)
		a=255;

	if (reportBuffer)
	{
	
		reportBuffer[0]=id;
		reportBuffer[1]=255-(char)a;
		reportBuffer[2]=button_state[(int)id-1];
	}

	button_reported_state[(int)id-1]=button_state[(int)id-1];
	old_channel[(int)id-1]=channel[(int)id-1];

	return REPORT_SIZE;
}

const char atariPaddles_usbHidReportDescriptor[] PROGMEM = {

	/* Controller and report_id 1 */
    0x05, 0x01,			// USAGE_PAGE (Generic Desktop)
    0x09, 0x04,			// USAGE (Joystick)
    0xa1, 0x01,			//	COLLECTION (Application)
    0x09, 0x01,			//		USAGE (Pointer)
    0xa1, 0x00,			//		COLLECTION (Physical)
	0x85, 0x01,			//			REPORT_ID (1)
	0x09, 0x30,			//			USAGE (X)
    0x15, 0x00,			//			LOGICAL_MINIMUM (0)
    0x26, 0xff, 0x00,	//			LOGICAL_MAXIMUM (255)
    0x75, 0x08,			//			REPORT_SIZE (8)
    0x95, 0x01,			//			REPORT_COUNT (1)
    0x81, 0x02,			//			INPUT (Data,Var,Abs)

    0x05, 0x09,			//			USAGE_PAGE (Button)
    0x19, 1,			//   		USAGE_MINIMUM (Button 1)
    0x29, 1,			//   		USAGE_MAXIMUM (Button 1)
    0x15, 0x00,			//   		LOGICAL_MINIMUM (0)
    0x25, 0x01,			//   		LOGICAL_MAXIMUM (1)
    0x75, 1,			// 			REPORT_SIZE (1)
    0x95, 8,			//			REPORT_COUNT (8)
    0x81, 0x02,			//			INPUT (Data,Var,Abs)
	0xc0,				//		END_COLLECTION
    0xc0,				// END_COLLECTION

	/* Controller and report_id 2 */
    0x05, 0x01,			// USAGE_PAGE (Generic Desktop)
    0x09, 0x04,			// USAGE (Joystick)
    0xa1, 0x01,			//	COLLECTION (Application)
    0x09, 0x01,			//		USAGE (Pointer)
    0xa1, 0x00,			//		COLLECTION (Physical)
	0x85, 0x02,			//			REPORT_ID (2)
    0x09, 0x30,			//			USAGE (X)
    0x15, 0x00,			//			LOGICAL_MINIMUM (0)
    0x26, 0xff, 0x00,	//			LOGICAL_MAXIMUM (255)
    0x75, 0x08,			//			REPORT_SIZE (8)
    0x95, 0x01,			//			REPORT_COUNT (1)
    0x81, 0x02,			//			INPUT (Data,Var,Abs)
    0x05, 0x09,			//			USAGE_PAGE (Button)
    0x19, 1,			//   		USAGE_MINIMUM (Button 1)
    0x29, 1,			//   		USAGE_MAXIMUM (Button 1)
    0x15, 0x00,			//   		LOGICAL_MINIMUM (0)
    0x25, 0x01,			//   		LOGICAL_MAXIMUM (1)
    0x75, 1,			// 			REPORT_SIZE (1)
    0x95, 8,			//			REPORT_COUNT (8)
    0x81, 0x02,			//			INPUT (Data,Var,Abs)
	0xc0,				//		END_COLLECTION
    0xc0,				// END_COLLECTION

};

#define USBDESCR_DEVICE         1

// This is the same descriptor as in devdesc.c, but the product id is 0x0a99 

const char atariPaddles_usbDescrDevice[] PROGMEM = {    /* USB device descriptor */
    18,         /* sizeof(usbDescrDevice): length of descriptor in bytes */
    USBDESCR_DEVICE,    /* descriptor type */
    0x01, 0x01, /* USB version supported */
    USB_CFG_DEVICE_CLASS,
    USB_CFG_DEVICE_SUBCLASS,
    0,          /* protocol */
    8,          /* max packet size */
    USB_CFG_VENDOR_ID,  /* 2 bytes */
    0x99, 0x0a,  /* 2 bytes */
    USB_CFG_DEVICE_VERSION, /* 2 bytes */
    USB_CFG_VENDOR_NAME_LEN != 0 ? 1 : 0,         /* manufacturer string index */
    USB_CFG_DEVICE_NAME_LEN != 0 ? 2 : 0,        /* product string index */
    USB_CFG_SERIAL_NUMBER_LEN != 0 ? 3 : 0,  /* serial number string index */
    1,          /* number of configurations */
};

Gamepad atariPaddlesJoy = {
	.num_reports			=	2,
	.reportDescriptorSize	=	sizeof(atariPaddles_usbHidReportDescriptor),
	.deviceDescriptorSize	=	sizeof(atariPaddles_usbDescrDevice),
	.init					=	atariPaddlesInit,
	.update					=	atariPaddlesUpdate,
	.changed				=	atariPaddlesChanged,
	.buildReport			=	atariPaddlesBuildReport,
};

Gamepad *atariPaddlesGetGamepad(void)
{
	atariPaddlesJoy.reportDescriptor = (void*)atariPaddles_usbHidReportDescriptor;
	atariPaddlesJoy.deviceDescriptor = (void*)atariPaddles_usbDescrDevice;

	return &atariPaddlesJoy;
}

ISR(ANALOG_COMP_vect)
{
	channel[currentchannel]=ICR1;		// Put triggered timer value in correcponding channel value
	flag=0;								// Lower reading in process flag.
}

void atariPaddlesReadPort(char val)
{
	val=val&0x1F;	// Only channel 0-31 are valid
	flag=1;	// Read in process flag
	currentchannel=val; // Set current channel to be read
	ADMUX &= 0xE0;
	ADMUX |= val;	// Set channel to read
	DDRC |= (1<<val);	// Force corresponding port to ground
	_delay_us(SETUPDELAY);	// Wait for capacitor to be discharged
	DDRC &= ~(1<<val);	// Put back port in read mode (floating);
	TCNT1=0;// Clear counter value
}
