// © 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 <SsiDeviceQueue.h>

#include <SsiBuffer.h>

#include <SSI.h>

#include <GPIO.h>


#include <inc/hw_gpio.h>



SsiDeviceQueue::SsiDeviceQueue( SSI* aSsi, uint32_t myNumber ) {

     ssi                         = aSsi;

     number                    = myNumber;


     nextSsiDeviceQueue     = NULL;

     startPointer          = NULL;

     currentCR               = NULL; };


SsiDeviceQueue::~SsiDeviceQueue() {};


// byte mode is used for ST Microelectronics daisy-chain dSpin

byte

     SsiDeviceQueue::getByte() {


     return currentCR ?

          currentCR->getByte() :

          0; };


void

     SsiDeviceQueue::receiveByte( uint32_t data ) { // Always called by TxEOT Interrupt


     if ( currentCR )

          currentCR->receiveByte( data );


     else

          currentCR     = startPointer; };


void

     SsiDeviceQueue::dequeue() { // CR ended - txEOT interrupts already disabled


     startPointer     = startPointer->nextSsiBuffer;

     currentCR          = startPointer;

     ssi->buffersInQueue--; };


void

     SsiDeviceQueue::queue( SsiBuffer* request ) {


     // Add to end of buffer queue

     request->nextSsiBuffer  = NULL;

     SsiBuffer** crPtrPtr     = &startPointer;


     ssi->disableSsiInterrupt();

          while ( *crPtrPtr ) // end pointer will be NULL

               crPtrPtr    = &(*crPtrPtr)->nextSsiBuffer;

          *crPtrPtr   = request;


          if ( ssi->buffersInQueue++ == 0 )

               ssi->startSpiTransfer();

     ssi->enableSsiInterrupt(); };