//
//  StreamReader.h
//  VisibleArmory
//
//  Created by jcassidy on 10-05-15.
//  Copyright 2010 Visible Assets Inc.. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <ExternalAccessory/ExternalAccessory.h>
#import "Timer.h"
#import "RingBuffer.h"
#import "ChannelData.h"

#define DEFAULT_TIMEOUT				5

#define ACCESSORY_CHANNEL			0
#define SCANNER_CHANNEL			1
#define TRANSCEIVER_CHANNEL		2
#define READER_CHANNEL				3
#define ETHERNET_CHANNEL			4

#define SCAN_SCAN					0
#define SCAN_START					1
#define SCAN_READ					2

#define ACMD_PING						0
#define ACMD_VER						1
#define ACMD_LISTEN					2
#define ACMD_SCANNER_INIT			3
#define ACMD_ETHERNET_INIT			4
#define ACMD_CARDREADER_INIT		5

#define ARSP_NAK						0
#define ARSP_ACK						1

#define bufferToInt(ptr)					( ( (unsigned int) ptr[0] ) << 8 ) + ( (unsigned int) ptr[1] )

@interface StreamReader : NSThread {
	RingBuffer			*rxRingBuffer;
	RingBuffer			*txRingBuffer;
	EAAccessory		*accessory;
	EASession			*session;
	NSInputStream		*inputStream;
	NSOutputStream	*outputStream;
	BOOL				isRunning;
	BOOL				blockMode;
	BOOL				inputStreamOpen;
	BOOL				outputStreamOpen;
	BOOL				availableFlag;
}

- init:(int) size;										// set inital state
- (void) dealloc;

// open/close connection member functions
- (BOOL) open:(NSString *) initString;				// open client socket
- (BOOL) close;										// close client socket

// instance var access functions
- (void) setBlockMode:(int) mode;					// set blocking mode, TRUE = block

// data I/O 
- (int) writeChannel:(int) channel data:(char*) data length:(int) length;
//- (NSString *) readChannel:(int) channel data:(char *) data length:(int) maxLength;
- (NSString *) readChannel:(int) channel data:(char *) data length:(int) maxLength timeout:(float) timeout eolChar:(char) eol;
- (int)	bufferLevel;																			// return bytes in rx buffer
- (void) stream:(NSStream *) stream handleEvent:(NSStreamEvent) streamEvent;

//- (NSString *) readString;							// return autoreleased nsstring

// misc
- (int) setBufferSize:( int ) size;						// set rx buffer size in Kbytes
- (void) initializeInstanceVars;
- (BOOL) ping;
- (int) firmwareVersion;
- (BOOL) isConnected;
- (BOOL) scannerInit;
- (BOOL) ethernetInit:(int) baud;
- (void) intToBuffer:(char *) buffer value:(int) i;
- (void) clear;
- (void) writeChan:(ChannelData *) data;
- (void) readChan:(ChannelData *) data;
- (void) stop;
- (void) triggerScanner;
- (NSString *) readScanner;
- (BOOL) cardReaderInit:(int) baud;

@end
