#include <avr/io.h>
#include <stdint.h>

#include "pin_programming.h"

/* Pin definitions */


#define PIN_PROG_1_DDR     DDRB
#define PIN_PROG_1_PORT    PORTB
#define PIN_PROG_1_PIN     PB6
#define PIN_PROG_1_PORTIN  PINB

#define PIN_PROG_2_DDR     DDRB
#define PIN_PROG_2_PORT    PORTB
#define PIN_PROG_2_PIN     PB7
#define PIN_PROG_2_PORTIN  PINB

#define PIN_PROG_3_DDR     DDRD
#define PIN_PROG_3_PORT    PORTD
#define PIN_PROG_3_PIN     PD4
#define PIN_PROG_3_PORTIN  PIND



void Configure_Pin_Programming_Pins(void)
{
	/* Set pins as input */
	PIN_PROG_1_DDR &= ~(1 << PIN_PROG_1_PIN);
	PIN_PROG_2_DDR &= ~(1 << PIN_PROG_2_PIN);
	PIN_PROG_3_DDR &= ~(1 << PIN_PROG_3_PIN);

	/* Enable pull-ups */ // TODO: enable once the boards have been fixed!
	PIN_PROG_1_PORT |= (1 << PIN_PROG_1_PIN);
	PIN_PROG_2_PORT |= (1 << PIN_PROG_2_PIN);
	PIN_PROG_3_PORT |= (1 << PIN_PROG_3_PIN);
}

uint8_t Get_Own_Identifier(void)
{
	/* The upper four bits of the ID are the module ID while the lower four bits are the serial
	 * number set by the pin programming.
	 * Switch 3 corresponds to bit 0
	 * Switch 2 corresponds to bit 1
	 * Switch 1 corresponds to bit 2
	 */
	uint8_t id = (MODULE_ID_SENSOR << 4);

	id |= ((((PIN_PROG_3_PORTIN & (1 << PIN_PROG_3_PIN)) == 0) << 0) | \
	       (((PIN_PROG_2_PORTIN & (1 << PIN_PROG_2_PIN)) == 0) << 1) | \
	       (((PIN_PROG_1_PORTIN & (1 << PIN_PROG_1_PIN)) == 0) << 2));

	return id;
}
