Tutorial: 02 - Connecting

02 - Connecting

Connecting to an Instance

View the Video Tutorial

In order to connect to an instance a WebSocket must be established, an event handler must be registered and the socket must be told to connect:

function tutorial() {
    var socket = new WebSocket("ws://localhost:8080");
    socket.onopen = function() {
        console.log("Web Socket Open");
    };
    socket.onclose = function() {
        console.log("Web Socket Closed");
    };
    socket.onmessage = function(evt) {
        var msg = JSON.parse(evt.data);
        console.log("Server sent a message:",msg);
    };
}

That's it! When you run this example in your web application you should see two messages: one from your application ("Web Socket Open") and one from the OmniScript server. The message from OmniScript is a DeviceEnumeration object that gets sent every time a new connection is established. This enumeration contains information about the server as well as any devices currently attached to the computer.

Connecting to a Device

Now that you've connected; in order to do anything useful you'll need to figure out what devices are connected to a server and then open a connection to one of them:

function tutorial() {
    var socket = new WebSocket("ws://localhost:8080");
    socket.onopen = function() {
        console.log("Web Socket Open");
    };
    socket.onclose = function() {
        console.log("Web Socket Closed");
    };
    socket.onmessage = function(evt) {
        var msg = JSON.parse(evt.data);
        if(msg._class==="ConnectionOpen") {
            //We've just connected to the server.
            if(msg.serverInfo.devices.length>0) {
                //Lets open the first available device:
                var device = msg.serverInfo.devices[0];
                console.log("Opening device",device.uuid,": ",device.manufacturer,device.product);
                var obj = {"_class":"DeviceOpenRequest","uuid":device.uuid};
                socket.send(JSON.stringify(obj));
            }
        } else if(msg._class==="DeviceOpenResponse") {
            console.log("Successfully opened device!");
        } else {
            console.log("Server sent a message: ",msg);
        }
    };
}

In this example you're receiving the server's device list (through the ConnectionOpen object) and asking it to open the very first one for you by sending a DeviceOpenRequest object to the server containing the first device's UUID.

You'll notice that you now receive a new message from the server: an instance of a ScriptelDevice object. This object contains information about the device you've just connected to.