/*
 * Control Canon EF lens, pretending to be that camera.
 *
 * for Arduino MEGA 2560 based on ATMega2560 chip.
 *
 * Timing is very critical so the raw ATMega port manipulations are required
 * rather than the Arduino digitalRead()/digitalWrite() commands.
 *
 * The conversation is stored in pairs (to/from lens) and output over serial when the buffer is full.
 *
 * Debugging output is done on a pin that can be watching with a suitably fast oscilloscope
 */
#include <Arduino.h>

//arduino pin numbers

//bidirectional clock (Arduino Digital I/O 11 = PB5)
#define CLK_OUTPORT	PORTB
#define CLK_INPORT		PINB
#define CLK_DIR 		DDRB
#define CLK_BIT		5
#define clkOut()		CLK_DIR |= (1 << CLK_BIT)
#define clkIn()		CLK_DIR &= ~(1 << CLK_BIT)
#define clockIsHigh()	(CLK_INPORT & (1 << CLK_BIT))
#define clkHigh()		CLK_OUTPORT |= (1 << DBG_BIT)
#define clkLow()		CLK_OUTPORT &= ~(1 << DBG_BIT)

//output to lens (Arduino Digital I/O 12 = PB6)
#define DCO_PORT	PORTB
#define DCO_DIR 	DDRB
#define DCO_BIT	6

//input from lens (Arduino Digital I/O 9 = PH6)
#define DCI_OUTPORT	PORTH
#define DCI_INPORT	PINH
#define DCI_DIR 	DDRH
#define DCI_BIT	6

//output for debugging with a scope (Arduino Digital I/O 8 = PH5)
#define DBG_PORT	PORTH
#define DBG_DIR 	DDRH
#define DBG_BIT	5
#define dbgHigh()	DBG_PORT |= (1 << DBG_BIT)
#define dbgLow()	DBG_PORT &= ~(1 << DBG_BIT)

void setup() {
  // initialize serial:
  Serial.begin(115200);
  Serial.println("Canon EF lens controller.");

  clkOut();	// clock as output to start
  DCO_DIR |= (1 << DCO_BIT);	// DCO as output
  DCI_DIR &= ~(1 << DCI_BIT);	// DCI as input
  DCI_OUTPORT |= (1 << DCI_BIT);	//   with pull-up enabled
  DBG_DIR |= (1 << DBG_BIT);	// debug as output

  clkHigh();
  dbgHigh();
}

//number of iterations to hold a bit (half cycle), probably something around 50-100kHz
#define BIT_LEN 10

//iterations to hold after receiving end of lens busy, before next byte
#define POST_BUSY_WAIT 40

//how long to wait for lens busy (to set or clear) before giving up entirely.
// NB: The lens will take forever to respond to motor commands if there is no motor voltage!
#define BUSY_TIMEOUT	30000

// Storage buffer
#define STORAGE_SIZE 	4096
uint8_t storage[STORAGE_SIZE];
int storagePos = 0;

/** Output stored data */
void dumpStorage(){
	Serial.println("Storage full, dumping");
	for(int i=0; i < storagePos; ){
		if((i % 32) == 0)
			Serial.println();
		Serial.print(storage[i++], HEX);
		Serial.print(" ");
		Serial.print(storage[i++], HEX);
		Serial.print(";  ");
	}
	Serial.println("\nStorage dump complete.");
	storagePos = 0;
}

/** Read a series of commands from Serial and preload them into storage
 * Bytes are read in hex and can be separated by space, tab or comma
 * Anything else is ignored.
 * Return (\n) reads back the data and returns.
 * */
int readCommands(){
	int n = 0;
	char c;
	do{
		uint8_t byte = 0;
		do{
			while(Serial.available() <= 0);
			c = Serial.read();
			//Serial.print("[r");
			//Serial.print(c , HEX);
			//Serial.print("]");

			//if valid char, write in LSB and shift byte up
			if(c >= '0' && c <= '9')
				byte = (byte << 4) | (c - '0');

			else if(c >= 'A' && c <= 'F')
				byte = (byte << 4) | (c - 'A' + 0x0A);

			else if(c >= 'a' && c <= 'f')
				byte = (byte << 4) | (c - 'a' + 0x0A);

			//ignore everything else
		}while(c != ',' && c != ' ' && c != '\t' && c != '\n' && c != '\r');
		//Serial.print("[b");
		Serial.print(byte , HEX);
		Serial.print(" ");
		storage[n*2] = byte;
		n++;
	}while(c != '\n' && c != '\r');

	Serial.print("[\n]");

	Serial.println("Command sequence:");
	for(int i=0; i < n; i++){
		if((i % 16) == 0)
			Serial.println();
		Serial.print(storage[i*2], HEX);
		Serial.print(" ");
	}

	storagePos = 0;
	return n;
}

