/*
   parking-access-s1 is demo application of parking access.
      
   Copyright (C) 2022 Maurilio Pizzurro 

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 1, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this library.  If not, see <http://www.gnu.org/licenses/>.
*/

/* 
    Pulsante verde per simulare la barriera IR
    Pulsante giallo per simulare il contatto chiave
*/

#include <IRremote.h>
#include <LiquidCrystal.h>

#include "parkingaccess.h"

#define PIN_RECEIVER 2   // Signal Pin of IR receiver

IRrecv receiver(PIN_RECEIVER);
//Servo RCservo;

LiquidCrystal lcd(12, 11, 10, 9, 8, 7);

/* PIN_SERVO pin a cui è connesso il servo */
const byte PIN_SERVO        = 5;
/* PIN_IR_BARRIER contatto pulito relay IR RX */
const byte PIN_IR_BARRIER   = 4;
/* PIN_KEY contatto pulito comando chiave */
const byte PIN_KEY          = 6;

ParkingAccess pa(PIN_SERVO, PIN_IR_BARRIER);

#define IRCMD_PLAY  168


void setup()
{
    Serial.begin(115200);
    pinMode(PIN_KEY, INPUT_PULLUP);
    
    receiver.enableIRIn(); // Start the receiver
    lcd.begin(16, 2);

    pinMode(A1, OUTPUT);

    Serial.print("Press play or\nyellow button\n");
    pa.begin();
    //pa.goTest();
}

bool checkOpenKey() {
    static uint8_t counter = 0;
    static uint8_t _delay = 10;
    if (digitalRead(PIN_KEY) == LOW) {
        delay(_delay);
        _delay = 1;
        counter++;
        if (counter == 10) {
            counter = 0;
            _delay = 10;
            return true;
        }
    } else {
        counter = 0;
        _delay = 10;
    }
    return false;
}
uint32_t loopCounter;
bool logic= false;
void loop() {
    logic = !logic;
    digitalWrite(A1, logic);
    

    
    uint8_t command = 0;

    if (receiver.decode()) {
        command = receiver.decodedIRData.command;
        receiver.resume();  // Receive the next value
    } else if (checkOpenKey()) {
        command = IRCMD_PLAY;
    } 

    if (command == IRCMD_PLAY) {
        pa.open();
    }
    loopCounter++;
    pa.run();
    /*if (millis() > 1000) {
        Serial.println(loopCounter);
        while(true);
    }*/


} // end loop()

D0D1D2D3D4D5D6D7GNDLOGIC