// © RiceMotion ( Robert Carl Rice ) 2012-2016 - All rights reserved


// This software makes use of tools and libraries obtained from open source projects or released for

// use by relevant hardware manufactures. However, this software is NOT a part of any open source project.

// It is released only on a "need to know" basis for beta testers of the "RiceCNC Interpolation Engine".

// Recipents of this source code must respect the confidential nature of this software and prevent any

// distribution that could result in counterfeit copies of the "RiceCNC Interpolation Engine".


// © RiceMotion ( Robert Carl Rice ) 2012-2016 - All rights reserved

#include <MySerial.h>

#include <Machine.h>

#include <MainCommands.h>

#include <Timers.h>



#define vitualComBaudrate 115200

#define CommandBufferSize 1024


char  serialCommandString[ CommandBufferSize ];

char* serialCommandPtr    = serialCommandString;


void

     MySerial::setup() {


     Serial.setBufferSize( 1024, 1024 ); // default is 256

     Serial.begin( vitualComBaudrate );

     Serial.flush();


     String msg = "";

     MainCommands::signOnMsg( &msg );

     Serial.println( msg ); };



void

     MySerial::loop() {


     while ( Serial.available() ) {

          Timers::setLoopLED( false );


          char inChar    = (char) Serial.read();


          if ( inChar == '\n' ) {

               if ( serialCommandPtr != serialCommandString ) { // ignore empty lines

                    *serialCommandPtr  = '\0'; // NULL terminate

               

                    String msg = "";

                    MainCommands::processCommand( serialCommandString, &msg );


                    // Since the command was received via serial link block if necessary sending the reply

                    if ( msg.length() > 0 )

                         Serial.println( msg );

               

                    serialCommandPtr   = serialCommandString; }; } // reset


          else if ( inChar == '\r' ||

               serialCommandPtr == &serialCommandString[ CommandBufferSize ] ) {} // ignore


          else {

               *serialCommandPtr  = inChar;

               serialCommandPtr++; }; }; };


void

     MySerial::background() {


     // pending method added by RCR 2/10/2015 to avoid blocking on a background message

     if ( Serial.txCapacity() < 128 )

          return;

     String msg = "";


     if ( Machine::firstMachine )

          Machine::firstMachine->background( &msg );


     if ( msg.length() )

          sendMessageNonBlocking( &msg ); };


void

     MySerial::sendMessageNonBlocking( String* msgPtr ) { // Debug messages

     

     // Just ignore the message if it would cause blocking

     if ( Serial.txCapacity() > msgPtr->length() )

          Serial.println( *msgPtr ); };

          

bool

     MySerial::isBusy() {


     return Serial.available(); };