/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/* 
 * File:   DigitalIO.cpp
 * Author: yovany
 * 
 * Created on June 19, 2018, 2:41 PM
 */

#include "DigitalIO.h"
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <bcm2835.h>

DigitalIO::DigitalIO(uint8_t ioPin, uint8_t ioDir) {
//    printf("Params -> ioPin: %d, ioDir: %d", ioPin, ioDir);
    bcm_init();
    io_pin = bcmPin(ioPin);
    io_dir = ioDir;
    if(ioDir == AS_INPUT) {
        asInput();
    } else {
        asOutput();
    }
//    prev_state = read();
}

DigitalIO::DigitalIO(const DigitalIO& orig) {
}

DigitalIO::~DigitalIO() {
}

void DigitalIO::asInput(){
    bcm2835_gpio_fsel(io_pin, BCM2835_GPIO_FSEL_INPT);
    bcm2835_gpio_set_pud(io_pin, BCM2835_GPIO_PUD_UP);
}

void DigitalIO::asOutput(){
    bcm2835_gpio_fsel(io_pin, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_write(io_pin, 0);
}

uint8_t DigitalIO::read(){
    return bcm2835_gpio_lev(io_pin);
}

uint8_t DigitalIO::bcmPin(uint8_t ioPin) {
    switch(ioPin) {
//        case 2:
//            return RPI_V2_GPIO_P1_03;
//        case 3:
//            return RPI_V2_GPIO_P1_05;
        case 4:
            return RPI_V2_GPIO_P1_07;
        case 17:
            return RPI_V2_GPIO_P1_11;
        case 18:
            return RPI_V2_GPIO_P1_12;
        case 27:
            return RPI_V2_GPIO_P1_13;
        case 22:
            return RPI_V2_GPIO_P1_15;
        case 23:
            return RPI_V2_GPIO_P1_16;
        case 24:
            return RPI_V2_GPIO_P1_18;
        case 25:
            return RPI_V2_GPIO_P1_22;
        case 5:
            return RPI_V2_GPIO_P1_29;
        case 6:
            return RPI_V2_GPIO_P1_31;
        case 12:
            return RPI_V2_GPIO_P1_32;
        case 13:
            return RPI_V2_GPIO_P1_33;
        case 16:
            return RPI_V2_GPIO_P1_36;
        case 26:
            return RPI_V2_GPIO_P1_37;
    }
    printf("[DigitalIO] -> IO pin not supported: %d\n", ioPin);
    exit(1);
//    return 0;
}

void DigitalIO::release() {
    if(io_dir == AS_INPUT){
        bcm2835_gpio_set_pud(io_pin, BCM2835_GPIO_PUD_OFF);
    }else{
        bcm2835_gpio_write(io_pin, 0);
    }
}

void DigitalIO::bcm_init(){
    if (!bcm2835_init()){
        printf("BCM2835 Error!!...\n");
        exit(1);
    }
}

void DigitalIO::bcm_end(){
    bcm2835_close();
}
