Click here to Skip to main content
15,883,921 members
Articles / Programming Languages / Javascript

Node.js - Spokes JavaScript On Your Desktop

19 Dec 2012CPOL4 min read 16.4K   4  
Node.js - Spokes JavaScript On Your Desktop.

This article is in the Product Showcase section for our sponsors at CodeProject. These articles are intended to provide you with information on products and services that we consider useful and of value to developers.

Image 1

The Spokes SDK currently provides three main languages of choice for developers to work with: C++, C#, and JavaScript. Each have their strengths and weaknesses and specialize in different uses.

JavaScript communicates with Spokes via REST and regularly polls for events. It's a lightweight event-driven programming language that's great for getting a lot done with little writing. However, it's typically used for developing applications that run in a browser; JavaScript is reliant on a virtual machine that usually runs in a web browser (V8 for Chrome, for instance).

However, lately there's been a huge amount of activity around a new piece of technology called Node.js. Basically it's Chrome's V8 JavaScript engine ripped out of the browser and running on its own; on your desktop. The exciting part of this is that, with Node.js, you can write event-driven programs with JavaScript that run on your desktop without requiring a browser to run your code in.

It's really simple and straightforward to get started with some Spokes desktop application development in JavaScript and Node.js. So, let's take a look at how to make it happen.

Requirements

  • Node.js - the standalone JavaScript environment that will power our application.
  • Python 2.7.x - a dependency for a module needed to get jQuery working outside of the browser.
  • Spokes SDK - the Spokes tools and runtime environment. (version 2.6 as of this posting)

You'll also need a text editor for writing your JavaScript code in. I use Notepad++.

Configuration:

Once everything is installed we need to install the jQuery module for Node.js to get the Spokes JavaScript library working properly.

The Node Package Manager should have been added to your PATH environment variable on installation of Node.js so go ahead and fire up command prompt and run the following command: "npm install jquery".

Now we'll need to make a new folder which will be our working directory. In this working directly we want to copy the Spokes.js JavaScript library which can be found in the RestJsClient sample in the Samples folder in your Spokes SDK installation directory. (For me, this is located at "C:\Program Files\Plantronics\Plantronics SDK\Samples\RestJsClient").

We need to edit the Spokes.js file slightly to not only get jQuery working for the library, but to expose some functions to be used by our external custom JavaScript files as well.

We will first expose some key objects to be used outside of the file. Add the following lines to to the top of Spokes.js:

module.exports.Spokes = Spokes;
module.exports.SpokesCallId = SpokesCallId;
module.exports.SpokesContact = SpokesContact;

this will allow us now to make use of the Spokes, SpokesCallId, and SpokesContact objects outside of the file itself.

Another change that needs to be made is to tell Spokes.js what the $ variable equates to. Normally this is taken care of by including the latest jQuery file in our browser-based scripts but things are a little different in node.js with the way jQuery is included/installed. Luckily it's incredibly simple to make jQuery work. Following our last changes, add the following line:

var $ = require('jquery');

and change

if(typeof jQuery === 'undefined')

to

if(typeof $ === 'undefined')

It's that easy.

Finally, we need to replace all instances of alert() with console.log(). Otherwise, node.js is going to complain at you a lot and your program isn't going to work. You can either hit ctrl+h in notepad++ and Replace All "alert(" with "console.log(" or use sed if that's your preference or do everything by hand.

Once the changes are made we can go ahead and work on our main JavaScript file. I'm going to go ahead and paste an edited version of the JavaScript example from my previous blog post, RESTful Programming With Your Voyager Pro UC as the purpose of this post is to get you started with running your JavaScript applications on your desktop, not to show you how to get started with the JavaScript API (refer to the RESTful Programming blog post if you need details regarding how to get started).

This code should go in the same folder as the edited Spokes.js file.

var SpokesJS = require('./spokes'); //NEW CODE - Node.js automatically knows spokes is a .js file. Required to use the Spokes library.
var spokes = null; //spokes session manager (class defined in spokes.js) 
var plugin_registered = false; 
var plugin_name = "NodeSpokes"; 
  
