/*
Copyright 2003/2004, Freie Universitaet Berlin. All rights reserved.

These sources were developed at the Freie Universität Berlin, Computer
Systems and Telematics group.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
 
- Neither the name of Freie Universitaet Berlin (FUB) nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

This software is provided by FUB and the contributors on an "as is"
basis, without any representations or warranties of any kind, express
or implied including, but not limited to, representations or
warranties of non-infringement, merchantability or fitness for a
particular purpose. In no event shall FUB or contributors be liable
for any direct, indirect, incidental, special, exemplary, or
consequential damages (including, but not limited to, procurement of
substitute goods or services; loss of use, data, or profits; or
business interruption) however caused and on any theory of liability,
whether in contract, strict liability, or tort (including negligence
or otherwise) arising in any way out of the use of this software, even
if advised of the possibility of such damage.

This implementation was developed by the CST group at the FUB.
Contributors: Bjoern Lichtblau

For documentation and questions please use the web site
http://scatterweb.mi.fu-berlin.de and the mailinglist
scatterweb@lists.spline.inf.fu-berlin.de (subscription via the Website).
Berlin, 2003/2004/2005
*/

#include <io.h>
#include <signal.h> 
#include "ScatterWeb.System.h"

#if defined(ESB430) || defined(EYE430)
#define IS_IR_RECEIVING   (TBCCTL0 & CCIE)
#define RC5_A_TV1     0
#define RC5_A_TV2     1
#define RC5_A_VCR1    5
#define RC5_A_VCR2    6
#define RC5_C_0       0
#define RC5_C_1       1
#define RC5_C_2       2
#define RC5_C_3       3
#define RC5_C_4       4
#define RC5_C_5       5
#define RC5_C_6       6
#define RC5_C_7       7
#define RC5_C_8       8
#define RC5_C_9       9
#define RC5_C_REW     13
#define RC5_C_VU      16
#define RC5_C_VD      17
#define RC5_CODE    (ir_data & 0x003F)           ///< Returns code of received packet.
#define RC5_ADR     ((ir_data & 0x07C0) >> 6)    ///< Returns data of received packet.
#define RC5_TOG     ((ir_data & 0x0800) >> 11)   ///< Returns toggle bit of received packet.
#define RC5_ERR     ((ir_data & 0x2000) >> 13)   ///< If 1 error occured during transmission.
#define SIR1  (P1OUT |= 0x01) ///< MACRO: Puts IR sending diode high.
#define SIR0  (P1OUT &= 0xFE) ///< MACRO: Puts IR sending diode low.
#define SET_EBIT    (ir_data |= 0x2000)
#define CLEAR_EBIT (ir_data &= 0xDFFF)
#define SET_DABIT   (ir_data |= 0x1000)
#define CLEAR_DABIT (ir_data &= 0xEFFF)

#if defined(DCO_2458KHZ)
#define BIT75 3282      ///< 3 quarters of a bit after start, 3282 cyc @ 2,4576Mhz = 1335us.
#define BIT50 2188      ///< Half of bit length, 2188 cyc @ 2,4576Mhz = 890 us.
#elif defined(DCO_4506KHZ)
#define BIT75 6015      ///< 3 quarters of a bit after start, 6015 cyc @ 4,5056Mhz = 1335us.
#define BIT50 4009      ///< Half of bit length, 4009 cyc @ 4,5056Mhz = 890 us.
#endif

UINT16 ir_pos;             ///< current position in frame
UINT16 ir_data;            ///< here a received packet is saved
UINT16 ir_databuffer;      ///< temporary buffer for receiving
UINT8 ir_temp;           ///< saves the first half of the manchester bit
#endif

