#include <stdio.h>
#include <stdlib.h>

// This program just sends an assembled 5-byte packet over IR to a Lennox
// air conditioner.  The assembly of the packet is done by my home automation
// controller, but the relevant part of the code is in this directory in
// the file named 'encoder_decoder.c'

// we use the irslinger library from https://github.com/bschwind/ir-slinger
// compile with cc -o send-lennox-code send-lennox-code.c -lpigpio -lm
#include "irslinger.h"

/*
      The mark/space timings were estimated from sampling, but it is possible that they
   should be the NEC times: 562.5 for 0 and 1687.5 for 1 ?
 */

void addpair(int mark, int space, int *codes, int *count) {
  codes[*count] = mark; codes[(*count)+1] = space;
  *count = (*count)+2;
}

void outbyte(int b, int *codes, int *count) {
  int i;
  for (i = 0; i < 8; i++) {
    if (b&1) {
      addpair(512, 1652, codes, count);
    } else {
      addpair(512, 574, codes, count);
    }
    b = b>>1;
  }
}

void sendcode(int code0, int code1, int code2, int code3, int code4, int *codes, int *count) {
  int code5 = ((0xff + code0 + code1 + code2 + code3 + code4) ^ 0xff)&255;
  addpair(4378, 4699, codes, count);
    outbyte(code0, codes, count);
    outbyte(code1, codes, count);
    outbyte(code2, codes, count);
    outbyte(code3, codes, count);
    outbyte(code4, codes, count);
    outbyte(code5, codes, count);
  addpair(512, 4699, codes, count);
  addpair(4378, 4699, codes, count);
    outbyte(code0^0xff, codes, count);
    outbyte(code1^0xff, codes, count);
    outbyte(code2^0xff, codes, count);
    outbyte(code3^0xff, codes, count);
    outbyte(code4^0xff, codes, count);
    outbyte(code5^0xff, codes, count);
  addpair(512, 4699, codes, count);
}

int main(int argc, char **argv) {
  int rc, count=0, result, codes[1024], code[6];
  unsigned int outPin = 23;       // The Broadcom pin number the signal will be sent on
  int frequency = 38000;          // The frequency of the IR signal in Hz
  double dutyCycle = 0.5;         // The duty cycle of the IR signal. 0.5 means for every cycle,
                                  // the LED will turn on for half the cycle time, and off the other half

  if ((argc == 6) || (argc == 7)) { // currently we'll ignore the proffered checksum and will recalculate it
    rc = sscanf(argv[1], "%x", &code[0]);
    rc += sscanf(argv[2], "%x", &code[1]);
    rc += sscanf(argv[3], "%x", &code[2]);
    rc += sscanf(argv[4], "%x", &code[3]);
    rc += sscanf(argv[5], "%x", &code[4]);
    // rc should be equal to 5.
    sendcode(code[0], code[1], code[2], code[3], code[4], codes, &count);
    result = irSlingRaw(outPin, frequency, dutyCycle, codes, count);
  } else {
    fprintf(stderr, "syntax: send-lennox-code xx xx xx xx xx\n");
    exit(1);
  }

  exit(0);
  return 1;
}