//------------------------------------------------ 
// connectToSpokes - attempt to create a new Spokes session manager, register this app, 
//    and get a valid device to work with. Begin polling for events on success. 
//------------------------------------------------ 
var connectToSpokes = function() 
{ 
    //attempt to make a new Spokes object with localhost:32001/Spokes as the base url path for REST calls 
    spokes = new SpokesJS.Spokes("http://localhost:32001/Spokes");//Spokes is now an object in the SpokesJS module
    spokes.Device.deviceList( function(result) 
    { 
         //on success... 

         if(!result.isError) 
         { 
              //on valid device found... 
              if(result.Result[0] !== null) 
              { 
                   //attempt to connect to the valid device and start polling for events from it. 
                   spokes.Device.attach(result.Result[0].Uid, controlInterface); 
                   pollDeviceEvents(); 
              } 

              else 
              { 
                   console.log("Error: Device was null on connecting to Spokes. Is there a Plantronics device connected?"); 
              } 
         } 
         else 
         { 
              console.log("Error connecting to Spokes."); 
         } 

    }); 
}; 
//------------------------------------------------ 
// controllerInterface - callback function to that registers this app on successful contact with a valid device. 
//------------------------------------------------ 
var controlInterface = function(session) 
{ 
    //if an error popped up in our session or we failed to connect with a device... 
    if(session.isError || !spokes.Device.isAttached) 
    { 
         console.log("Session Registration Error"); 
    } 
    else 
    { 
         registerPlugin(); 

    } 
}; 
//------------------------------------------------ 
// registerPlugin - where the actual dirty work is done for app registration. 
//------------------------------------------------ 
var registerPlugin = function() 
{ 
    //only register if we haven't done so already... 
    if(!plugin_registered) 
    { 
         spokes.Plugin.register(plugin_name, function(result) 
         { 
              if(!result.isError) 
              { 
                   //successfully registered the plugin. Set status of plugin to active. 

                   spokes.Plugin.isActive(plugin_name, true, function(result) 
                   { 
                        if(!result.isError) 
                        { 
                             plugin_registered = true;
                        } 
                        else 
                        { 

                             console.log("Error checking if plugin is active: " + result.Err.Description); 
                        } 
                   }); 
              } 
              else 
              { 
                   console.log("Error registering plugin: " + result.Err.Description);
              } 

         }); 
    } 
}; 
//------------------------------------------------ 
// pollDeviceEvents - regularly ask the Spokes service for new, if any, events to work with.
//    This is the main program loop where all the program-specific work will be done. 
//------------------------------------------------ 
var pollDeviceEvents = function() 
{ 
    setInterval(function() 
    { 
         if(spokes === null || !spokes.Device.isAttached) 
         { 
              return; 

         } 
         //ask for events, if any 
         spokes.Device.events(function(result) 
         { 
              var i;
              if(result.isError) 
              { 
                   console.log("Error polling for events: " + result.Err.Description);

              } 
              else 
              { 
                   //we have one or more events!
                   if(result.Result.length > 0) 
                   { 
                        i = 0; 

     
                        //iterate over the events while we haven't hit the end of the array of events returned 
                        while(i < result.Result.length) 
                        { 
                            console.log(result.Result[i].Event_Name);
                             i++; //increment counter so we're not stuck in an infinite loop 
                        } 
                   } 

              } 
         });
    }, 2000); //repeat this loop every 2 seconds. 
};
connectToSpokes(); //Begin the program. Entry point.

Save the above code to ... let's say, nodespokes.js. Now, if everything has been installed and configured right you should be able to fire up the command prompt, change directory to your working directory and run the nodespokes.js script with node.js by typing the following ' "C:/program files/nodejs/node" nodespokes.js' (assuming the default installation folder for when you installed node.js is C:/program files/nodejs).

Turn your headset on, turn it off, take it out of range. If everything's working as it should be you should see some events start displaying in the command prompt window. Kind of like this (making a call to a softphone from my cellphone while my headset is paired to both the computer and phone):

Image 2

Have fun developing with Spokes in a fantastic and powerful event-driven language! If you're the adventurous type you could even take a look at some of the latest efforts for providing GUI rendering for node.js projects such as Appjs. It'll be interesting to see where people take this.

I've attached the modified Spokes.js file and nodespokes.js file together in a zip that you should be able to start using once the requirements are all installed and configured.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
Today’s smart devices and applications have untapped potential in the realm of context-aware computing. Plantronics is making it possible for its audio devices to deliver contextual information to a range of applications through Plantronics headsets. The Plantronics Spokes SDK allows developers to create a range of business applications that will have the power to change the way we communicate and collaborate.

Please check out our DevZone for more info on the Spokes SDK:
http://developer.plantronics.com/community/devzone

Comments and Discussions

 
-- There are no messages in this forum --