#if defined(ESB430) || defined(EYE430)
volatile void sendIRHigh(UINT16 j){
    volatile UINT16 i;
    for(i=0; i<j; i++){ // 26 us
      SIR1; SIR1; SIR1; SIR1; SIR1; SIR1; SIR1; // added 3
      SIR0; SIR0; SIR0; SIR0; 
      SIR0; SIR0; SIR0; SIR0; 
      SIR0; SIR0; SIR0; SIR0; 
      SIR0; SIR0; SIR0; SIR0; 
      SIR0; SIR0; // 25 alltogether
    }  
}

volatile void sendIRLow(UINT16 j){
    volatile int i;
    for(i=0; i<j; i++){
      SIR0; SIR0; SIR0; SIR0; SIR0; SIR0; SIR0; 
      SIR0; SIR0; SIR0; SIR0; 
      SIR0; SIR0; SIR0; SIR0; 
      SIR0; SIR0; SIR0; SIR0; 
      SIR0; SIR0; SIR0; SIR0;  
      SIR0; SIR0; // 25 together
    }  
}

interrupt(TIMERB0_VECTOR) Timer_B0() {
    if(ir_pos <= 25) {
      if(ir_pos % 2) {                             // odd position
        if(ir_temp && !(P1IN & 0x04)) {           // 1 - 0 -->  write 1 
          ir_databuffer +=1;
          ir_databuffer = ir_databuffer << 1;  
        } 
        else if(!ir_temp && (P1IN & 0x04)) {      // 0 - 1 -->  write 0 
          ir_databuffer = ir_databuffer << 1;  
        } 
        else { 
          SET_EBIT;
          if(P1IN & 0x04) ir_databuffer += 1;
          ir_databuffer = ir_databuffer << 1;
        }
      }
      else {                                    // even position
        ir_temp = P1IN & 0x04;
      }
    }
    if(ir_pos==25) {                          // end reached
      ir_databuffer = ir_databuffer >> 1; 

      if(! RC5_ERR && ( (ir_databuffer & 0x0FFF) != (ir_data & 0x0FFF) ) ){
        ir_data = ir_databuffer;
        SET_DABIT;
        Data_yellowOn();
        WAKEUPLPM1(Timer_B0, MF_RC5);
      }   
    }
    if(ir_pos==27) {
      TBCCTL0 &= ~CCIE;  
      Data_greenOff();  
      Data_yellowOff();    
      // reenable interrupt for falling edge
      P1IFG &= ~(0x04);
      P1IE  |= 0x04;                    // enable interrupt for recir RC5
    }
  ir_pos++;
  TBCCR0 += BIT50;        // set new interrupt
  TBCCTL0 &= ~CCIFG;
}
#endif

COMMAND(sir, SERIALONLY) { 		                            
    #if defined(ESB430) || defined(EYE430)
    UINT8 high;
    UINT8 low;
    UINT16 data;
    high = String_fromHexToByte((char*) &str[4]);
    low = String_fromHexToByte((char*) &str[6]);
    data = high;
    data = (data << 8) + low;
    Data_RC5Send(data);
    Comm_print("%x gesendet. \n", data); 
    #else
    String_write(term_reply, "NOT SUPPORTED: %s (wrong platform)", str);
    #endif
}

UINT8 sensorFlags;

#if defined(ESB430) || defined(EYE430) || defined(ECR430)

#define SENSORCALLBACK(Sensor, State)    do { \
                                             sdata_t data; \
                                             data.id = Configuration.id; \
                                             data.sensor = (Sensor); \
                                             data.timeStamp = CURRENT_TIME; \
                                             data.value = State; \
                                             if(callbacks[C_SENSOR]) callbacks[C_SENSOR](&data); }while(0) 

