/*
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://www.scatterweb.net and the mailinglist
scatterweb@lists.spline.inf.fu-berlin.de (subscription via the Website).
Berlin, 2003/2004/2005
*/

/** \file ehandler.c
 ** \ingroup scatternode
 ** \brief Methods for handling and forwarding sensor data events.
 **  
 ** Processes events according to ::sensorMask and ::announceFlags:
 **
 ** appconfig_t.sensorMask contains what sensors will be processed (commands "rsm"/"ssm"):
 ** <table>
 ** <tr><td> 0x10 </td><td> ::SENSOR_VIB     </td><td> Vibration sensor </td></tr>
 ** <tr><td> 0x08 </td><td> ::SENSOR_PIR     </td><td> PIR sensor </td></tr>
 ** <tr><td> 0x80 </td><td> ::SENSOR_BUTTON  </td><td> Button </td></tr>
 ** <tr><td> 0x01 </td><td> ::SENSOR_MIC     </td><td> Microphone </td></tr>
 ** <tr><td> 0x02 </td><td> ::SENSOR_TMP     </td><td> Temperature </td></tr>
 ** <tr><td> 0x04 </td><td> ::SENSOR_RC5     </td><td> RC5 Receiving </td></tr> 
 ** <tr><td> 0x40 </td><td> ::SENSOR_VOLTAGE     </td><td> Battery Voltage </td></tr> 
 ** </table>
 **
 ** appconfig_t.announceFlags contains what will be done with sensor events (commands "raf"/"saf"):  
 ** <table>
 ** <tr><td> 0x01 </td><td> ::AF_SERIAL  </td><td> Prints events to serial port. </td></tr>
 ** <tr><td> 0x02 </td><td> ::AF_RADIO   </td><td> Broadcasts events in a ::SENSOR_PACKET.  </td></tr>
 ** <tr><td> 0x04 </td><td> ::AF_ROOT    </td><td> Sends events with a ::routing_rootcast to the root of the network.  </td></tr>
 ** </table>
 **
 ** So to get all sensors reported over serial link and radio do:
 ** \code
 ** ssm FF
 ** saf 03
 ** \endcode
 **/
 
#include "ScatterWeb.Event.h"
#include "lib/ScatterWeb.Routing.h"

/// Application config held in ram, in EEPROM at address 0x0000.
appconfig_t AppConfig;

/// Loads application config from EEPROM[0x0000]-EEPROM[sizeof(appconfig_t)] to ::AppConfig.
void appconfig_load(){ IO_read( EADR_APPCONFIG, (UINT8*) &AppConfig, sizeof(appconfig_t)); }
/// Saves application config ::AppConfig to EEPROM[0x0000]-EEPROM[sizeof(appconfig_t)].
void appconfig_save(){ IO_write( EADR_APPCONFIG, (UINT8*) &AppConfig, sizeof(appconfig_t)); }

/// Sensor event handler.
void handleEvent(sdata_t* data){
    if(AppConfig.announceFlags & AF_SERIAL) Comm_print("%e\r\n", data);
    if(AppConfig.announceFlags & AF_RADIO){
      packet_t p; // = { BROADCAST, 0, SENSOR_PACKET, 0, 0, 0, (UINT8*) event, sizeof(*event) };
      p.to = BROADCAST;
      p.type = SENSOR_PACKET;
      p.header_length = 0;
      p.data = (UINT8*) data;
      p.data_length = sizeof(*data);
      Net_send(&p, NULL);
    }
    if(AppConfig.announceFlags & AF_ROOT){
      Routing_rootCast(RPT_SENSOR, (UINT8*)data, sizeof(*data));
    }
}

/// \name ScatterNode: Configuration commands.
/// \ingroup Commands
/// \todo Update esr and dsr.
//@{

