#!/usr/bin/tclsh
#
# a simple reciever test
#

package require udp 1.0

source oscUnpack.tcl
# Provides: proc unpackOSCpath oscBinStr => multilevel list
# Provides: proc handleEvent oscBinStr

source osctime.tcl
set ::osctime::debug 0
#
# This takes too long....
#
::osctime::setup


##########################################################################
#
# UDP setup and utility proc for fileevent
#

source musys.conf.tcl

# Select a subnet and the port number.
set subnet $cast(myapp)
set myport   $port(OSCEAIgw)
set outgoing $port(myapp)

# Create a listening socket and configure for sending too.
set udpSock [udp_open $myport]
fconfigure $udpSock -buffering none -blocking 0 -translation binary
fconfigure $udpSock -broadcast 1 -remote [list $subnet $outgoing]
fileevent  $udpSock readable [list oscMsgEvent $udpSock]

proc oscMsgEvent {chan} {
	set debug 1

	set oscMsg [read $chan]
	set peer [fconfigure $chan -peer]
	#
	# Hmm.. we do not always seem to get the data in one read.
	# 4K boundaries in read buffer ?
	#
	set gotMore 1
	while {$gotMore > 0} {
		after 1
		set moreData [read $chan]
		set gotMore [string length $moreData]
		if {$gotMore > 0} {
			puts "oscMsgEvent Drips and drabs: add $gotMore bytes to [string length $oscMsg] bytes"
			append oscMsg $moreData
		}
	}
	if {$debug == 1} {
		puts "$peer sent [string length $oscMsg] bytes"
	}
	if {[string length $oscMsg] > 0} {
		# We are rnning in callback mode
		oscUnpack::handleEvent $oscMsg
	}
	return
}

##########################################################################
#
# oscUnpack configuration
#

# Would you like dummy values for True, False, Nil and Infinity ?
# If so, fill in the list of what you would like back...
#
set ::oscUnpack::wantSymbols [list {<T>} {<F>} {<N>} {<I>}]
	# else
	#set ::oscUnpack::wantSymbols {}

# Would you like keep the midi packed into a 32bit word?
# If you rather have it unpacked into 4 bytes, please
# remember that there will be a discrepancy
# between the count of the types, and the count of the values
set ::oscUnpack::wantPackedMidi 0

# During unpacking:
# Would you like the blob returned as hex ?
set ::oscUnpack::wantHexBlob 1

##########################################################################
#
# Sample callback routine
#
set ::oscUnpack::callback handleOSCmsg

proc handleOSCmsg {path types valueList} {
	puts stdout [format "handleOSCmsg (%s) path=%s , types={%s} , values=\[%s\]" [clock format [clock seconds]] $path $types $valueList]
}

puts stdout "Ready..."

set forever 0
vwait ::forever