UINT16 _vibDebounceDelay;
UINT16 _tmpInterval;   ///< How often is the temperature read in systems ticks (~1ms)
UINT16 _tmpStartRange; ///< How much must the temperature differs from the last value.
UINT16 _tmpDiffStep;   ///< How much measures until Range is decremented with Diff.
UINT16 _tmpDiff;       ///< How much the Range is decreased every DiffStep measures.
temp_t _tmpLast;       ///< Last signaled temperature.
UINT16 _tmpSteps;      ///< Current steps, if this reaches DiffStep do Range -= Diff 
UINT16 _tmpRange;      ///< Current range, if abs(current temperature - last temperature) > range signal new temperature.
UINT16 _batInterval;   ///< How often is the battery voltage read in systems ticks (~1ms).
UINT16 _batThresh;     ///< When battery voltage drops below this level, every _batInterval ticks voltage will get signaled.

void vibCheck() {
  if(P1IFG & SENSOR_VIBRATION) {
      P1IFG &= ~SENSOR_VIBRATION;
      Timers_add(_vibDebounceDelay, vibCheck, 0xFFFF);    
  }
  else {
    P1IE |= SENSOR_VIBRATION;
  	SENSORCALLBACK(SENSOR_VIBRATION, 0);
  }
}

void temperatureCheck() {
  temp_t temperature;
  sdata_t data = { Configuration.id, SENSOR_TEMPERATURE, CURRENT_TIME, 0 };
  UINT16 diff;
  #if defined(ESB430) || defined(EYE430)
  System_clStartConversion();
  #endif
  temperature = System_getTemperature(); // Adjust range if enabled.
  if(_tmpDiffStep>0) {
    _tmpSteps++;
    if(_tmpSteps==_tmpDiffStep) {
      _tmpSteps = 0;
      if(_tmpRange < _tmpDiff) _tmpRange = 0;
      else                     _tmpRange -= _tmpDiff;
    }
  }
  if(_tmpLast.s < temperature.s) diff = temperature.s - _tmpLast.s;
  else                           diff = _tmpLast.s - temperature.s;
  if(diff >= _tmpRange) {
    data.value = temperature.u;
    if(callbacks[C_SENSOR]) callbacks[C_SENSOR](&data); 
    _tmpLast = temperature;
    _tmpRange = _tmpStartRange;
    _tmpSteps = 0;
  }
  Timers_add(_tmpInterval, temperatureCheck, 0xFFFF);
}

void batteryCheck() {
  sdata_t data = { Configuration.id, SENSOR_VOLTAGE, CURRENT_TIME, 0 };
  unsigned int bat = BATTERYVOLTAGE;
  if(bat < _batThresh) {
    data.value = bat;
    if(callbacks[C_SENSOR]) callbacks[C_SENSOR](&data); 
  }
  Timers_add(_batInterval, batteryCheck, 0xFFFF);
}

interrupt(PORT1_VECTOR) p1_irq (void) {
  #if defined(ESB430) || defined(EYE430)
  if(P1IE & P1IFG & SENSOR_MOVEMENT) {
    sensorFlags |= SENSOR_MOVEMENT;
    P1IE  &= ~SENSOR_MOVEMENT;
    P1IFG &= ~SENSOR_MOVEMENT;
  }
  if(P1IE & P1IFG & 0x04) Data_RC5EventHandler();
  #endif
  if(P1IE & P1IFG & SENSOR_VIBRATION) {
    sensorFlags |= SENSOR_VIBRATION;
    P1IE  &= ~SENSOR_VIBRATION;
    P1IFG &= ~SENSOR_VIBRATION;
  } 
  WAKEUPLPM1(p1_irq, MF_SENSORS);
}

#endif

#if defined(ESB430) || defined(EYE430)

UINT16 _pirDebounceDelay;
UINT16 _buttonDebounceDelay;
UINT16 _micDiff;
UINT16 _micDebounceDelay;

void pirCheck() {
  if(P1IFG & SENSOR_MOVEMENT){
      P1IFG &= ~SENSOR_MOVEMENT;
      Timers_add(_pirDebounceDelay, pirCheck, 0xFFFF);    
  }
  else {
    P1IE |= SENSOR_MOVEMENT;
  	SENSORCALLBACK(SENSOR_MOVEMENT, 0);
  }
}

