/****************************************************************************/
/* Copyright 2016 MBARI.                                                    */
/* MBARI Proprietary Information. All rights reserved.  
 * Change log
 * 18MAY BDJ 
 *  -Adding rotational maintenance function
 * 19AUG16 BDJ v1.2b
 *  -switch baud to 19200 so straight through programming comms
 *  -integrate "advance" function
 * 
 * 30NOV2023 move position to eeprom                                        */
/****************************************************************************/

//#include <p24fxxxx.h>
//#include <p24FV16KM202.h>
#include <stdio.h>
#include <string.h>
#include <xc.h>
#include "uart1.h"
#include "timer.h"
#include "eeprom.h"
#include "elmo.h"

#define VER "2.0"

/* general definitions */
#include "typedefs.h" //True/False, UINT16, etc...


// Configuration Bits to make the part run from Internal FRCDIV
// Oscillator.



// PIC24FV16KM202 Configuration Bit Settings

// 'C' source line config statements

// FBS
#pragma config BWRP = OFF               // Boot Segment Write Protect (Disabled)
#pragma config BSS = OFF                // Boot segment Protect (No boot program flash segment)

// FGS
#pragma config GWRP = OFF               // General Segment Write Protect (General segment may be written)
#pragma config GSS0 = OFF                // General Segment Code Protect (No Protection)

// FOSCSEL
#pragma config FNOSC = FRC              // Oscillator Select (Fast RC Oscillator (FRC))
#pragma config SOSCSRC = ANA            // SOSC Source Type (Analog Mode for use with crystal)
#pragma config LPRCSEL = LP             // LPRC Oscillator Power and Accuracy (Low Power, Low Accuracy Mode)
#pragma config IESO = ON                // Internal External Switch Over bit (Internal External Switchover mode enabled (Two-speed Start-up enabled))

// FOSC
#pragma config POSCMOD = NONE           // Primary Oscillator Configuration bits (Primary oscillator disabled)
#pragma config OSCIOFNC = 1          // CLKO Enable Configuration bit (CLKO output signal enabled)
#pragma config POSCFREQ = HS            // Primary Oscillator Frequency Range Configuration bits (Primary oscillator/external clock input frequency greater than 8MHz)
#pragma config SOSCSEL = SOSCHP         // SOSC Power Selection Configuration bits (Secondary Oscillator configured for high-power operation)
#pragma config FCKSM = CSDCMD           // Clock Switching and Monitor Selection (Both Clock Switching and Fail-safe Clock Monitor are disabled)

// FWDT
#pragma config WDTPS = PS32768          // Watchdog Timer Postscale Select bits (1:32768)
#pragma config FWPSA = PR128            // WDT Prescaler bit (WDT prescaler ratio of 1:128)
#pragma config FWDTEN = OFF              // Watchdog Timer Enable bits (WDT enabled in hardware)
#pragma config WINDIS = OFF             // Windowed Watchdog Timer Disable bit (Standard WDT selected(windowed WDT disabled))

// FPOR
#pragma config BOREN = BOR3             // Brown-out Reset Enable bits (Brown-out Reset enabled in hardware, SBOREN bit disabled)
//#pragma config RETCFG = 1             //  (Retention regulator is not available)
#pragma config PWRTEN = ON              // Power-up Timer Enable bit (PWRT enabled)
#pragma config I2C1SEL = PRI            // Alternate I2C1 Pin Mapping bit (Use Default SCL1/SDA1 Pins For I2C1)
//#pragma config BORV = V18               // Brown-out Reset Voltage bits (Brown-out Reset set to lowest voltage (1.8V))
#pragma config MCLRE = ON               // MCLR Pin Enable bit (RA5 input pin disabled, MCLR pin enabled)

// FICD
#pragma config ICS = PGx3               // ICD Pin Placement Select bits (EMUC/EMUD share PGC3/PGD3)

//globals
unsigned long AlarmCnt;//Global incremented in AlarmISR
//Globally accessible FIFO for UART port2
unsigned char RxFifo[RxFifoSz]; // The statically allocated FIFO buffer (500 bytes)
//                SCI1 FIFO routines are slightly modified versions from
//                "Embedded Microcomputer Systems: Real Time Interfacing",
//                Jonathan W. Valvano 9/7/00
unsigned char *RxPutPt;    // Pointer of where to put next char in SCI1 FIFO
unsigned char *RxGetPt;    // Pointer of where to get next char from SCI1 FIFO
                  // FIFO is empty if PutPt=GetPt 
                  // FIFO is full  if PutPt+1=GetPt





