/*
   Copyright (c) 2019 Boot&Work Corp., S.L. All rights reserved
   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU Lesser General Public License as published by
   the Free Software Foundation, either version 3 of the License, 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 Lesser General Public License for more details.
   You should have received a copy of the GNU Lesser General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <SimpleComm.h>
#include <WifiModule.h>
int leds[] = {Q0_0, Q0_1, Q0_2, Q0_3, Q0_4, Q0_5};
int select = 0;
void open_all(void){
  select = 0;
  while(select < 7){
    digitalWrite(leds[select], HIGH);
    select += 1;
  }
}
SimplePacket packet;
////////////////////////////////////////////////////////////////////////////////////////////////////
void setup() {
  Serial.begin(115200UL);
  WifiModule.begin(115200UL);
  SimpleComm.begin();
  Serial.println("Wifi Module started");
  pinMode(Q0_0, OUTPUT);
  pinMode(Q0_1, OUTPUT);
  pinMode(Q0_2, OUTPUT);
  pinMode(Q0_3, OUTPUT);
  pinMode(Q0_4, OUTPUT);
  pinMode(Q0_5, OUTPUT);
  
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void loop() {
  static uint32_t lastSent = 0UL;
  if (millis() - lastSent > 1000) {
    if (select<=6) {
      digitalWrite(leds[select-1], LOW);
      digitalWrite(leds[select], HIGH);
      select += 1;
    }
    else{
      select = 0;
    }
    lastSent = millis();
  }
  
  if (SimpleComm.receive(WifiModule, packet)) {
    const char *data = packet.getString();
    const char *match = 'STOP';
    Serial.println(data);
    
    if (strcmp(data, match) == 0 && digitalRead(Q0_3) == HIGH) {
      Serial.println("\nYOU HAVE WON");
      open_all();
      packet.setData("W");
      if (!SimpleComm.send(WifiModule, packet, 0)) {
        Serial.println("Send packet error");
      }
    }
  }
}