void buttonCheck() {
  if(P2IES & SENSOR_BUTTON) {     // button down was debounced
    if(!(P2IN & SENSOR_BUTTON)) { // button is still down
      P2IES &= ~SENSOR_BUTTON;    // set interrupt to detect rising edge (button up)
      P2IFG &= ~SENSOR_BUTTON;    // clear ifg
      P2IE |= SENSOR_BUTTON;      // and enable interrupt again
    }
    else {                        // button already up again
  	    SENSORCALLBACK(SENSOR_BUTTON, 0);
       	Timers_add(_buttonDebounceDelay, buttonCheck, 0xFFFF);
         P2IES &= ~SENSOR_BUTTON; // debounce is now for button up        	
    }
  }
  else {                          // button up was debounced
    if(P2IN & SENSOR_BUTTON) {    //button is still up
      P2IES |= SENSOR_BUTTON;     // set interrupt to detect falling edge (button down)
      P2IFG &= ~SENSOR_BUTTON;    // clear ifg
      P2IE |= SENSOR_BUTTON;      // and enable interrupt again
    }
    else {                        // button already down again
   	  SENSORCALLBACK(SENSOR_BUTTON, 1);
      Timers_add(_buttonDebounceDelay, buttonCheck, 0xFFFF);             	        
      P2IES |= SENSOR_BUTTON;     // debounce is now for button down

    }
  }
}

void micCheck2() {
  if(MIC & MICIFG) {
      MIC = 0;
      Timers_add(_micDebounceDelay, micCheck2, 0xFFFF);
  }
  else {
    MIC = MICIE;
  	SENSORCALLBACK(SENSOR_MICROPHONE, 0);     
  }
}

void micCheck1() {
  if(MIC & MICIFG) {  // still loud
      MIC = 0;
      Timers_add(_micDebounceDelay, micCheck2, 0xFFFF);
      SENSORCALLBACK(SENSOR_MICROPHONE, 1);
  }
  else {              // silent again
    MIC = MICIE;    
  }
}

#endif

#if defined(ESB430) || defined(EYE430)
interrupt(PORT2_VECTOR) p2_irq (void) { /// ISR for Port 2, only detects button presses.
  if(P2IE & P2IFG & SENSOR_BUTTON){
    sensorFlags |= SENSOR_BUTTON;
    P2IE  &= ~SENSOR_BUTTON;
    P2IFG &= ~SENSOR_BUTTON;
  } 
  WAKEUPLPM1(p1_irq, MF_SENSORS);
}
#endif

bool Data_vibrationOn(UINT16 delay) {
  #if defined(ESB430) || defined(EYE430) || defined(ECR430)
  _vibDebounceDelay = delay;
  P1IFG &= ~SENSOR_VIBRATION;
  P1IE |= SENSOR_VIBRATION;
  return True;
  #else
  return False;
  #endif
}

bool Data_vibrationOff() {
  #if defined(ESB430) || defined(EYE430) || defined(ECR430)
  P1IE &= ~SENSOR_VIBRATION;
  Timers_remove(vibCheck, 0xFFFF);
  sensorFlags &= ~ SENSOR_VIBRATION;
  return True;
  #else
  return False;
  #endif
}

bool Data_movementOn(UINT16 delay) {
  #if defined(ESB430) || defined(EYE430)
  _pirDebounceDelay = delay;
  P1IFG &= ~SENSOR_MOVEMENT;
  P1IE |= SENSOR_MOVEMENT;
  return True;
  #else
  return False;
  #endif
}

bool Data_movementOff(){
  #if defined(ESB430) || defined(EYE430)
  P1IE &= ~SENSOR_MOVEMENT;
  Timers_remove(pirCheck, 0xFFFF);
  sensorFlags &= ~ SENSOR_MOVEMENT;
  return True;
  #else
  return False;
  #endif
}

