/*
 * Watch the conversation between a Canon EF camera and the lens.
 * 
 * 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.
 * 
 * Data 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

//input from clock (Arduino Digital I/O 11 = PB5)
#define CLK_PORT	PINB
#define CLK_DIR 	DDRB
#define CLK_BIT	5
#define clockIsHigh()	(CLK_PORT & (1 << CLK_BIT))

//input from data camera out (Arduino Digital I/O 12 = PB6)
#define DCO_PORT	PINB
#define DCO_DIR 	DDRB
#define DCO_BIT	6

//input from data camera input (Arduino Digital I/O 9 = PH6)
#define DCI_PORT	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 protocol observation.");

  CLK_DIR &= ~(1 << CLK_BIT);	// clock as input
  DCO_DIR &= ~(1 << DCO_BIT);	// dco as input
  DCI_DIR &= ~(1 << DCI_BIT);	// dci as input
  DBG_DIR |= (1 << DBG_BIT);	// debug as output


}

//maximum number of iterations for bit timeout
#define BIT_TIMEOUT 50

//maximum number of iterations for busy state or next byte timeout
#define BYTE_TIMEOUT 300

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

}

void loop() {
	
	while(1){ //for each byte (don't exit the loop, I'm not sure how long the Arduino code will take) 

		while(!clockIsHigh()); //wait for clean state before starting (high)
		dbgHigh();

		while(clockIsHigh()); //wait for the initial clk low
		noInterrupts();
		dbgLow();

		//start the byte read
		unsigned char byteOut = 0x00;
		unsigned char byteIn = 0x00;
		int timeout = 0;
		for(int i=0; i < 8; i++){ //for each bit

			//wait for the low
			while(clockIsHigh()){
				timeout++;
				if(timeout > BIT_TIMEOUT) goto fail;
			};

			dbgLow();

			//wait for high
			while(!clockIsHigh()){
				timeout++;
				if(timeout > BIT_TIMEOUT) goto fail;
			};
			//get these as fast as possible after the clock rise
			uint8_t dciVal = DCI_PORT;
			uint8_t dcoVal = DCO_PORT;

			dbgHigh();

			//add that bit (MSB first) to the collected byte
			byteOut = (byteOut << 1) | ((dcoVal >> DCO_BIT) & 0x01);
			byteIn = (byteIn << 1) | ((dciVal >> DCI_BIT) & 0x01);

		}

		dbgLow(); //byte complete signature, pt.1
		dbgHigh();

		storage[storagePos++] = byteOut; //storage
		storage[storagePos++] = byteIn;

		dbgLow(); //byte complete signature, pt.2
		dbgHigh();

		//wait for lens busy pull-down to start (we must catch this otherwise we'll get lost)
		while(clockIsHigh()){
			timeout++;
			if(timeout > BYTE_TIMEOUT) goto fail;
		};
		dbgLow();

		//while the lens is busy we can reenable interrupts for a bit
		interrupts();
		if(storagePos >= STORAGE_SIZE){ //if buffer is full
			dumpStorage(); //output storage
			return; //and give up, because that will have taken too long
		}

		//wait for end of camera busy
		while(!clockIsHigh()){
			timeout++;
			if(timeout > BYTE_TIMEOUT) goto fail;
		};
		dbgHigh();

		//ready for next byte
		continue;

		fail:

		//error signature on debug line
		dbgLow();
		dbgHigh();
		delayMicroseconds(10);
		dbgLow();
		delayMicroseconds(10);
		dbgHigh();
		delayMicroseconds(10);
		dbgLow();
		delayMicroseconds(10);
		dbgHigh();
		dbgLow();
		dbgHigh();
		interrupts();

		//mark data as DEAD
		storage[storagePos++] = 0xDE;
		storage[storagePos++] = 0xAD;
		if(storagePos >= STORAGE_SIZE){
			dumpStorage();
			return;
		}

	}

}








