Webifi.me

Javascript Tutorial

 

Index

1. HTML
2. Javascript
3. Test

1. HTML

The source code for this tutorial is available on GitHub at: https://github.com/webifi-me/WebifiJavascriptTutorial. This tutorial shows how to make a simple HTML page that can send and receive data. Create an empty HTML file called webifiJavascriptTutorial.html and open it with your favourite editor. Paste the code below into the editor:

<!DOCTYPE html>
<head>
    <title>Webifi Javascript Tutorial</title>
    <script type="text/javascript" src="https://www.webifi.me/js/jquery-1.10.2.min.js"></script>
    <script type="text/javascript" src="https://www.webifi.me/Webifi-min-1.0.js"></script>
    <script type="text/javascript">
        //user JavaScript

    </script>
    <style>
        .webifiSpacing {
            margin-bottom: 5px;
        }
    </style>
</head>
<body>
    <h1>Webifi Javascript Tutorial</h1>
    <div id="webifiControl"></div>
    <input type="checkbox" id="checkSaveConnectionDetails" />Save connection details<br /><br />
    Send data:<br />
    <input type="text" id="textSendData" value="test data" size="40" class="webifiSpacing" /><br />
    <button type="button" onclick="SendData()" id="buttonSendData">Send data</button>&nbsp;&nbsp;&nbsp;
    <button type="button" onclick="SendDiscovery()" id="buttonDiscovery">Discover</button><br /><br />
    Received data:<br />
    <textarea id="textAreaRecData" style="height: 100px; width: 500px;" rows="10"></textarea>
    <br /><button type="button" onclick="ClearRecData()" id="buttonClearRecData">Clear</button><br /><br />
    Messages:<br />
    <textarea id="textAreaMessages" style="height: 100px; width: 500px;" rows="10"></textarea>
    <br /><button type="button" onclick="ClearMessages()" id="buttonClearMessages">Clear</button>
</body>
</html>

This is all the HTML that will be needed to test the Javascript library. Inside the script tag, under the //user javascript comment we will insert all the Javascript for using the library. It is better practice to put your Javascript in a separate file but for simplicity we will put everything in one file for this tutorial. The Webifi Javascript library can generate a control for entering the user’s credentials. The webifiControl div will be used for this purpose. When you open the file in your browser it should look like this:
Javascript tutorial html file in browser before javascript is added
If the Save connection details checkbox is checked then the user’s credentials (the control is not generated yet) will be stored in your browser’s HTML5 local storage after connecting to the Webifi server. The discover button will send a discovery message for getting the session IDs of all your other devices that are discoverable and on the same default networks.

If you need help on how our technology works please read our How it works guide. The messages box will display connection and error messages.

2. Javascript

Next we will add the Javascript. Copy the code below and paste it under the comment: //user javascript

var webifi;  //this will reference the Webifi library
var recData = "";
var messages = "";

//this function runs when the page is finished loading
$(function () {
    webifi = WebifiCreate();
    var networkNames = [];

    //set name for discovery by other devices
    webifi.name = "Javascript tutorial";

    //set callbacks
    webifi.SetDataReceivedCallback(RecDataCallback);
    webifi.SetConnectionStatusCallback(ConnectionMessageCallback);
    webifi.SetErrorCallback(ErrorCallback);
    //create the webifi control
    webifi.WebifiControl("webifiControl");
    //see if previously entered information can be loaded from html5 local storage
    if (typeof (Storage) !== "undefined") {
        if (localStorage.webifiConnectName !== undefined) {
            webifi.SetConnectName(localStorage.webifiConnectName);
        }
        if (localStorage.webifiConnectPassword !== undefined) {
            webifi.SetConnectPassword(localStorage.webifiConnectPassword);
        }
        if (localStorage.webifiNetworkNames !== undefined) {
            networkNames = localStorage.webifiNetworkNames.split("\n");
        }
        else {
            networkNames.push("network 1");  //default to "network 1"
        }
    }
    else {
        networkNames.push("network 1");  //default to "network 1"
    }
    webifi.SetNetworkNames(networkNames);
});

function AddMessage(message) {
    messages += message + "\n";
    $('#textAreaMessages').val(messages);
}

//called when the send data button is clicked
function SendData() {
    var val;
    var sendData = webifi.CreateSendData();

    sendData.data = $('#textSendData').val();
    sendData.dataType = "data";
    var errorCode = webifi.SendData(sendData);
    if (errorCode === "0") {
        //data was sent
        AddMessage("Data sent")
    } else {
        messages += "Send Error: " + errorCode + "\n";
        messages += webifi.ConvertErrorCodeToString(errorCode) + "\n";
        AddMessage(messages)
    }
}

//callback functions
function RecDataCallback(data, dataType, from, sender) {
    //check if a discovery response was received
    if (dataType == "Discovery Response") {
        AddMessage("Device Discovered: " + data + ", ID: " + from);
    }
    else {
        recData += data;
        $('#textAreaRecData').val(recData);
    }
}

function ErrorCallback(errorCode, sender) {
    messages += "Error: " + errorCode + "\n";
    messages += webifi.ConvertErrorCodeToString(errorCode) + "\n";
    $('#textAreaMessages').val(messages);
}

function ConnectionMessageCallback(connected, sender) {
    if (connected) {
        messages += "Connection successful\n";
        //after successful connect store Webifi variables to local storage to make it easier to connect next time
        if ($('#checkSaveConnectionDetails').prop('checked')) {
            if (typeof (Storage) !== "undefined") {
                localStorage.setItem("webifiConnectName", webifi.GetConnectName());
                localStorage.setItem("webifiConnectPassword", webifi.GetConnectPassword());
                //convert network names array into string for storing
                var networkNamesArray = webifi.GetNetworkNames();
                var networkNamesStr = "";
                var i;
                for (i = 0; i < networkNamesArray.length; i++) {
                    if (i > 0) {
                        networkNamesStr += "\n";
                    }
                    networkNamesStr += networkNamesArray[i];
                }
                localStorage.setItem("webifiNetworkNames", networkNamesStr);
            }
        }
    } else {
        messages += "Connection failed\n";
    }
    $('#textAreaMessages').val(messages);
}

function ClearRecData() {
    $('#textAreaRecData').val("");
    recData = "";
}

function ClearMessages() {
    $('#textAreaMessages').val("");
    messages = "";
}

function SendDiscovery() {
    webifi.SendDiscovery();
}

When you refresh the page in your browser the controls for entering the user’s credentials should be displayed. The page should look as follows:
Javascript tutorial html file in browser after javascript was added
For a detailed description about all the functions and callbacks please see our Javascript Library Documentation page.

3. Test

The last step is to test the HTML file. Open the file in your browser, enter valid credentials and then click on the Start button. After a short delay the Messages text box should say “Connection Successful” if your user details are correct. We need something to communicate with. We made a test page especially for this purpose. Go to our Test Page and enter your details in the connect name and password text boxes and click the Start button. Enter “test123” into the Send data textbox and click the Send button. The message should be displayed on the web page. Next click the Send data button on the test page and the message should be received in the Javascript tutorial.

If both the tutorial and the web page connected successfully but no data can be sent between them then the most common cause is that the network names don’t match. If the devices are not on the same default networks then they cannot exchange data unless the data is specifically sent to the other one’s network. The network names can be set after connection by clicking the Set Network Names button. Click on the Send Discovery button. After a short delay the Messages textbox should display a list of devices that was discovered. We hope this tutorial gave enough information to get you going using our Javascript library. We also have a full featured example available at https://github.com/webifi-me/WebifiJavascriptExample