#!/usr/bin/env tclkit85

# Display multiplexed data from the MuxShield in separate window panes
# 2009-03-18 <jcw@equi4.com> http://opensource.org/licenses/mit-license.php

package require Tk

proc guiSetup {} {
  foreach i {1 2 3 4 5 6} {
    text .t$i -width 80 -height 25 -font {Courier 10} -wrap char \
              -highlightthickness 1 -highlightbackground lightgrey
  }
  grid .t1 .t2 .t3
  grid .t4 .t5 .t6
  grid rowconfigure . 0 -weight 1
  grid rowconfigure . 1 -weight 1
  grid columnconfigure . 0 -weight 1
  grid columnconfigure . 1 -weight 1
  grid columnconfigure . 2 -weight 1
}

proc gotkey {fd} {
  set c [read stdin 1]
  if {"\1" <= $c && $c <= "\5"} {
    set ::txchan [scan $c %c]
    wm title . "RX $::rxchan - TX $::txchan"
  }
  puts -nonewline $fd $c
}

proc gotser {fd} {
  set c [read $fd 1]
  # .t6 insert end $c
  # .t6 see end
  if {"\1" <= $c && $c <= "\5"} {
    set ::rxchan [scan $c %c]
    wm title . "RX $::rxchan - TX $::txchan"
  } else {
    if {($c < " " && $c != "\r" && $c != "\n") || $c > "~"} {
      set c <[format %02x [scan $c %c]]>
    }
    .t$::rxchan insert end $c
    .t$::rxchan see end
  }
}

guiSetup

set port /dev/tty.usbserial-A60061ef
set baud 57600

set fd [open $port {RDWR NONBLOCK}]
fconfigure $fd -mode $baud,n,8,1 -buffering none -translation binary
fconfigure stdin -blocking 0 -buffering none -translation binary
fconfigure stdout -buffering none

set rxchan 6
set txchan 6

fileevent stdin readable [list gotkey $fd]
fileevent $fd readable [list gotser $fd]

vwait done
