FETCH_DATA_COMMAND = 0x80
PRINT_DATA_COMMAND = 0x81
PRINT_DATA_LCD = 0x82

srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
    conn:on("receive", function(client,request)
        local str = "";
        local buf = "";
        local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP");
        if(method == nil)then
            _, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP");
        end
        local _GET = {}
        if (vars ~= nil)then
            --for k, v in string.gmatch(vars, "(%w+)=(%w%s*)+&*") do
            for k, v in string.gmatch(vars, "(%w*%s*)=([^&=]+)&*") do 
                _GET[k] = v
            end
        end
        buf = "<html><head><title>Arduino Message Center</title></head></body>"
        buf = buf.."<h1>Arduino Home Message Center</h1>";
        buf = buf.."<p>GPIO0 <a href=\"?pin=ON1\"><button>ON</button></a>&nbsp;<a href=\"?pin=OFF1\"><button>OFF</button></a></p>";
        buf = buf.."<p>GPIO2 <a href=\"?pin=ON2\"><button>ON</button></a>&nbsp;<a href=\"?pin=OFF2\"><button>OFF</button></a></p>";
        --buf = buf.."<p>Message <a href=\"?pin=TXT\"><input type=\"text\" name=\"text\"></p>";
        buf = buf.."<form>"
        buf = buf.."<p>Message<input type=\"text\" name=\"text\"></p>";
        buf = buf.."<input type=\"submit\" value=\"Submit\">"
        buf = buf.."</form>"
        buf = buf.."</html></body>"
        if pcall(function () x=tonumber(_GET.x)
                    y=tonumber(_GET.y)
                    end)then
          if (_GET.x~=nil and _GET.y~=nil)then
            uart.write(0,FETCH_DATA_COMMAND)
            uart.write(0,bit.arshift(bit.band(x,0xff00),8), bit.band(x,0x00ff))
            uart.write(0,bit.arshift(bit.band(y,0xff00),8), bit.band(y,0x00ff))
            uart.write(0,PRINT_DATA_COMMAND)
          end
        end
        if pcall(function () string_print = _GET.text 
                        string_print = string.gsub(string_print, "+", " ")
                  end) then
              uart.write(0,PRINT_DATA_LCD)
              uart.write(0,string_print)
              uart.write(0,PRINT_DATA_LCD)
        end
        if(_GET.pin == "ON1")then
              --gpio.write(led1, gpio.HIGH);
              uart.write(0,"1")
        elseif(_GET.pin == "OFF1")then
              --gpio.write(led1, gpio.LOW);
              uart.write(0,"2")
        elseif(_GET.pin == "ON2")then
              --gpio.write(led2, gpio.HIGH);
              uart.write(0,PRINT_DATA_LCD)
              uart.write(0,"Hello World! ") 
              uart.write(0,PRINT_DATA_LCD)
        elseif(_GET.pin == "OFF2")then
                --gpio.write(led2, gpio.LOW);
                uart.write(0,PRINT_DATA_LCD)
                uart.write(0,"Bye World! ")
                uart.write(0,PRINT_DATA_LCD)
        end
        client:send(buf);
        client:close();
        collectgarbage();
    end)
end)