# Sept 2004 Dave Tetarenko
# Opens a ethernet socket on the system IP address to the Sensor7 Windown Box
# The Windows box must probe this machine (discovery) to get the string
# Port Number is 2054
# The host address is probably 192.168.0.0  This is set outside this program with Linux
# network config.
# The client Address is probably 192.168.0.1  This is set on the windows box
# Sends the same data that is on the serial port + the data fromthe DVL
#

set dvl_data "Waiting for DVL Connection"
set dvl_data2 "Waiting for DVL Connection"
set sensor7_socket(main) ""
set teleos_ethernet_timer_tx 0
set teleos_ethernet_timer_rx 0
set teleos_ethernet_status 0
set teleos_ethernet_freq_tx 0
set teleos_ethernet_freq_rx 0

proc sensor7_ethernet { port } {

	puts "sensor7_ethernet.tcl : Try the server $port"
	global sensor7_socket
	
	#When we open a new file we can't redo the socket on the same address.
	#sensor7_socket(main) will be null the first go around then will have "sock8"
	#because "sock8" means something to someone I guess
	if { $sensor7_socket(main) == "" } {
	        set sensor7_socket(main) [socket -server config_sensor7_ethernet $port]
		}	
}	

proc config_sensor7_ethernet {sock addr port} {
		
	global sensor7_socket	
	global teleos_ethernet_status
	
	puts "Accept $sock from $addr port $port"
	set teleos_ethernet_status 1
	set sensor7_socket(addr,$sock) [list $addr $port]
	fconfigure $sock -buffering line 
	fileevent $sock readable [list update_sensor7_ethernet $sock]
        ethernet_timer
}

proc update_sensor7_ethernet {sock} {

	global tx_vision_string 
	global sensor7_socket(addr)
	global dvl_data dvl_data2
	global teleos_ethernet_timer_rx teleos_ethernet_timer_tx
	global teleos_ethernet_status
	
	set rx_vision_string ""
	
        if {[eof $sock]} {
        	#end of file or abnormal connection drop
        	close $sock
        	puts "Close and terminate $sock"
		set teleos_ethernet_status 0	
        	return
        } 

	set tx_teleos [get_teleos_tx_ethernet ]
    	set dvl_data [get_dvl_data 1]
    	set dvl_data2 [get_dvl_data 2]
		
	gets $sock rx_vision_string
		
	if { $rx_vision_string == "*" } {
		incr teleos_ethernet_timer_tx
		append tx_vision_string "$tx_teleos"
			#$dvl_data"
		puts $sock $tx_vision_string
		set tx_vision_string ""
	} else {
		incr teleos_ethernet_timer_rx
		put_teleos_ethernet_to_telemetry $rx_vision_string
	}
		
}	

proc ethernet_timer {} {
 	global teleos_ethernet_timer_rx teleos_ethernet_timer_tx
 	global teleos_ethernet_status
 	global teleos_ethernet_freq_tx teleos_ethernet_freq_rx
 	 	
 	set teleos_ethernet_freq_tx $teleos_ethernet_timer_tx
 	set teleos_ethernet_freq_rx $teleos_ethernet_timer_rx
 	
 	set teleos_ethernet_timer_tx 0
 	set teleos_ethernet_timer_rx 0
 	if { $teleos_ethernet_status == 0 } return
 	after 1000 [list ethernet_timer]
 	
 }