bool Data_buttonOn(UINT16 delay) {
  #if defined(ESB430) || defined(EYE430)
  _buttonDebounceDelay = delay;
  P2IES |= SENSOR_BUTTON;         // wait for raising edge
  P2IFG &= ~SENSOR_BUTTON;
  P2IE |= SENSOR_BUTTON;
  return True;
  #else
  return False;
  #endif
}

bool Data_buttonOff() {
  #if defined(ESB430) || defined(EYE430)
  P1IE &= ~SENSOR_BUTTON;
  Timers_remove(buttonCheck, 0xFFFF);
  sensorFlags &= ~ SENSOR_BUTTON;
  return True;
  #else
  return False;
  #endif
}

bool Data_microphoneOn(UINT16 delay, UINT16 diff) {
  #if defined(ESB430) || defined(EYE430)
  _micDiff = diff;
  _micDebounceDelay = delay;
  MIC &= ~MICIFG;
  MIC |= MICIE;
  return True;
  #else
  return False;
  #endif
}

bool Data_microphoneOff(){
  #if defined(ESB430) || defined(EYE430)
  MIC = 0x00;
  Timers_remove(micCheck1, 0xFFFF);
  Timers_remove(micCheck2, 0xFFFF);
  sensorFlags &= ~SENSOR_MICROPHONE;
  return True;
  #else
  return False;
  #endif
}

bool Data_temperatureOn(UINT16 interval, UINT16 range, UINT16 diff, UINT16 stepsperdiff) {
  #if defined(ESB430) || defined(EYE430) || defined(ECR430)
  #if defined(ESB430) || defined(EYE430)
  System_clStartConversion();
  #endif
  _tmpInterval = interval;
  _tmpStartRange = range;
  _tmpDiff = diff;
  _tmpDiffStep = stepsperdiff;
  _tmpLast.u = 0xC000;
  _tmpRange = _tmpStartRange;
  _tmpSteps = 0;
  Timers_add(_tmpInterval, temperatureCheck, 0xFFFF);
  return True;
  #else
  return False;
  #endif
}

bool Data_temperatureOff() {
  #if defined(ESB430) || defined(EYE430) || defined(ECR430)
  Timers_remove(temperatureCheck, 0xFFFF);
  return True;
  #else
  return False;
  #endif
}

bool Data_batteryOn(UINT16 interval, UINT16 thresh) {
  #if defined(ESB430) || defined(EYE430) || defined(ECR430)
  _batInterval = interval;
  _batThresh = thresh;
  Timers_add(_batInterval, batteryCheck, 0xFFFF);
  return True;
  #else
  return False;
  #endif  
}

bool Data_batteryOff() {
  #if defined(ESB430) || defined(EYE430) || defined(ECR430)
  Timers_remove(batteryCheck, 0xFFFF);
  return True;
  #else
  return False;
  #endif
}

bool Data_init() {
  #if defined(ESB430) || defined(EYE430) || defined(ECR430)
  sensorFlags = 0x00;
  callbacks[C_SENSOR] = NULL;
  Data_on();
  return True;
  #else
  Data_on();
  return False;
  #endif
}

bool Data_on() {
  #if defined(ESB430) || defined(EYE430) || defined(ECR430)
  #if defined(ECR430)
  P2OUT |= 0x08;
  System_wait(2000);
  P5OUT |= 0x10;
  #endif
  P5OUT &= ~0x20; // turn power on for sensors
  #endif
  #if defined(ESB430) || defined(EYE430)
  System_wait(150000); // Needed for microphone
  return True;
  #else
  return False;
  #endif  
}

bool Data_off() {
  #if defined(ESB430) || defined(EYE430) || defined(ECR430)
  P5OUT |= 0x20;  // turn power off for sensors
  #if defined(ECR430)
  // Important for ECR430: When disabling Power (set P55 to 1) set
  // P50-P54 and P23 to ouput 0, else current will flow from them.
  P2OUT &= ~0x08;
  P5OUT &= ~0x1C;
  #endif
  return True;
  #else
  return False;
  #endif
}

