#!/usr/bin/wish
#
#

global line
global argv
set line ""
set VERSION ""

proc Serial_Init {ComPort ComRate} {
	set iChannel [open $ComPort w+]
	set rate $ComRate
	fconfigure $iChannel -mode $ComRate,n,8,1
	fconfigure $iChannel -blocking 0
	fconfigure $iChannel -buffering none
	fileevent $iChannel readable ""
	return $iChannel
}

proc send_cmd2 {CMD} {
	global Serial
	foreach CHAR [split "$CMD" ""] {
#		puts -nonewline "$CHAR"
		puts -nonewline $Serial "$CHAR"
		after 100
	}
}

proc rd_chid {chid} {
	global line
	global VERSION
	global SYSINFO
	set msg [read $chid 1]
	if {$msg == "\n"} {
		puts "$line"

		set line ""
	} else {
		set line "$line$msg"
	}
}


#wm geometry . 320x250
wm title . "BTM222-Tool"

frame .frame3
pack .frame3 -side top -fill x -expand yes

	button .frame3.master -text "Master" -command {
		send_cmd2 "ATR0\r"
	}
	pack .frame3.master -side top -fill x -expand yes

	button .frame3.slave -text "Slave" -command {
		send_cmd2 "ATR1\r"
	}
	pack .frame3.slave -side top -fill x -expand yes

	button .frame3.info -text "Info" -command {
		send_cmd2 "ATI1\r"
	}
	pack .frame3.info -side top -fill x -expand yes

	button .frame3.scan -text "Scan" -command {
		send_cmd2 "ATF?\r"
	}
	pack .frame3.scan -side top -fill x -expand yes

	button .frame3.hwaddr -text "MyHWADDR" -command {
		send_cmd2 "ATB?\r"
	}
	pack .frame3.hwaddr -side top -fill x -expand yes

	button .frame3.autoconnect -text "Auto-Connect On" -command {
		send_cmd2 "ATO0\r"
	}
	pack .frame3.autoconnect -side top -fill x -expand yes

	button .frame3.autoconnect_off -text "Auto-Connect Off" -command {
		send_cmd2 "ATO1\r"
	}
	pack .frame3.autoconnect_off -side top -fill x -expand yes



if {[lindex $argv 0] != ""} {
	puts "Open Serial-Port: [lindex $argv 0]"
	if {[lindex $argv 1] != ""} {
		set Serial [Serial_Init "[lindex $argv 0]" [lindex $argv 1]]
	} else {
		set Serial [Serial_Init "[lindex $argv 0]" 19200]
	}
} else {
	puts "USAGE: rx-tool COMPORT [BAUD]"
	exit 1
}
fileevent $Serial readable [list rd_chid $Serial]

send_cmd2 "ATI1\r"










