//	M530 : Port state persistence, text / binary transmission and reception

define	bno_tx	= 0;
define	bno_rx	= 0;
define	port 	= 0;
define	fOpened = _FALSE;
define	$InpTxt = "";

function main()
{
	//	Memory block allocation
	bno_tx = _MemAlloc(1024);
	bno_rx = _MemAlloc(1024);

	//	Button display
	_BtnOpen(0, "PortSetting");	_BtnEnable(0, _TRUE );
	_BtnOpen(1, "PortClose");	_BtnEnable(1, _FALSE);
	_BtnOpen(2, "SendText");	_BtnEnable(2, _FALSE);
	_BtnOpen(3, "SendBinary");	_BtnEnable(3, _FALSE);
	_BtnOpen(4, "End");			_BtnEnable(4, _TRUE );

	_Cls();

	//	Port number, open status read
	port	= _GetProfileVal("PORT"   , 0	  );
	fOpened = _GetProfileVal("fOpened", _FALSE);

	//	Persisting the serial port
	if (port != 0) {
		_ComCreate(port);
		if (fOpened) OpenPort();
	}

	_Stop();

	//	Port number, open state record
	_SetProfileVal("PORT"	, port	 );
	_SetProfileVal("fOpened", fOpened);

	/*	Resource destruction			*/
	_BtnClose(0); _BtnClose(1); _BtnClose(2);  _BtnClose(3);
	if (port != 0) {_ComClose(port); _ComDelete(port);}
	_MemFree(bno_tx);
	_MemFree(bno_rx);
}

//	Button event processing
function _OnButton(BtnNo)
{
	define	bytes;

	if		(BtnNo == 0) {				//	- "Port setting" button pressed?
		if (port = _ComCreateByDialog(port)) {
			_ComSetOnRxText  (port, "OnRxText");
			_ComSetOnRxPacket(port, "OnRxPacket", bno_rx);
			OpenPort();
		}
	}
	else if (BtnNo == 1) {				//	- "Port close" button pressed?
		_ComClose(port);
		fOpened = _FALSE;
		_BtnEnable(1, _FALSE); _BtnEnable(2, _FALSE); _BtnEnable(3, _FALSE);
	}
	else if (BtnNo == 2) {				//	- "Text transmission" button pressed?
		//	Enter and send text
		if ($InpTxt = $_Input("Please enter the text to send", $InpTxt)) {
			_ComSendText(port, $_StrCat($InpTxt, "\n"));
		}
	}
	else if (BtnNo == 3) {				//	- "Binary transmission" button pressed?
		//	Binary data input and transparent packet transmission
		$InpTxt = $_Input("Please enter the binary data (2 hexadecimal digits) to send, separated by blanks");
		if ($InpTxt != "") {									// With character string input?
			if (bytes = _HexStrToBinary($InpTxt, bno_tx, 0)) {	//	 Hexadecimal character string  binary conversion
				_ComSendPacket(port, bno_tx, 0, bytes);			//	 Binary packet data transmission
			}
		}
	}
	else if (BtnNo == 4) _Restart();	//	- "End" button pressed?
}

//	Text reception event processing
function  OnRxText($Text)
{
	_PrintF("%s", $Text);
	_PrintF("\n");
}

//	Packet reception event processing
function  OnRxPacket(len)
{
	_DumpMemBlk(bno_rx, 0, len);
}

//	Open serial port
function  OpenPort()
{
	if (!_ComIsOpened(port) && _ComIsOpenPossible(port)) {
		_ComOpen(port);
		fOpened = _TRUE;
	}
	if (fOpened) {_BtnEnable(1, _TRUE ); _BtnEnable(2, _TRUE ); _BtnEnable(3, _TRUE );}
	else		 {_BtnEnable(1, _FALSE); _BtnEnable(2, _FALSE); _BtnEnable(3, _FALSE);}
}