bool Data_sensorHandler() {
  #if defined(ESB430) || defined(EYE430) || defined(ECR430)
  if(sensorFlags & SENSOR_VIBRATION) {
      Timers_add(_vibDebounceDelay, vibCheck, 0xFFFF);  
      SENSORCALLBACK(SENSOR_VIBRATION, 1);
      sensorFlags &= ~SENSOR_VIBRATION;    
  }
  #if defined(ESB430) || defined(EYE430)
  if(sensorFlags & SENSOR_MOVEMENT) {
      Timers_add(_pirDebounceDelay, pirCheck, 0xFFFF);  
      SENSORCALLBACK(SENSOR_MOVEMENT, 1);
      sensorFlags &= ~SENSOR_MOVEMENT;    
  }
  if(sensorFlags & SENSOR_BUTTON) {
      Timers_add(_buttonDebounceDelay, buttonCheck, 0xFFFF);  
    	if((P2IES & SENSOR_BUTTON))  SENSORCALLBACK(SENSOR_BUTTON, 1);
    	if(!(P2IES & SENSOR_BUTTON)) SENSORCALLBACK(SENSOR_BUTTON, 0);   	
      sensorFlags &= ~SENSOR_BUTTON;    
  }
  if(sensorFlags & SENSOR_MICROPHONE) {
      sensorFlags &= ~SENSOR_MICROPHONE;    
      MIC = 0;
      Timers_add(50, micCheck1, 0xFFFF);
  }
  #endif
  // Reset flag if nothing more needs handling
  dint(); nop();
  if(sensorFlags==0) runModule &= ~MF_SENSORS;
  eint();
  return True;
  #else
  return False;
  #endif
}

bool Data_beeperOn() {
  #if defined(ESB430) || defined(EYE430) || defined(ESS430)
  P2OUT |=  0x08;
  return True;
  #else
  return False;
  #endif
}


bool Data_beeperOff() {
  #if defined(ESB430) || defined(EYE430) || defined(ESS430)
  P2OUT &= ~0x08;
  return True;
  #else
  return False;
  #endif
}

bool Data_beeperToggle() {
  #if defined(ESB430) || defined(EYE430) || defined(ESS430)
  P2OUT ^=  0x08;
  return True;
  #else
  return False;
  #endif
}

bool Data_greenOn() {
  #if defined(ESB430) || defined(EYE430) || defined(ECR430) || defined(ESS430)
  do{ P2OUT &= ~0x02; }while(0);
  return True;
  #else
  return False;
  #endif
}

bool Data_greenOff() {
  #if defined(ESB430) || defined(EYE430) || defined(ECR430) || defined(ESS430)
  do{ P2OUT |=  0x02; }while(0);
  return True;
  #else
  return False;
  #endif
}

bool Data_greenToggle() {
  #if defined(ESB430) || defined(EYE430) || defined(ECR430) || defined(ESS430)
  do{ P2OUT ^=  0x02; }while(0);
  return True;
  #else
  return False;
  #endif
}

bool Data_redOn() {
  #if defined(ESB430) || defined(EYE430) || defined(ECR430) || defined(ESS430)
  do{ P2OUT &= ~0x01; }while(0);
  return True;
  #elif defined(ESF430)
  do{ P5OUT &= ~0x01; }while(0);
  return True;
  #else
  return False;
  #endif
}

bool Data_redOff() {
  #if defined(ESB430) || defined(EYE430) || defined(ECR430) || defined(ESS430)
  do{ P2OUT |=  0x01; }while(0);
  return True;
  #elif defined(ESF430)
  do{ P5OUT |=  0x01; }while(0);
  return True;
  #else
  return False;
  #endif
}

bool Data_redToggle() {
  #if defined(ESB430) || defined(EYE430) || defined(ECR430) || defined(ESS430)
  do{ P2OUT ^=  0x01; }while(0);
  return True;
  #elif defined(ESF430)
  do{ P5OUT ^=  0x01; }while(0);
  return True;
  #else
  return False;
  #endif
}

