' IOM141_1.Bas (Liberty Basic)
'
' Illustrates an interface with either the IOM #141 or #142 to control the relays.
'
' Continually reads the PCs system clock and if the time is in the range of 9:15 to 9:20
' Relay 1 is operated.  It is released at all other times.
'
' 9600 baud.  Assumes COM2 
'
' copyright, Peter H. Anderson, Baltimore, MD, Mar, '05

    Com = 16384     ' size of buffer

    ' define a box
    nomainwin

    WindowWidth = 400
    WindowHeight = 300
    texteditor #window.te, 0, 0, 391, 254     'The handle for our texteditor is #window.te
    graphicbox #window.gb, 800, 1, 10, 10
    open "kb" for window as #window           'The handle for our window is #window
    print #window.gb, "when characterInput [getChar]"   'When the user presses a key go to [getChar]
    print #window, "trapclose [quit]"    'When the user closes our terminal window, go to [quit]
    print #window.te, "!autoresize";   'Tell the texteditor to resize with the terminal window
    print #window, "font courier_new 9";

[top]
    oncomerror [closecomm]  ' not sure if this works
    open "com2:9600,n,8,1, cs0, ds0" for random as #commhandle

    call pause 500  ' wait for unit to settle

    print #commhandle, "F0"    ' turn all relays off

    x = 0
    while x=0

       T$ = time$()
       Delimiter$ = ":"
       Hours = Val(ExtractField$(T$, Delimiter$, 1))
       Mins = Val(ExtractField$(T$, Delimiter$, 2))

       If (Hours = 9 AND Mins >= 15) AND (Mins < 20) then  ' 9:15 to 9:20
          print #commhandle, "N1"
       Else
          print #commhandle, "F1"
       End If
       call pause 10000 ' 10 sec
       print #window.te,  T$  ' just to see that it is working
    wend

function ExtractField$(Var$, Delimiter$, NumField)

    for Num = 1 to NumField
       Index = FindDelimiter(Var$, Delimiter$)
       LeftStr$ = Left$(Var$, Index - 1) ' everything to the left of the space
       Var$ = Mid$(Var$, Index+1)        ' to the right of the space
       If Num = NumField Then
          exit for
       End If
    next

    ExtractField$ = LeftStr$

end function

function FindDelimiter(Var$, Delimiter$)

    for n = 1 to len(Var$)
       ch$ = Mid$(Var$, n, 1)
       If ch$ = Delimiter$ then
          exit for
       End If
       If ch$ = Chr$(13) then
          exit for
       End If
       If ch$ = Chr$(10) then
          exit for
       End If
    next
    FindDelimiter = n

end function

sub pause mil
    tcurrent = time$("milliseconds")
    timeout = tcurrent + mil
    if timeout > 86400000 then  ' roll over at midnight
       timeout = timeout - 86400000
       do
           tcurrent = time$("milliseconds")
       loop until (86400000 - tcurrent) > 1000000
    end if

    do
       tcurrent = time$("milliseconds")
    loop until (tcurrent >= timeout)

    end sub

    end