#!/usr/bin/lua
local f = io.open("/dev/ttyACM0", "r+")
f:write("quiet\n")

function sread ()
  while true do
    local ret = f:read("*line")
    if( ret ~= "" ) then return ret end
  end
end

if os.getenv("QUERY_STRING") ~= "" then
  f:write(os.getenv("QUERY_STRING").."\n")
--  f:read("*line")
--  sread()
end

print("Content-type: text/html\nRefresh: 10\n\n")
print("<HTML><HEAD><TITLE>Teensy Monitoring and Control</TITLE>")
print("</HEAD><BODY>")
for i = 0,11 do
  f:write("A"..i.."?\n")
  print("A"..i.."="..sread().."V<BR>")
end
for i = 0,13 do
  f:write("D"..i.."?\n")
  local state = sread()
  f:write("M"..i.."?\n")
  local direction = sread()
  print("D"..i.."="..state.." ("..direction..")");
  if direction == "input" then
    print(" &nbsp; <A HREF=\"?IPU"..i.."\">pull-up on</A> &nbsp; <A HREF=\"?D"..i.."=0\">go active low</A> &nbsp; <A HREF=\"?D"..i.."=1\">go active high</A>")
  elseif direction == "input with pull-up" then
    print(" &nbsp; <A HREF=\"?I"..i.."\">pull-up off</A> &nbsp; <A HREF=\"?D"..i.."=0\">go active low</A> &nbsp; <A HREF=\"?D"..i.."=1\">go active high</A>")
  elseif state == "0" then
    print(" &nbsp; <A HREF=\"?I"..i.."\">make input without pull-up</A> &nbsp; <A HREF=\"?IPU"..i.."\">make input with pull-up</A> &nbsp; <A HREF=\"?D"..i.."=1\">go active high</A>")
  else
    print(" &nbsp; <A HREF=\"?I"..i.."\">make input without pull-up</A> &nbsp; <A HREF=\"?IPU"..i.."\">make input with pull-up</A> &nbsp; <A HREF=\"?D"..i.."=0\">go active low</A>")
  end
  print("<BR>")
end

print("<BR><A HREF=\"?\">refresh</A><BR>")
print("</BODY></HTML>")
