/* Atari driving controller to USB
 * Copyright (C) 2018 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 "ataridriving.h"

#define MULT 32	// Spinner sensivity

static char AtariDrivingInit(void);
static void AtariDrivingUpdate(void);
static char AtariDrivingChanged(char id);
static char AtariDrivingBuildReport(unsigned char *reportBuffer, char id);

static unsigned char last_update_state=0;
static unsigned char last_reported_state=0;

volatile int wheel_pos;
static unsigned char spinner, old_spinner;

int QEM [16] = {0,1,-1,2,-1,0,2,1,1,2,0,-1,2,-1,1,0};               // Quadrature Encoder Matrix
/* QEM explanation:
 *
 * Quadrature from an Atari driving controller is made of two 90 degree out of phase signals that corresponds to
 * two bumped wheels driven by the spinner shaft. The bumped weels triggering microswitches that are 
 * generating those signals. 
 *
 * Here is an example of a signal of the spinner going left:
 *          ________            ________            ________            ____
 *         /        \          /        \          /        \          /
 * A  ____/          \________/          \________/          \________/
 *              ________            ________            ________
 *             /        \          /        \          /        \
 * B  ________/          \________/          \________/          \__________
 *
 * Here is an example of a signal of the spinner going right:
 *
 *          ________            ________            ________            ____
 *         /        \          /        \          /        \          /
 * A  ____/          \________/          \________/          \________/
 * 
 * B ________            ________            ________            ________
 *            \          /        \          /        \          /
 *             \________/          \________/          \________/
 *
 * Note on these two example the diffence in phase between A and B for left and right.
 *
 * Using these generated waves, we can determine by software the delta displacement of the spinner.
 * The following table is generated by combining these signals in two 2-bit value, A, B, A' and B'.
 *
 *        Actual readed value (A-B 2-bit combinasion)
 *        0   1   2   3
 *     ----------------
 *   0 |  0   1  -1   X
 *   
 *   1 | -1   0   X   1
 *
 *   2 |  1   X   0  -1
 *  
 *   3 |  X  -1   1   0
 *
 *   Previous readed value (A-B 2-bit combinasion)
 *
 */


static char AtariDrivingInit(void)
{

	/* PB0   = PIN1 XB (IN,w/Pull-up)9
	 * PB1   = PIN2 XA (IN,w/Pull-up)7
	 * PB2   = PIN3 nc (IN,0)
	 * PB3   = PIN4 nc (IN,0)
	 * PC1&3 = PIN5 nc (IN,0)
	 * PB4   = PIN6 fire button (IN, w/Pull-up)
	 * PB5   = PIN7 nc (IN,0)
	 * PD7   = PIN8 GND (OUT,0)
	 * PC0&2 = PIN9 nc (IN,0)
	 */
	
	DDRB &= ~((1<<PB0)|(1<<PB1)|(1<<PB2)|(1<<PB3)|(1<<PB4)|(1<<PB5));
	PORTB |= ((1<<PB0)|(1<<PB1)|(1<<PB4));
	PORTB &= ~((1<<PB2)|(1<<PB3)|(1<<PB5));

	DDRC &= ~((1<<PC0)|(1<<PC2)|(1<<PC1)|(1<<PC3));
	PORTC &= ~((1<<PC1)|(1<<PC2)|(1<<PC3)); 
	
	DDRD |= (1<<PD7);
	PORTD &= ~((1<<PD7));

	/* Spinner, initial condition */
	AtariDrivingUpdate();
	wheel_pos=0x80;

	return 0;
}

static void AtariDrivingUpdate(void)
{
	int delta;

	last_update_state = (PINB&0x13);

	/* Spinner */
	spinner =(((~last_update_state&(0x01))<<1)|(~last_update_state&(0x02)>>1));
	
	// Apply delta displacement from quadrature generated by the spinner.
	// Quad Format (4 bits): MSB OldB OldA ActualB ActualA LSB
	delta = (QEM[(spinner|(old_spinner<<2))]*MULT);
	wheel_pos += delta;

	// Clipping min and max position
	if(wheel_pos>(int)255)
		wheel_pos=255;

	if(wheel_pos<(int)0)
		wheel_pos=0;

	old_spinner=spinner; // Old position = new position for next iteration.

}

static char AtariDrivingChanged(char id)
{
	return (last_update_state != last_reported_state);
}

#define REPORT_SIZE 2

static char AtariDrivingBuildReport(unsigned char *reportBuffer, char id)
{
	unsigned char tmp;
	
	if (reportBuffer)
	{
		tmp = (last_update_state ^ 0xff);
		
	   /*
 		* [0] Wheel_Pos
 		* [1] Fire
 		*/
		
		reportBuffer[0] = (unsigned char)wheel_pos;
		reportBuffer[1] = 0;

		if (tmp&(1<<PB4)) reportBuffer[1] |= 0b00000001;	//fire
	}
	last_reported_state = last_update_state;

	return REPORT_SIZE;
}

const char AtariDriving_usbHidReportDescriptor[] PROGMEM = {

    0x05, 0x01,                    // USAGE_PAGE (Generic Desktop)
    0x09, 0x05,                    // USAGE (Game Pad)
    0xa1, 0x01,                    // COLLECTION (Application)
    0x09, 0x01,                    //   USAGE (Pointer)
    0xa1, 0x00,                    //   COLLECTION (Physical)
    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)
    0xc0,                          // END_COLLECTION
    0x05, 0x09,                    // USAGE_PAGE (Button)
    0x19, 0x01,                    //   USAGE_MINIMUM (Button 1)
    0x29, 0x01,               	   //   USAGE_MAXIMUM (Button 1)
    0x15, 0x00,                    //   LOGICAL_MINIMUM (0)
    0x25, 0x01,                    //   LOGICAL_MAXIMUM (1)
    0x75, 0x01,                    //   REPORT_SIZE (1)
    0x95, 0x08,                    //   REPORT_COUNT (8)
    0x81, 0x02,                    // INPUT (Data,Var,Abs)
    0xc0                           // END_COLLECTION
};

#define USBDESCR_DEVICE         1

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

const char AtariDriving_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 */
    USB_CFG_DEVICE_ID,  /* 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 AtariDrivingJoy = {
	.num_reports			=	1,
	.reportDescriptorSize	=	sizeof(AtariDriving_usbHidReportDescriptor),
	.deviceDescriptorSize	=	sizeof(AtariDriving_usbDescrDevice),
	.init					=	AtariDrivingInit,
	.update					=	AtariDrivingUpdate,
	.changed				=	AtariDrivingChanged,
	.buildReport			=	AtariDrivingBuildReport,
};

Gamepad *AtariDrivingGetGamepad(void)
{
	AtariDrivingJoy.reportDescriptor = (void*)AtariDriving_usbHidReportDescriptor;
	AtariDrivingJoy.deviceDescriptor = (void*)AtariDriving_usbDescrDevice;

	return &AtariDrivingJoy;
}