/// Enable sensor reporting, which actually does a saf 14 what means take local events and broadcast them via radio.
COMMAND(esr, 0){ 
  AppConfig.announceFlags |=  AF_RADIO; 
  if(AppConfig.sensorMask & SENSOR_VIBRATION) Data_vibrationOff();
  if(AppConfig.sensorMask & SENSOR_MOVEMENT) Data_movementOff();
  if(AppConfig.sensorMask & SENSOR_BUTTON) Data_buttonOff();
  if(AppConfig.sensorMask & SENSOR_MICROPHONE) Data_microphoneOff();
  if(AppConfig.sensorMask & SENSOR_VOLTAGE) Data_batteryOff();
  AppConfig.sensorMask |= SENSOR_VIBRATION + SENSOR_MOVEMENT + SENSOR_BUTTON + SENSOR_MICROPHONE + SENSOR_VOLTAGE; 
  if(AppConfig.sensorMask & SENSOR_VIBRATION) Data_vibrationOn(1000);
  if(AppConfig.sensorMask & SENSOR_MOVEMENT) Data_movementOn(1500);
  if(AppConfig.sensorMask & SENSOR_BUTTON) Data_buttonOn(100);
  if(AppConfig.sensorMask & SENSOR_MICROPHONE) Data_microphoneOn(500, 600);
  if(AppConfig.sensorMask & SENSOR_VOLTAGE) Data_batteryOn(1000, 2600);
  appconfig_save(); 
}                
  
/// Disable sensor reporting, which clears bits 0x14 of announceFlags.
COMMAND(dsr, 0){ 
  AppConfig.announceFlags = 0x00; 
  if(AppConfig.sensorMask & SENSOR_VIBRATION) Data_vibrationOff();
  if(AppConfig.sensorMask & SENSOR_MOVEMENT) Data_movementOff();
  if(AppConfig.sensorMask & SENSOR_BUTTON) Data_buttonOff();
  if(AppConfig.sensorMask & SENSOR_MICROPHONE) Data_microphoneOff();
  if(AppConfig.sensorMask & SENSOR_TEMPERATURE) Data_temperatureOff();
  if(AppConfig.sensorMask & SENSOR_VOLTAGE) Data_batteryOff();  
  AppConfig.sensorMask = 0x00; 
  appconfig_save();   
}                

/// raf <br> Reads announcing state of the sensor board (appconfig_t.announceFlags).
COMMAND(raf, 0){ 
 String_write(term_reply, "%b [%s%s%s]", AppConfig.announceFlags,
                          ((AppConfig.announceFlags & AF_SERIAL) ? "SERIAL " : ""),
                          ((AppConfig.announceFlags & AF_RADIO) ? "RADIO " : ""),
                          ((AppConfig.announceFlags & AF_ROOT) ? "ROOT " : "")
  );
}                 

/// saf xx <br> Writes announcing state of the sensor board (appconfig_t.announceFlags) as a possible combination of ::AF_SERIAL, ::AF_RADIO, ::AF_ROOT.
COMMAND(saf, 0){ 
  AppConfig.announceFlags = String_fromHexToByte( &str[4]); appconfig_save(); 
  term_raf(str);
} 

/// rsm <br> Read sensor mask (appconfig_t.sensorMask).
COMMAND(rsm, 0){ 
  String_write(term_reply, "%b [%s%s%s%s%s%s%s]", AppConfig.sensorMask,
                          ((AppConfig.sensorMask & SENSOR_VIBRATION) ? "VIB " : ""),
                          ((AppConfig.sensorMask & SENSOR_MOVEMENT) ? "PIR " : ""),
                          ((AppConfig.sensorMask & SENSOR_BUTTON) ? "BUTTON " : ""),
                          ((AppConfig.sensorMask & SENSOR_MICROPHONE) ? "MIC " : ""),
                          ((AppConfig.sensorMask & SENSOR_RC5) ? "RC5 " : ""),
                          ((AppConfig.sensorMask & SENSOR_TEMPERATURE) ? "TEMP " : ""), 
                          ((AppConfig.sensorMask & SENSOR_VOLTAGE) ? "BAT " : "")
  ); 
}                    

