//	M530 : |[gԂ̉iƁAeLXg^oCȋM

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

function main()
{
	//	ubNm
	bno_tx = _MemAlloc(1024);
	bno_rx = _MemAlloc(1024);

	//	{^\
	_BtnOpen(0, "|[gݒ");		_BtnEnable(0, _TRUE );
	_BtnOpen(1, "|[gN[Y");	_BtnEnable(1, _FALSE);
	_BtnOpen(2, "eLXgM");	_BtnEnable(2, _FALSE);
	_BtnOpen(3, "oCiM");	_BtnEnable(3, _FALSE);
	_BtnOpen(4, "I@");			_BtnEnable(4, _TRUE );

	_Cls();

	//	|[gԍCI[vԓǂݏo
	port	= _GetProfileVal("PORT"   , 0	  );
	fOpened = _GetProfileVal("fOpened", _FALSE);

	//	VA|[g̉i
	if (port != 0) {
		_ComCreate(port);
		if (fOpened) OpenPort();
	}

	_Stop();

	//	|[gԍCI[vԋL^
	_SetProfileVal("PORT"	, port	 );
	_SetProfileVal("fOpened", fOpened);

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

//	{^ECxg
function _OnButton(BtnNo)
{
	define	bytes;

	if		(BtnNo == 0) {				//	u|[gݒv{^
		if (port = _ComCreateByDialog(port)) {
			_ComSetOnRxText  (port, "OnRxText");
			_ComSetOnRxPacket(port, "OnRxPacket", bno_rx);
			OpenPort();
		}
	}
	else if (BtnNo == 1) {				//	u|[gN[Yv{^
		_ComClose(port);
		fOpened = _FALSE;
		_BtnEnable(1, _FALSE); _BtnEnable(2, _FALSE); _BtnEnable(3, _FALSE);
	}
	else if (BtnNo == 2) {				//	ueLXgMv{^
		//	eLXg̓͂ƑM
		if ($InpTxt = $_Input("MeLXg͂Ă", $InpTxt)) {
			_ComSendText(port, $_StrCat($InpTxt, "\n"));
		}
	}
	else if (BtnNo == 3) {				//	uoCiMv{^
		//	oCif[^̓͂ƁAߌ^pPbgM
		$InpTxt = $_Input("MoCif[^i16i2j󔒂ŋ؂ē͂Ă");
		if ($InpTxt != "") {									// ͂H
			if (bytes = _HexStrToBinary($InpTxt, bno_tx, 0)) {	//	 16i񁨃oCiϊ
				_ComSendPacket(port, bno_tx, 0, bytes);			//	 oCipPbgf[^M
			}
		}
	}
	else if (BtnNo == 4) _Restart();	//	uIv{^
}

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

//	pPbgMCxg
function  OnRxPacket(len)
{
	_DumpMemBlk(bno_rx, 0, len);
}

//	VA|[g̃I[v
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);}
}
