'
' This script periodically reads data from a Midon Tempo 8 device
'


' This function waits for a line from the given filenumber or times out
' parameters: timeout [in] - the timeout in msecs
'             fileno [in] - the input filenumber
'             result [out] - return status: 1 if we got a line, 0 if we timed out
' Return value is the received line.
' Note that a received line may be incomplete if we timed out.
' A line is terminated with CR (which is removed from the returned string)
' LF characters are ignored and discarded.

function waitforline(timeout, fileno, result)
local ch, n, myline

result = 1
myline = ""

while waitevents(timeout) = fileno
	ch = input(1,fileno)
	if asc(ch) <> 10 then
		if asc(ch) = 13 then
			waitforline = myline
			exit sub
		endif
		myline = myline & ch
	endif
wend
' timed out
result = 0
waitforline = myline

end function

split command by " " to asyport, destip, destport
if isundef(asyport) or isundef(destip) or isundef(destport) then
	print "\r\nUsage: midonio.bas asyport destip destport\r\n"
	print "Where: asyport  is the serial port, eg asy0\r\n"
	print "       destip   is the destination host address\r\n"
	print "       destport is the destination port number\r\n"
	exit sub
endif


on error goto errorlabel

open asyport for input as 1
open asyport for output as 2
print "successfully opened serial port\n"

open destip & ":" & destport for socket as 3

' clears the event list
dummy = setevent(0)
' we want to check for received data on descriptor 1 (i.e. serial input)
dummy = setevent(1)

print #2, "tmp"
print "Sent tmp\n"

myloop:
	a = waitforline(15000, 1, res)

'
' check for a timeout
'
	if res = 0 then

		' check for just ">" response
		if a = ">" then
			print "got midon prompt\n"
			goto loopnext
		endif

		print "timed out\n"
		goto loopnext

	endif

	timestamp = FormatDate("0H:0m:0s 0D MON YEAR ",GmTime()) & "\r\n"
	if a like "Voltage ~###*=*" then
		datastring = "voltage reading from sensor " & joker(1) & joker(2) & ", value: " & joker(4) & "\r\n"
		print datastring
		print #3, timestamp
		print #3, datastring
	elseif a like "Temp ~###*=*" then
		datastring = "temperature reading from sensor " & joker(1) & joker(2) & ", value: " & joker(4) & "\r\n"
		print datastring
		print #3, timestamp
		print #3, datastring
	else
		print "GOT ", a, "\n"
	endif
	if eof(3) then
		print "socket was closed .. attempting to reopen it\n"
		close 3
		open destip & ":" & destport for socket as 3
	endif
	goto myloop

loopnext:
	sleep(10)
	print #2, "tmp"
	print "Sent tmp\n"
goto myloop

finished:
close 1
close 2
print "Finished\n"
stop

errorlabel:
print "encountered an error opening the port\n"
print error$, "\n"
