/*attiny recepteur IR 4 sorties V5
  21/02/2024
  Dominique Hudry
  lien: https://github.com/LuisMiCa/IRsmallDecoder
  simulation: https://wokwi.com/projects/387263826718912513
  utilise une interruption donc la led IR branchée sur pin2
   
     wokwi                 carmp3           peeKTON
  touche code déc     en hex  en déc    en hex  en déc
    1      48            C     12          D     13   
    2      24            18    24          11    17
    3      122           5E    194         15    21
    4      16            8     8           E     14
    power  162          power  0           power 73
    
            Brochage ATtiny85

               =|1  U  8|= VCC
  Sortie4 <--3 =|2     7|= 2<-- PinIR
  Sortie3 <--4 =|3     6|= 1--> Sortie1
           GND =|4     5|= 0--> Sortie2
*/

// constantes
const byte pinSortie1 = 1;
const byte pinSortie2 = 0;
const byte pinSortie3 = 4;
const byte pinSortie4 = 3;

// variables
bool etatsSorties[] = {false, false, false, false};
byte compteur = 0;

#define IR_SMALLD_NEC
#include <IRsmallDecoder.h>
#include "telecommandewokwi.h"
//#include "telecommandecarmp3.h"
//#include "telecommandepeekTON.h"
IRsmallDecoder irDecoder(2);
irSmallD_t irData;

void setup() {
  pinMode(pinSortie1, OUTPUT);
  pinMode(pinSortie2, OUTPUT);
  pinMode(pinSortie3, OUTPUT);
  pinMode(pinSortie4, OUTPUT);
}

void loop() {
  digitalWrite(pinSortie1, etatsSorties[0]);
  digitalWrite(pinSortie2, etatsSorties[1]);
  digitalWrite(pinSortie3, etatsSorties[2]);
  digitalWrite(pinSortie4, etatsSorties[3]);

  if (irDecoder.dataAvailable(irData)) {
    gestionCommandeIR();
  }
}

void gestionCommandeIR() {
  switch (irData.cmd) {
    case touche1:
      toggleSortie(0);
      break;
      
    case touche2:
      toggleSortie(1);
      break;
      
    case touche3:
      toggleSortie(2);
      break;
      
    case touche4:
      toggleSortie(3);
      break;
      
    case power:
      if (compteur == 0) {
        activerToutesLesSorties();
      } else if (compteur == 4) {
        desactiverToutesLesSorties();
      }
      break;

    default:
      break;
  }
  delay(500);
}

void toggleSortie(int index) {
  etatsSorties[index] = !etatsSorties[index];
  compteur += etatsSorties[index] ? 1 : -1;
}

void activerToutesLesSorties() {
  for (byte i = 0; i < 4; i++) {
    etatsSorties[i] = true;
  }
  compteur = 4;
}

void desactiverToutesLesSorties() {
  for (byte i = 0; i < 4; i++) {
    etatsSorties[i] = false;
  }
  compteur = 0;
}
ATTINY8520PU