#ifndef AOI_H
#define AOI_H

#include <stdint.h>

#define DBG 1

#define RESPONSE_MAX_LENGTH 5

class AOI {
	public:
		void init(uint8_t ssPin);
		void poll();
		void recognizeSerialNumber();
		uint32_t lastSerialNumber = 0;
		bool commandDone = false;
		bool commsOk = false;

	private:
		enum commands {
			UNUSED,
			COMMAND_GET_BYTE,
			COMMAND_COMMS_CHECK,
			COMMAND_RECOGNIZE_SERIAL_NUMBER,
			COMMAND_CHECK_EXECUTION
		};
		commands lastCommand = COMMAND_GET_BYTE;

		enum interfaceStates {
			INTERFACE_STATE_IDLE,
			INTERFACE_STATE_AWAITING_EXECUTION,
			INTERFACE_STATE_CHECK_EXECUTION,
			INTERFACE_STATE_GET_RESPONSE
		};
		interfaceStates interfaceState = INTERFACE_STATE_IDLE;

		uint8_t spiTransfer(uint8_t data);
		bool startCommand(commands command);
		void parseResponse();
		void interfaceStateMachine();
		void error();

		uint8_t ssPin = 0;
		unsigned long commsCheckTimestamp = 0;
		uint8_t responseLength = 0;
		unsigned long executionCheckTimestamp = 0;
		uint8_t responseBuffer[RESPONSE_MAX_LENGTH];
		uint8_t responseBufferCounter = 0;
};

#endif