/** Send and receive 1 byte */
uint8_t doByte(uint8_t byteToSend){
	clkHigh(); //clock should be high already
	clkOut();

	noInterrupts(); //timing is critical and Arduino keeps doing things

	uint8_t byteIn;
	uint8_t byteOut = byteToSend;
	for(int i=0; i < 8; i++){ //for each bit

		//set the output bit
		DCO_PORT = (DCO_PORT & ~(1 << DCO_BIT)) | ((byteOut & 0x80) >> (7 - DCO_BIT));
		byteOut = (byteOut << 1); //move to next bit

		clkLow(); //drop the clock, the lens sets our DCI after this edge.
		dbgLow();

		for(int j=0; j < BIT_LEN; j++); //bit delay on low clock
				__asm__("nop\n\t");

		clkHigh(); //raise the clock. The lens reads our DCO after this edge.
		uint8_t dciVal = DCI_INPORT;
		byteIn = (byteIn << 1) | ((dciVal >> DCI_BIT) & 0x01); //store the DCI bit in byteIn and shift
		dbgHigh();

		for(int j=0; j < BIT_LEN; j++);  //bit delay on high clock
					__asm__("nop\n\t");

	}


	clkHigh(); //enable pull-up for clock
	clkIn();   //and release the clock line output

	dbgLow(); //debug signature for end of byte
	dbgHigh();
	dbgLow();

	//Delay a bit to give the lens time to pull the clock low to signify it is busy
	// (we don't assume it always does, although it does appear to)
	for(int j=0; j < BIT_LEN; j++);
			__asm__("nop\n\t");
	dbgHigh(); //dbg signature for 'busy received'

	//wait for lens busy to end. This can take a long time, or forever
	int timeout = 0;
	while(!clockIsHigh()){
		timeout++;
		if(timeout > BUSY_TIMEOUT)
			goto busyTimeout;
	};
	dbgLow(); //debug signature: busy complete
	dbgHigh();
	dbgLow();

	// wait a little bit longer before proceeding with the next byte
	for(int j=0; j < POST_BUSY_WAIT; j++);
			__asm__("nop\n\t");

	dbgHigh();

	clkOut();
	interrupts(); //end of critical timing

	//store and return
	storage[storagePos++] = byteToSend;
	storage[storagePos++] = byteIn;
	return byteIn;

busyTimeout:
	dbgLow();	//debug error signature
	dbgHigh();
	dbgLow();
	dbgHigh();
	dbgLow();
	dbgHigh();
	dbgLow();
	storage[storagePos++] = 0xDE; //mark command failure (maybe)
	storage[storagePos++] = 0xAD;
	return 0xFF;
}

void loop() {

	while(1){

		//start up conversation
		delayMicroseconds(100);

		doByte(0x0A); //are you busy??
		doByte(0x00);

		delayMicroseconds(100);

		doByte(0x90); // ???
		doByte(0x8E);
		doByte(0x00);

		delayMicroseconds(100);

		doByte(0xB0); // request aperture data
		doByte(0x00);
		doByte(0x00);
		doByte(0x00);

		delayMicroseconds(100);

		doByte(0x80); // request lens data
		doByte(0x00); //? lens code
		doByte(0x00); // lens code
		doByte(0x00);
		doByte(0x00); // focal len in mm
		doByte(0x00);
		doByte(0x00); // focal len in mm (maybe they are min/max?)
		doByte(0x00);

		dumpStorage();

		while(true){
			int commandLen = readCommands();
			for(int i=0; i < commandLen; i++){
				uint8_t byteOut = storage[i*2]; //commands were preloaded into storage
				doByte(byteOut); //and puts byteIn in storage
			}

			dumpStorage();
		}

		/*for(int i=0; i < 20; i++){
							doByte(0x07);
							doByte(0x13);
							doByte(0x01);
				}

		dumpStorage();

		doByte(0x05);
		delay(1000);

		dumpStorage();

		for(int i=0; i < 20; i++){
			doByte(0x07);
			doByte(0x13);
			doByte(0xFF);
		}

		dumpStorage();

		doByte(0x06);
		delay(1000);

		dumpStorage();

		delay(2000);
		*/

	}
}








