InqPortal – JavaScript Library Reference v5

The InqPortal library is added to a web page by adding it to your html file with a line like: <script src=”inqportal.js”></script>. Some people prefer to add this to the <head> section while other tend to add it toward the end of the html file. Either works fine.

Although it is possible to embed JavaScript in the html file and/or use JavaScript methods directly from the html file, it is often preferred to add a JavaScript file to the project and pull it in with the reference. This is simply a matter of preference, but it does separate concerns. In larger software companies, the HTML page and CSS files tend to be handled by designers and graphic artists while the JavaScript files are handled by a developers.

Callback Methods

The library has three optional callback methods. Here they are and why you might want to take advantage of them.

onConnected(ws)

When you include the InqPortal library above, it will automatically start up a Web Socket communications path with your ESP8266 server. Once it has successfully connected, this method is called to notify your custom, client-side JavaScript. You can think of it being similar in nature to the void setup() in Arduino Sketch. Typically, you would do any one-time setup to configure the rest of your html page.

Parameter

ws = (optional parameter)

// Example

onConnected = function(ws)
{
   configureMyChart(); 
};

onModifyResult(webID, value, ws)

The default behavior of data being sent implicitly from the server using publishRO() publishRW() or explicitly using send(), sendAll(), sendChanged() is to look for an element id with the same name as the webID (The first letter of webID must be capitalized). If it finds an ID, it simply places the value in the HTML for you. No intervention is required. However, there are some reasons you might want to intercept that action. onModifyResult lets you inspect each value and/or modify something else. If no intervention is required, you simply return the value. If you just want to modify the value, you can do that and return the modified version. You might want to modify something more extensive… like add a row in a table and set one cell to the webID and another to the value. You can still return some value that will continue to look for an HTML element with the id. onModifyResult is very flexible.

Parameters

webID – This is always a string of the webID name as defined in server methods publishRO and publishRW or the labels as defined in send, sendAll and sendChanged.

value – This could be a string, integer or float. Typically you don’t need to know if you’re just displaying it, but if you do, you are the one that defined and sent it from the server or… you can check and make sure it is of the type you expect.

ws = (optional parameter)

// Example

onModifyResult = function(webID, value)
{
    switch(webID)
    {
        case "T":
            // webID = "T" for a temperature sent from the server for a 
            // sensor in °C.  Somewhere on the html page, there is an 
            // element id = "T" and another with and element id = "Tf".
            // Set Tf element's text to a converted temp in °F.
            $('Tf').innerText = (value * 9 / 5 + 32).toFixed(1) + "°F";
        
            // Append the units on the original and return it and let
            // library assign it to the id='T' element.
            value = value.toFixed(1) + "°C";
            break;
    
        case "V":
            // webID = "V" is the version number of your app.
            // We just want to prefix some verbiage.
            value = "InqWeather v" + value;
            break;

        default:
            // All other values being sent just pass through and return to
            // to be populated by the default behavior.
            break;
    }
    return value;
};

onBinary(data, ws) (Currently disabled in Version 5… will be returning soon)

This is the receiver callback when the server sends some binary data using the sendBinary() method. Binary data transfer is extremely fast mainly because there are no translations, parsing or interpreting of the JSON data that flows for all other transactions. It is also far more compact. A float on binary is 4 bytes. The JSON representation of that can be quite a bit larger (“Pi”:3.141592,) takes 14 bytes. A longer name and it gets bigger. The data parameter is simply an array of bytes and its structure is totally up to you to configure and support on both sides. Just remember GIGO!

Parameter

data = Array of bytes.

Example: TBD – Will make a full Examples project to be installed with the library.

ws = (optional parameter)

get(array)

This requests one or more values of variables on the server. Its one parameter uses JavaScript array notation to send a list of strings. On the server-side you will need to implement a publishRO() or publishRW() method for each variable you want to “get”. get() is rarely needed because of the publish subsystem will automatically request them onConnect() of the client page, but it can be used anywhere in your HTML or JavaScript code.

Parameter

array (optional) – Array of variable names to request (strings). If not supplied, the server will reply with all published variables.

<!-- Example 1 - Somewhere on your html page, when clicked... --> 
<div onclick="get(['MyStatus', 'MyCount', 'MyDay']);">Get My Status</div>

