Tutorial: 08 - Handling Membership Changes

08 - Handling Membership Changes

View the Video Tutorial

All ScripTouch devices are USB devices. Due to the nature of USB these devices can be added to or removed from a computer at any time (including when you're using them). OmniScript provides events to help you handle when ScripTouch devices are added to and removed from a computer.

Here's an example of an application handling these events:

function tutorial() {
    var devConnected = false;
    var devices = [];

    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("Just connected to device ",msg.device.uuid);
            devConnected = true;
        } else if(msg._class==="ConnectionDeviceMembershipChange") {
            console.log("The device membership has changed, we now have access to ",msg.devices.devices.length,"devices.");
            devices = msg.devices.devices;

            //Lets see if we're currently connected.
            if(!devConnected && devices.length>0) {
                //We're not connected to a device, but we could be!
                socket.send(JSON.stringify({"_class":"DeviceOpenRequest","uuid":devices[0].uuid}));
            }
        } else if(msg._class==="DeviceCloseResponse") {
            console.log("The device we were connected to was just removed!");
            devConnected = false;

            //Lets see if we have any other devices we can go to:
            if(devices.length>0) {
                socket.send(JSON.stringify({"_class":"DeviceOpenRequest","uuid":devices[0].uuid}));
            }
        }
    };
}