/// ssm xx <br> Writes sensor mask (appconfig_t.sensorMask) to enables/disable sensors as a possible combination of ::SENSOR_VIB, ::SENSOR_PIR, ::SENSOR_BUTTON, ::SENSOR_MIC, ::SENSOR_TEMP. 
COMMAND(ssm, 0){ 
  if(AppConfig.sensorMask & SENSOR_VIBRATION) Data_vibrationOff();
  if(AppConfig.sensorMask & SENSOR_MOVEMENT) Data_movementOff();
  if(AppConfig.sensorMask & SENSOR_BUTTON) Data_buttonOff();
  if(AppConfig.sensorMask & SENSOR_MICROPHONE) Data_microphoneOff();
  if(AppConfig.sensorMask & SENSOR_RC5) Data_RC5Disable();
  if(AppConfig.sensorMask & SENSOR_TEMPERATURE) Data_temperatureOff(); 
  if(AppConfig.sensorMask & SENSOR_VOLTAGE) Data_batteryOff();  
  AppConfig.sensorMask = String_fromHexToByte(&str[4]); appconfig_save(); 
  if(AppConfig.sensorMask & SENSOR_VIBRATION) Data_vibrationOn(1000);
  if(AppConfig.sensorMask & SENSOR_MOVEMENT) Data_movementOn(1500);
  if(AppConfig.sensorMask & SENSOR_BUTTON) Data_buttonOn(100);
  if(AppConfig.sensorMask & SENSOR_MICROPHONE) Data_microphoneOn(500, 600);
  if(AppConfig.sensorMask & SENSOR_RC5) Data_RC5Enable();
  if(AppConfig.sensorMask & SENSOR_VOLTAGE) Data_batteryOn(1000, 2100);  
  //if(AppConfig.sensorMask & SENSOR_TMP) enableTemperature(5000, 0, 0, 0);    // Every 5 seconds.
  //if(AppConfig.sensorMask & SENSOR_TMP) enableTemperature(5000, 0x0080, 0, 0); // Only on change greater 1°C.
  if(AppConfig.sensorMask & SENSOR_TEMPERATURE) Data_temperatureOn(6144, 0x0080, 0x0080, 20); // Every 25 s or if changed more than 1°C.
  //if(AppConfig.sensorMask & SENSOR_TMP) enableTemperature(5000, 0x0200, 0x0040, 10); // Funnel function: Measure every 5 seconds and decrease range from 2°C for 0,5°C every 10*5 seconds.
  term_rsm(str); // answer is like rsm
} 

//@}

/// Init function.
bool Event_init(){
  appconfig_load();
  Comm_print("| AppConfig: \r\n", AppConfig.announceFlags, AppConfig.sensorMask);
  term_raf(NULL); Comm_print("| announceFlags: %s\r\n", term_reply);
  term_rsm(NULL); Comm_print("| sensorMask: %s\r\n", term_reply);
  System_registerCallback(C_SENSOR, handleEvent);  
  if(AppConfig.sensorMask & SENSOR_VIBRATION) Data_vibrationOn(1000);
  if(AppConfig.sensorMask & SENSOR_MOVEMENT) Data_movementOn(1500);
  if(AppConfig.sensorMask & SENSOR_BUTTON) Data_buttonOn(100);
  if(AppConfig.sensorMask & SENSOR_MICROPHONE) Data_microphoneOn(500, 600);
  if(AppConfig.sensorMask & SENSOR_RC5) Data_RC5Enable();
  if(AppConfig.sensorMask & SENSOR_VOLTAGE) Data_batteryOn(1000, 2100);
  //if(AppConfig.sensorMask & SENSOR_TMP) enableTemperature(5000, 0, 0, 0);    // Every 5 seconds.
  //if(AppConfig.sensorMask & SENSOR_TMP) enableTemperature(5000, 0x0080, 0, 0); // Only on change greater 1°C.
  if(AppConfig.sensorMask & SENSOR_TEMPERATURE) Data_temperatureOn(6144, 0x0080, 0x0080, 20); // Every 25 s or if changed more than 1°C.
  //if(AppConfig.sensorMask & SENSOR_TMP) enableTemperature(5000, 0x0200, 0x0040, 10); // Funnel function: Measure every 5 seconds and decrease range from 2°C for 0,5°C every 10*5 seconds. 
  return True;
}
