package com.henrypump.poc;

/**
 * Created by patrickjmcd on 2/1/17.
 */

import mraa.Dir;
import mraa.Gpio;
import mraa.mraa;
import mraa.Platform;
import mraa.Result;

import static java.lang.Thread.sleep;

public class DigitalOut {
    private int channel;
    private Gpio gpioPin;
    private int value;

    DigitalOut(int channel, int startupValue){
        this.channel = channel;
        if (channel != 99) {
            Platform platform = mraa.getPlatformType();

            if (platform != Platform.INTEL_EDISON_FAB_C) {
                System.err.println("Error: This program can only be run on edison");
                System.exit(Result.ERROR_INVALID_PLATFORM.swigValue());
            }
            this.gpioPin = new Gpio(this.channel);
            gpioPin.dir(Dir.DIR_OUT);
            this.value = startupValue;
            write(value);
        }
    }

    public void write(int writeVal){
        if ( value != writeVal & channel != 99) {
            gpioPin.write(writeVal);
            value = writeVal;
        }
    }

    public void write(int writeVal, boolean force){
        if ( value != writeVal || force) {
            if (channel != 99) {
                gpioPin.write(writeVal);
                value = writeVal;
            }
        }
    }

    public static void main(String[] args){
        try {
            DigitalOut testOut2 = new DigitalOut(2, 0);
            testOut2.write(1);
            sleep(500);
            testOut2.write(0);

            DigitalOut testOut3 = new DigitalOut(3, 0);
            testOut3.write(1);
            sleep(500);
            testOut3.write(0);

            DigitalOut testOut4 = new DigitalOut(4, 0);
            testOut4.write(1);
            sleep(500);
            testOut4.write(0);

            DigitalOut testOut5 = new DigitalOut(5, 0);
            testOut5.write(1);
            sleep(500);
            testOut5.write(0);

            DigitalOut testOut6 = new DigitalOut(6, 0);
            testOut6.write(1);
            sleep(500);
            testOut6.write(0);

            DigitalOut testOut7 = new DigitalOut(7, 0);
            testOut7.write(1);
            sleep(500);
            testOut7.write(0);

        } catch(InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
    }

}
