    * Analog 5 to Arduino 5 via level shifter
    * RF Status LED attached to digital pin 9
  
-   Created 06-JAN-2015 by Jon Brule
+   Created 13-JAN-2015 by Jon Brule
 ----------------------------------------------------------------------------- */
 #include <RFM69.h>
 #include <SPI.h>

// Receives a message from the RF mesh
//
boolean receiveFromRF() {
    if (radio.receiveDone()) {
        if (radio.DATALEN != sizeof(Message)) {
            Serial.print("Invalid payload received, not matching Message struct!");
        } else {
            memcpy(&msgRF, (byte*) radio.DATA, sizeof msgRF);
            msgRF.msg.rssi = radio.RSSI;
            haveDataRF = true;
        }
        if (radio.ACK_REQUESTED) {
            radio.sendACK();
        }
    }
    return haveDataRF;
}

//------------------------------------------------------------------------------
// Receives a message from the I2C bus (a.k.a Wire).
//
void receiveFromWire(int howMany) {
    if (howMany < sizeof msgI2C) {
        return;
    }

    // read into structure
    byte * p = (byte *) &msgI2C;
    for (byte i = 0; i < sizeof msgI2C; i++) {
        *p++ = Wire.read();
    }
    haveDataI2C = true; 
}

//------------------------------------------------------------------------------
// Publishes an I2C message to the RF mesh.
//
void sendToRF() {
    radio.send(msgI2C.msg.destination, msgI2C.raw, MSG_LENGTH);
}

//------------------------------------------------------------------------------
// Publishes an RF message to the I2C bus.
//
void sendToI2C() {
    Serial.println("xmit to i2c");
    Wire.beginTransmission(I2C_TARGET);
    Wire.write((byte *) &msgRF, sizeof msgRF);
    Wire.endTransmission();
}


// setup the arduino board
//
void setup() {  
  Serial.begin(BAUD_RATE);
  #if SERIAL
    Serial.print("\n[OHA RF Gateway - ");
    Serial.print(VERSION);
    Serial.println("]");
  #endif
    
  setup_rf();
  setup_i2c();
}

//------------------------------------------------------------------------------
// Initializes the RF radio.
//
static void setup_rf() {
  #if SERIAL
    Serial.print("Setup radio...");
  #endif
  radio.initialize(FREQUENCY, NODEID, NETWORKID);
  radio.setHighPower();
  delay(1000);
  #if DEBUG
    Serial.println("OK");
  #endif
}

//------------------------------------------------------------------------------
// Initializes the I2C bus.
//
static void setup_i2c() {
  #if SERIAL
    Serial.print("Setup I2C...");
  #endif
  Wire.begin (I2C_ADDR);
  Wire.onReceive(receiveFromWire);
  delay(1000);
  #if DEBUG
    Serial.println("OK");
  #endif
}


