/*
  RFSniffer

  Usage: ./RFSniffer [<pulseLength>]
  [] = optional

  Hacked from http://code.google.com/p/rc-switch/
  by @justy to provide a handy RF code sniffer
*/

#include "../rc-switch/RCSwitch.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>


RCSwitch mySwitch;



void light()
{
    digitalWrite(25, LOW);
    usleep(200000);
    digitalWrite(25, HIGH);
    
    //printf("%d\n", digitalRead(25));
}

int main(int argc, char *argv[]) {
  
    // This pin is not the first pin on the RPi GPIO header!
    // Consult https://projects.drogon.net/raspberry-pi/wiringpi/pins/
    // for more information.
    int PIN = 7;

    if(wiringPiSetup() == -1) {
    printf("wiringPiSetup failed, exiting...");
    return 0;
    }

    int pulseLength = 0;
    if (argv[1] != NULL) pulseLength = atoi(argv[1]);

    mySwitch = RCSwitch();
    if (pulseLength != 0) mySwitch.setPulseLength(pulseLength);
    mySwitch.enableReceive(PIN);  // Receiver on interrupt 0 => that is pin #2
    
    pinMode(25, OUTPUT);
    
    
    #define LIVE 1
    
    static int i=0;
    unsigned long value = 0;
    static int values[LIVE] = {0};
    
    while(1) {
        while(1) {
            if (mySwitch.available()) {
                value = mySwitch.getReceivedValue();
                values[i] = value;

                if (value == 0)
                {
                    printf("Unknown encoding\n");
                }
                else
                {
                    light();
                    printf("i=%d, Received %lu\n", i, values[i] );
                }

                fflush(stdout);
                mySwitch.resetAvailable();
                
                if (i != 0) {
                    if (values[1] == values[0]+1)
                    printf("有我的按钮发来数据\n");
                }
                if (i != 1) {
                    if (values[0] == values[1]+1)
                    printf("有我的按钮发来数据\n");
                }
                
                
                if (i==LIVE) {
                    i=0;
                    break;
                }
                i=i+1;
            }
            
        }

        usleep(100);
    }


    return 0;
}