// Example 2 - Somewhere in your own custom javascript
function onClickRefresh()
{
  // Normally you do not need to do this.  The server will either 
  // periodically update values base on server-side autoSend() 
  // settings or by explicit calls using server-side send, sendAll, sendChanged
  get();
};

set(<several versions>)

The set() function is used to set your published variable on the server. There are multiple user-friendly versions of set() that can be used to ease your client-side development burden. Under the covers, it builds up a list of param/value pairs as a single JavaScript object with one or more properties. It is then sent to the server and processed by publish subsystem. You can only set variables on the server that have been setup using the publishRO() and publishRW() methods.

  • set(); (no parameter) – This is the simplest, yet the most comprehensive and is the only one we discuss in the Tutorial and Quick Start Guide. When called this looks for all INPUT elements and uses their ID as the param name and… well… the value is sent as the value. There are very few reasons to use the other versions except to reduce processing time and WiFi bandwidth. They only restrict the amount of values sent.
  • set(string); – Even the string version can achieve several things.
    • If the string is the ID of an INPUT element, its id/value pair will be sent. ie set(“MyInput”);
    • If the string is a class name as designated by a dot prefix ie. set(“.myClass”); all INPUT elements using that class will be sent.
    • If the string is an ID of a <div> or a <table>, all child INPUT elements within are sent. ie. set(“myPropertyTable”);
  • set([array]); – You can supply an array of strings that will combine the results as if multiple set(string); versions were called. ie. set([“MyInput”, “.myClass”, “myPropertyTable”]);
  • set(obj); – Sends a standard JavaScript object. Please use see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects for some good examples of creating a JS object using several techniques. ie. set({“Temp1” : 42.0, “Room” : “Garage”, “Factor” : 1.8, “Offset” : 32});

The ws parameter (Advanced Usage)

If your client Html page only talks to its own server, then this parameter can be ignored and even omitted in the parameter lists above. Starting in version 3, it is possible to connect your page to other InqPortal servers. In other words… one web page can watch/manage multiple InqPortal servers. They do not even have to be of the same Sketch project. The default server (this is the one that the page is being pulled) is define by the global methods described above. It is now possible to create another connection by simply creating a new instance of WS. Once this connects, it will call your same onConnected(), onModifyResult() and onBinary() methods. The ws parameter will identify which server is sending you something. It is up to you to query it and make sure which one you’re getting info from to determine what you need to do with it. If you want to use get(), and set() methods with one of these secondary servers, you must use its WS object that was returned to you during creation or when the value comes down in the onConnected(), onModifyResult() or onBinary() callback methods… your choice.

// This example has not been updated for Version 5 yet.  TBD
// The following Example has a table element on its 
// HTML page with id='tl' and one row with headers.

// our server, as well as all other servers we connect to 
// come through this.  We ask them all to send us their 
// version number.  
// Note - we aren't using the global version.  

onConnected = function(ws)
{ 
    // ws will be null for the primary and defined for 
    // all others.
    findRow(ws);

    ws.get(['V']);    // Request this server's version number.

    if (!ws)   
    {
        // When we first get connected, ws will = _ws.
        // We create connections to other servers
        // that we know are on our network.
        new WS('InqSR-1');
        new WS('InqSR-2');
        new WS('InqSR-3');
        new WS('InqSR-4');
    }
};
// Again all servers come through this function and we
// identify them by their ws varible.
onModifyResult = function(p, v, ws)
{
    var row = findRow(ws);

    if (p == 'V')
    {
        // We now add the version on the table row
        // that was created earlier.
        row.cells[1] = v;
        // We put the version number of our server (_ws)
        // in a visible header with the id='V'.  But
        // we don't want to put the other servers version
        // number in it, so we return null for those.
        if (ws != _ws)
            return null;
    }
    return v;
}

function findRow(ws)
{

    // Finds table row based on the received 
    // WS class object or creates new row
    var tl = $('tl');   
    if (!tl)        // Table is not defined.
        return null;

    var n = ws.url.substring(5);
    n = n.substring(0, n.length - 4);
    // 1st row is the header row
    for(var i=1; i<tl.rows.length; i++)
    {
        if (tl.rows[i].ws === ws)
            return tl.rows[i];
    }
    var r = tl.insertRow();
    r.ws = ws;
    // Put the name of the server in the first column.   

    r.insertCell(0).innerHTML = n;
    // Make an empty column to hold the version number
    // we get when we get the callback to onModifyResult().
    r.insertCell(1);
    return r;
};