/*
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 "ScatterWeb.System.h"
#include <stdarg.h>

volatile UINT8* serial_line;

#if !defined(EYE)
#if defined(eGate)
#define SERIAL_STOP       do{ P1OUT |= 0x02; }while(0)   ///> Set CTS to 1 to stop receiving bytes.
#define SERIAL_RESUME     do{ P1OUT &= ~0x02; }while(0) ///> Set CTS to 0 to resume receiving bytes.
#define RTS               (P1IN & 0x01)
#else
#define SERIAL_STOP       do{}while(0) ///> Set CTS to 1 to stop receiving bytes.
#define SERIAL_RESUME     do{}while(0) ///> Set CTS to 0 to resume receiving bytes.
#define RTS               (0)
#endif

volatile UINT8 serial_buf1[SERIAL_BUFSIZE]; ///< The serial ISR writes bytes into this buffer.
volatile UINT8 serial_buf2[SERIAL_BUFSIZE];
volatile UINT8* buf;
volatile int serial_pos;                    ///< Current position in receive buffer ::serial_buffer.


COMMAND(brt, 0) { Comm_init(String_parseInt(&str[4], NULL)); }

interrupt(UART1RX_VECTOR) usart1_rx (void){
  UINT8 temp = RXBUF1;
  if(temp=='\r') return;    // filter out carriage returns
  if(temp=='\n'){           // line is complete 
    SERIAL_STOP;            // set CTS to 1 to stop receiving bytes
    buf[serial_pos] = '\0'; // terminate
    if(buf==serial_buf1){
      buf         = serial_buf2;
      serial_line = serial_buf1;
    }
    else {
      buf         = serial_buf1;
      serial_line = serial_buf2;
    }
    WAKEUPLPM1(usart1_rx, MF_SERIAL_RX);
    serial_pos = 0;
   } // END line complete
   else if(temp=='\b') { if(serial_pos>0) serial_pos--; } // backspace  
   else {                                                 // write byte into buf
      if(serial_pos==SERIAL_BUFSIZE) return;              // dont write anymore if buf full
      buf[serial_pos++]=temp;
   }
}

void initReceiving() {
  // init vars
  UINT16 i;
  serial_pos = 0;
  for(i=0; i<SERIAL_BUFSIZE; i++){ serial_buf1[i] = 0x00; serial_buf2[i] = 0x00; }
  serial_line = 0;
  buf = serial_buf1;
  ME2 |= UTXE1 + URXE1; // Enable USART0 TXD/RXD, disabling does not yield any powersavings
  IE2 |= URXIE1;        // Enable USART0 RX interrupt  
  Comm_clear();
}

void sendRS232(UINT8 data) {  // sends one byte
  System_startWatchdog();        // not good to have that here 
  while RTS;                  // for USBStick wait til RTS is set to 0      
  while (!(IFG2 & UTXIFG1));  // loop until USART1 TX buffer ready
  TXBUF1 = data;
}

void sendRS232Chars(char* data, int n) { int i; for(i=0; i<n; i++) sendRS232(data[i]); }

#endif

bool Comm_init(UINT8 bps) {   
  #if !defined(EYE)      
  //////////////////////////////////////// RS232
  UCTL1 = CHAR;                         // 8-bit character
  switch(bps) {
  #if defined(DCO_2458KHZ)
    case BPS_2400  : UTCTL1 = SSEL1; UBR01 = 0x00; UBR11 = 0x04; UMCTL1 = 0x00; break; /* uart1 2457600Hz 2400bps */ // UTCTL1 = SSEL0; UBR01 = 0x0D; UBR11 = 0x00; UMCTL1 = 0x6D; break; // RS232 auf 2400 Bit/s // UCLK = ACLK
    case BPS_14400 : UTCTL1 = SSEL1; UBR01 = 0xAA; UBR11 = 0x00; UMCTL1 = 0x6D; break; /* uart1 2457600Hz 14405bps */                    
    case BPS_19200 : UTCTL1 = SSEL1; UBR01 = 0x80; UBR11 = 0x00; UMCTL1 = 0x00; break; // RS232 auf 19200 Bit/s // UCLK = MCLK // 2,457MHz/19200 = 128 -> 0x80                       
    case BPS_38400 : UTCTL1 = SSEL1; UBR01 = 0x40; UBR11 = 0x00; UMCTL1 = 0x00; break; // RS232 auf 38400 Bit/s UCLK = MCLK  2,457MHz/38400 = 64 -> 0x40                      
    case BPS_57600 : UTCTL1 = SSEL1; UBR01 = 0x2A; UBR11 = 0x00; UMCTL1 = 0x5B; break; // RS232 auf 57600 Bit/s UCLK = MCLK 2,457MHz/57600 = 42.7 -> 0x2A
    case BPS_115200: UTCTL1 = SSEL1; UBR01 = 0x15; UBR11 = 0x00; UMCTL1 = 0x4A; break; // RS232 auf 115200 Bit/s UCLK = MCLK 2,457MHz/115200 = 21.4 -> 0x15 
  #elif defined(DCO_4506KHZ)
    case BPS_2400  : UTCTL1 = SSEL1; UBR01 = 0x55; UBR11 = 0x07; UMCTL1 = 0x09; break; /* uart1 4505600Hz 2400bps */ // UTCTL1 = SSEL0; UBR01 = 0x0D; UBR11 = 0x00; UMCTL1 = 0x6D; break; // RS232 with 2400 bps @ 32768 Hz ACLK
    case BPS_14400 : UTCTL1 = SSEL1; UBR01 = 0x38; UBR11 = 0x01; UMCTL1 = 0xEF; break; /* uart1 4505600Hz 14399bps */
    case BPS_19200 : UTCTL1 = SSEL1; UBR01 = 0xEA; UBR11 = 0x00; UMCTL1 = 0x5B; break; /* uart1 4505600Hz 19197bps */   // RS232 with 19200 bps @  Mhz           
    case BPS_38400 : UTCTL1 = SSEL1; UBR01 = 0x75; UBR11 = 0x00; UMCTL1 = 0x52; break; /* uart1 4505600Hz 38378bps */ // RS232 with 38400 bps @  Mhz 
    case BPS_57600 : UTCTL1 = SSEL1; UBR01 = 0x4E; UBR11 = 0x00; UMCTL1 = 0x44; break; /* uart1 4505600Hz 57616bps */  // RS232 with 57600 bps @  Mhz                            
    case BPS_115200: UTCTL1 = SSEL1; UBR01 = 0x27; UBR11 = 0x00; UMCTL1 = 0x10; break; /* uart1 4505600Hz 115232bps */  // RS232 with 115200 bps @  Mhz        
  #else
  #error No DCO frequency in init_Uart().
  #endif
  }
  initReceiving();
  Comm_logLevel = Configuration.boot_logLevel;
  return True;
  #else
  return False;
  #endif
}

bool Comm_print(const char *fmt, ...) {
  #if !defined(EYE)
  va_list argp;
  if((Comm_logLevel & 0x0F) >= NO){
    va_start(argp, fmt);
    String_abstractWrite(sendRS232, fmt, argp);  
    va_end(argp);
  }
  return True;
  #else
  return False;
  #endif
}

bool Comm_log(UINT8 level, const char* fmt, ...) {
  #if !defined(EYE)
  va_list argp;
  if((Comm_logLevel & 0x0F) >= level){
    va_start(argp, fmt);
    String_abstractWrite(sendRS232, fmt, argp);  
    va_end(argp);
  }
  return True;
  #else
  return False;
  #endif
}

bool Comm_clear() {
  #if !defined(EYE)
  runModule &= ~MF_SERIAL_RX;
  serial_line = 0;
  SERIAL_RESUME;
  return True;
  #else
  return False;
  #endif
}