bool Data_yellowOn() {
  #if defined(ESB430) || defined(EYE430) || defined(ECR430) || defined(ESS430)
  do{ P2OUT &= ~0x04; }while(0);
  return True;
  #else
  return False;
  #endif
}

bool Data_yellowOff() {
  #if defined(ESB430) || defined(EYE430) || defined(ECR430) || defined(ESS430)
  do{ P2OUT |=  0x04; }while(0);
  return True;
  #else
  return False;
  #endif
}

bool Data_yellowToggle() {
  #if defined(ESB430) || defined(EYE430) || defined(ECR430) || defined(ESS430)
  do{ P2OUT ^=  0x04; }while(0);
  return True;
  #else
  return False;
  #endif
}

UINT8 Data_greenLed() {
  #if defined(ESB430) || defined(EYE430) || defined(ECR430) || defined(ESS430)
  return P2OUT & 0x02;
  #elif defined(ESF430)
  return 0;
  #else
  return 0;
  #endif
}

UINT8 Data_redLed() {
  #if defined(ESB430) || defined(EYE430) || defined(ECR430) || defined(ESS430)
  return P2OUT & 0x01;
  #elif defined(ESF430)
  return P5OUT & 0x01;
  #else
  return 0;
  #endif
}

UINT8 Data_yellowLed() {
  #if defined(ESB430) || defined(EYE430) || defined(ECR430) || defined(ESS430)
  return P2OUT & 0x04;
  #elif defined(ESF430)
  return 0;
  #else
  return 0;
  #endif
}

volatile bool Data_RC5Send(int data) {
  #if defined(ESB430) || defined(EYE430)
  volatile int mask = 0x2000;
  data |= 0xF000;
  dint();
  while(mask != 0){
    if(!(mask & data)){
      sendIRHigh(36); // 0,890 ms needed, (16+36*110) @ 4505600 = 0,882 ms
      sendIRLow(36);  
    } else {
      sendIRLow(36);
      sendIRHigh(36);
    }
    mask /= 2;
  }
  eint();
  return True;
  #else
  return False;
  #endif
}

bool Data_RC5Enable() {
  #if defined(ESB430) || defined(EYE430)
  P1IES |= 0x04;  // Important for IR-RC5 receive to detect the first FALLING edge
  P1IFG &= ~0x04;
  P1IE  |= 0x04; 
  return True;
  #else
  return False;
  #endif
}

bool Data_RC5Disable() {
  #if defined(ESB430) || defined(EYE430)
  dint(); nop();
  TBCCTL0 &= ~CCIE; 
  P1IE &= ~0x04;
  eint();
  return True;
  #else
  return False;
  #endif
}

void Data_RC5ReceiveHandler() {
  #if defined(ESB430) || defined(EYE430)
  sdata_t data = { Configuration.id, SENSOR_RC5, CURRENT_TIME, 0 };
  data.value = ir_data;
  if(callbacks[C_SENSOR]) callbacks[C_SENSOR](&data);
  runModule &= ~MF_RC5;
  #endif
}

void Data_RC5EventHandler() {
  #if defined(ESB430) || defined(EYE430)
  if(P1IN & 0x04) return; // high again, just a peak
  ir_pos = 0;
  ir_databuffer = 0;  
  CLEAR_EBIT;
  // the first timer interrupt will occur in the mid of the first half of the second start bit 
  TBCCR0 = TBR + BIT75;     // set first TBCCR1 IRQ to 75% of RC5 bitlength
  TBCCTL0 &= ~CCIFG;        // clear previous compare flag
  TBCCTL0 |= CCIE;          // CCR0 interrupt enabled, interrupt occurs when timer equals CCR0
  P1IE &= ~0x04;   // disable interrupt for P12 ( ReceiveIR )
  #endif
}
