/*
 * irdecode.c
 *
 *  Created on: 2014-5-2
 *      Author: twd2
 */

#include "irdecode.h"

void irdecode_init() {
	IR_IN;
}

unsigned char irdecode_readhead() {
	while(IR_DATA);
	unsigned int l=0,h=0;
	while(!IR_DATA && l<100) {
		++l;
		utils_delay_us(100);
	}
	while(IR_DATA && h<100) {
		++h;
		utils_delay_us(100);
	}
	return ((l>50) && (h>30)) || ((l>20 && l<50) && (h>15));
}

int irdecode_read(unsigned char *buff, unsigned int maxn) {
	irdecode_init();

	if (!irdecode_readhead())
		return -1; //head error

	unsigned int i,j;
	for(i=maxn;i!=0;--i) {
		*buff=0;
		for(j=8;j!=0;--j) {

			unsigned long l=0,h=0;
			while(!IR_DATA && l<100) {
				++l;
				utils_delay_us(100);
			}
			while(IR_DATA && h<25) {
				++h;
				utils_delay_us(100);
			}

			if(h>=25)
				return maxn-i; //read error

			*buff<<=1;
			*buff |= h>9;
		}
		++buff;
	}
	return maxn;
}

short irdecode_readbyte() {
	unsigned char buff[1];
	int count;
	count=irdecode_read(buff,1);
	if (count>0) {
		return buff[0];
	} else {
		return -1;
	}
}
