var serial = {
    xhr: new XMLHttpRequest(),
    port: null,
    response: "",
    timeout: 1000,
    host: "http://localhost:8886",
    open: function (port, baudrate) {
        var url = this.host + "/serial/open?port=" + port + "&baudrate=" + baudrate + "&timeout=" + this.timeout;
        this.xhr.open("GET", url, false);
        this.xhr.send();
        if (this.xhr.status != 200) {
            this.port = null;
            return false;
        } else {
            this.port = port;
            return true;
        }
    },
    close: function() {
        port = null;
        this.xhr.open("GET", this.host + "/serial/close", false);
        this.xhr.send();
    },
    write: function(str, eos)
    {
        var url = this.host + "/serial/write?timeout=" + this.timeout;
        if (eos) {
            url += "&eos=" + eos;
        }
        this.xhr.open("POST", url, false);
        this.xhr.send(str);
        this.response = this.xhr.responseText;
        return this.xhr.status == 200;
    },
    read: function(eos)
    {
        var url = this.host + "/serial/read?timeout=" + this.timeout;
        if (eos) url += "&eos=" + eos;
        this.xhr.open("GET", url, false);
        this.xhr.send();
        this.response = this.xhr.responseText;
        return this.xhr.status == 200;
    },
    list: function()
    {
        var url = this.host + "/serial";
        this.xhr.open("GET", url, false);
        this.xhr.send();
        if (this.xhr.status == 200) {
            return JSON.parse(this.xhr.responseText).ports;
        } else {
            return null;
        }
    }
};
