/*
	SIOAECHO.C

	This program demonstrates how to use SIO port A for echoing characters
	input from a remote device running at 9600 bps.

	Character-wise or block-wise transfer is performed according to the value
	of the "BLOCK" macro.

	RTS/CTS hardware flow control is performed according to the value of the
	"RTS_CTS" macro.

	Break processing is illustrated with the use of the assembly function
	"sioA_Break" that increments the number of breaks encountered.

	A different bit rate can be used by changing the multiplier of the
	"SIO_1200" parameter in the "aascOpen()" function.
*/

#use aasc.lib
#use aascsioa.lib

// Macro definitions

#define BLOCKWISE 0		// Set to 0 for characterwise transfer, 1 for blockwise transfer.
#define BLKSIZE 10		// Set to the number of bytes in a block.

#define RTS_CTS 0			// Set to 1 for RTS/CTS hardware flow control, 0 otherwise

#define BUFRSIZE 2048	// Number of bytes in each circular buffer.

// Buffer definitions

char RxCircBuf[BUFRSIZE], TxCircBuf[BUFRSIZE], localBuf[BUFRSIZE], localChar;

// Break processing variables and function

int breakCounter, _breakCounter;

#asm
sioA_Break::

	push	hl						; Save what is changed

	ld		hl,(breakCounter)
	inc	hl
	ld		(breakCounter),hl

	pop	hl						; Restore what is changed

	ret

#endasm

main()
{
unsigned count, remaining;
long sioaErr;
struct _Channel *sioaChannel;

	// Initializations

	_GLOBAL_INIT();

	sioaChannel = aascOpen( DEV_SIOA, RTS_CTS, SIO_8N1 + SIO_1200*8, sioA_Break);

	aascSetReadBuf( sioaChannel, RxCircBuf, BUFRSIZE);
	aascSetWriteBuf( sioaChannel, TxCircBuf, BUFRSIZE);

	breakCounter = 0;
	_breakCounter = breakCounter;

	// Process characters input from a remote device

	while( 1) {

		hitwd();

		// Process any errors encountered
		
		if( sioaErr = aascGetError( sioaChannel) ) {

			printf(" %d", sioaErr);
			aascClearError( sioaChannel);
		}

		// Display the number of breaks received
		
		if( breakCounter != _breakCounter ) {

			printf("\nBreaks: %2d ", breakCounter);
			_breakCounter = breakCounter;
		}

		// Write any received characters back to the port

		if( BLOCKWISE ) { 

			if( aascReadBlk( sioaChannel, localBuf, BLKSIZE, 1) ) {

				while( !aascWriteBlk( sioaChannel, localBuf, BLKSIZE, 1) ) hitwd();
			}
		}
		else {

			if( aascReadChar( sioaChannel, &localChar) ) {

				while( !aascWriteChar( sioaChannel, localChar) );
			}
		}
	}
}