int main(void)
{
    unsigned int i;
    CHAR ch;
    int position=-1;
    
    
    // Set up output pin for LED
    TRISAbits.TRISA0 = 0;
    
    //turn on max322 converter
    TRISBbits.TRISB14=0;
    LATBbits.LATB14 = 1;
    
    vInitTimer1();    // Initialization of Timer1
    
    // init uarts
    vInitU1(); //main comms to vehicle
    vInitU2(); //comms to elmo
    
    printf("CANON SAMPLER TWITTER %s\r\n",VER);
    
    //get the last valid position
    position = eeRead(ePOS);
    
    DelaySecs ( 4 ); //let the elmo boot
    
    //check where elmo wants to go
    printf("Last pos=%d, UI[4]=%d\r\n",position, elmo_UI_get(4));
    
    //for (i=0;i<RxFifoSz;i++)printf("%c-",RxFifo[i]);
    
    
    //LED ON means good power up
    LATAbits.LATA0 = 1; //leave LED on
    
 //               while(1)
 //           {        position++;
 //                    eeWrite(position);
 //                   printf("EEPROM=%d\n",eeRead());
 //                   DelaySecs (60);
 //           }
    
    
    while(1)
    {   
      printf("S>");     //prompt 
      while (!U1STAbits.URXDA); //wait for char
      ch = cGetCharU(1); //Read one character form UART1
      printf("%c\r\n",ch);  //echo
        
      switch(ch) //====================================================
       { // and depending upon the ch, do the appropriate action =======
         case '?' :  break; // causes directory prompt to be displayed
         case ' ' :  break; // wait for another character
         case  -1 :  break; // wait for another character
     
         case 'P' :  // read position
                    position = eeRead(ePOS);
                    printf("EEPROM=%d, Elmo UI[1]=%d\r\n",position,elmo_UI_get(1));
	                break;
         case 'C' :  // clear position
                    position = 0;
                    eeWrite(position,ePOS);
                    printf("EEPROM=%d\r\n",eeRead(ePOS));
                    elmo_UI_set(1,position);
	                break;
         case '+' :  //increase position
                    position++;
                     eeWrite(position,ePOS);
                    printf("EEPROM=%d\r\n",eeRead(ePOS));
                    elmo_UI_set(1,position);
                    break;
        case '-' :  //decrease position
                    position--;
                     eeWrite(position,ePOS);
                    printf("EEPROM=%d\r\n",eeRead(ePOS)); 
                    elmo_UI_set(1,position);
	                break; 
        case 'S' : //sample!!!   
                    elmo_sample();
                    break;
        case 'E' : //talk directly to the elmo (power cycle to return)  
                    elmo_passthru();
                    break;
        case 'R' : //rotate carousel 1x           
                    elmo_rotational_maint();
                    break; 
        case 'H' : //rotate carousel 1x           
                    elmo_HOME();
                    break;  
        case '1' : //change pump time  
                    elmo_change_pump_time();
                    printf("New pump time (s) =%d\r\n",eeRead(ePUMP));
                    break;         
        case '2' : //change purge time  
                    elmo_change_purge_time();
                    printf("New purge time (s) =%d\r\n",eeRead(ePURGE));
                    break;      
        case 'T' : //test code chunks
                    printf("EEPROM=%d\r\n",eeRead(ePUMP));
                    elmo_change_pump_time();
                    printf("EEPROM=%d\r\n",eeRead(ePUMP));
                    break;
        case 'U' : //show menu and pump times
                    printf("CANON SAMPLER TWITTER%s\r\n",VER);
                    printf(" S.ample      :  R.otate    : E.lmo passthru\r\n");
                    printf(" 1.pump time  :  T.est code : C.lear position\r\n");
                    printf(" +.inc    pos :  -.dec pos  : P.osition\r\n");
                    printf(" 2.purge time :  H.ome\r\n");
                    printf("Pump time = %d s\r\n",eeRead(ePUMP));
                    printf("Purge time = %d s\r\n",eeRead(ePURGE));
                    break;
        default  :  printf(" input unknown \r\n");

       } //==============================================================
        
    }
}




