Language - JavaScript: Difference between revisions

From Phidgets Support
(46 intermediate revisions by 3 users not shown)
Line 1: Line 1:
<metadesc>Communicate with sensors, controllers and relays with Phidgets! Our JavaScript API supports Node.js and Browsers.</metadesc>
[[Category:Language]]
[[Category:Language]]
{{OSLang|[[File:icon-Javascript.png|64x64px|link=|left|alt=]]|Javascript is a high-level object-oriented programming language ideal for use in web applications.}}
__TOC__
__TOC__


== Introduction ==
== Quick Downloads ==
=== Documentation ===


If this is your first time working with a Phidget, we suggest starting with the Getting Started page for your specific device. This can be found in the user guide for your device. That page will walk you through installing drivers and libraries for your operating system, and will then bring you back here to use Javascript specifically.
*{{Phidget22API}} (Select JavaScript from drop-down menu)


Javascript is capable of using the complete {{Phidget22API}}, including events. We also provide example code in Javascript for all Phidget objects.
=== Libraries ===


Javascript does not require any special programming environment to write. Just use your favourite text editor to write .html and .js files.
*'''Browser''': [{{SERVER}}/downloads/phidget22/libraries/any/Phidget22JavaScript.zip JavaScript Library Download]
*'''Node.js''': npm install phidget22


== Quick Downloads ==
=== Example Code ===
 
'''<span style="color:#FF0000">List of download links, to be added once files are available</span>'''


=== Documentation ===
*[{{SERVER}}?view=code_samples&lang=JavaScript&os=Nodejs JavaScript Examples (Node.js)]
=== Example Code ===
*[{{SERVER}}?view=code_samples&lang=JavaScript&os=Browser JavaScript Examples (Browser)]
=== Libraries and Drivers ===


== Getting Started with Javascript ==
=== Tools ===


If you are new to writing code for Phidgets, we recommend starting by running, then modifying existing examples. This will allow you to:
*[{{SERVER}}/downloads/phidget22/tools/any/Phidget22JavaScriptControlPanel.zip JavaScript Control Panel Source]
{{ExampleCodeReasons}}


Instructions are divided up by operating system. Choose:
=== OS Libraries ===
*[[#Windows|Windows XP / Vista / 7]]
*[[#OS X |OS X]]
*[[#Linux | Linux]] (including PhidgetSBC)


== Windows ==
{{AllQuickDownloads}}
===Description of Library Files===
Javascript  programs depend on the following files, which the installers above put onto your system:


*'''jphidgets22.x.x.x.min.js''' is the Javascript library for Phidget22. The x's in the filename denote the version of the library.
== Getting Started with JavaScript ==
Welcome to using Phidgets with JavaScript! By using JavaScript, you will have access to the complete {{Phidget22API}}, including events. We also provide example code in JavaScript for all Phidget devices.


===Visual Studio Code===
=== Version Change ===
'''Note:''' The Phidgets JavaScript library has been bumped to version 2.x.x following a rewrite. The version 2 API is mostly identical to version 1, but does have some breaking changes. It is highly recommended that any code written against version 1 be updated to version 2, as version 1 is considered unstable.


Javascript can be written in any text editor. If you don't have one yet, [https://code.visualstudio.com/ Visual Studio Code] is recommended because it's free and simple.  
== Phidget Network Server ==
The JavaScript library requires the [[Phidget Network Server]]. Start by configuring the server for your OS:


====Use Our Examples====
* [[OS - Windows#Phidget Network Server|Windows]]
* [[OS - OS X#Phidget Network Server|macOS]]
* [[OS - Linux#Phidget Network Server|Linux]]
* [[OS - Phidget SBC#Phidget Network Server|PhidgetSBC]]


0000000000000000000000000000what will the customers see when they get the examples?
The Phidget Server includes a built-in Webserver. This must be enabled when using the JavaScript library in browser, but can be left disabled when using the library from Node.js.


====Write Your Own Code====
The Phidget Server Webserver can be used to serve files - such as the Phidget JavaScript library, or your own projects. By default, it serves the JavaScript control panel files. The main purpose of the Webserver is to support a Websockets connection for the Browser library - because regular sockets cannot be used in Browser. The Node.js library uses raw sockets to connect to the Phidget Server, and so does not require the Webserver or Websockets.


We'll be using [https://jquery.com/download/ jQuery] in these examples. jQuery is a Javascript library that will make it easier for us to access elements on an html page.  
== JavaScript Control Panel ==
The JavaScript control panel is a Browser version of our Phidget control panel. This can be used to view and control all Phidgets attached to a Phidget server. The JavaScript control panel is installed by default on Windows, macOS and PhidgetSBC. You can also download the source [{{SERVER}}/downloads/phidget22/tools/any/Phidget22JavaScriptControlPanel.zip here].


Let's start by writing a simple html page that makes a dynamic list of attached Phidgets visible to the user. Create a new folder and put the required library files inside. Then create a new HTML file and fill it with the following code:
Make sure the Phidget Server - Webserver is enabled, and running, then navigate to http://localhost:8989. You will now see a program written with JavaScript/HTML that mimics the Phidget Control Panel. It will show all the Phidgets attached to your machine. By double-clicking on the Phidgets, and example will launch.


<div class="source">
[[File:Javascript_windows_controlpanel.png|link=|center]]
<syntaxhighlight lang=javascript>


<!DOCTYPE html>
== Browser ==
=== Use Our Examples ===
One of the best ways to start programming with Phidgets is to use our example code as a guide. Our browser examples are available [{{SERVER}}?view=code_samples&lang=JavaScript&os=Browser here].


<html>
=== Write Your Own Code ===
<head>
Let's start by writing a simple HTML page that makes a dynamic list of attached Phidgets visible to the user.
<title>Javascript Test Program</title>
We will be using the JavaScript library [https://jquery.com/download/ jQuery] in these examples. jQuery is not required in order to use Phidgets, however, it will make it easier for us to access elements on an HTML page.  
<script src="jquery-2.1.4.min.js"></script>
<script src="sha256.js"></script>
<script src="jphidgets22.1.0.0.min.js"></script>


<script>
To start, create a new empty folder.


$(document).ready(function () {
Next, download the latest JavaScript browser library from [{{SERVER}}/downloads/phidget22/libraries/any/Phidget22JavaScript.zip here] and copy the files into the folder.
var conn = new jPhidgets.Connection('ws://' + window.location.host + '/phidgets', { name: window.location.host });


conn.connect().then(function () {
Next, create a file called ''index.html'' and copy the following code into it (Note: if you have a newer jQuery, modify the code below to match your version):
console.log('connected');
}).catch(function (err) {
alert('failed to connect to server:' + err);
});;


conn.onattach = function(dev) {
<syntaxhighlight lang=javascript>
$('#list').append(new Option(dev.name,dev.phid));
<!DOCTYPE html>
}
<html>
<head>
    <title>Phidget Manager</title>
    <script src="jquery-2.1.4.min.js"></script>
    <script src="sha256.min.js"></script>
    <script src="phidget22.min.js"></script>
    <script>
        $(document).ready(function() {
            var conn = new phidget22.Connection(8989, 'localhost');


conn.ondetach = function(dev) {
            conn.connect().then(function() {
$("#list option[value='" + dev.phid + "']").remove();
                console.log('connected');
}
            }).catch(function(err) {
});
                conn.delete();
                alert('failed to connect to server:' + err);
            });


</script>
            var man = new phidget22.Manager({
                onDeviceAttach: function(dev) {
                    $('#list').append(new Option(dev.getDeviceName(), dev.getKey()));
                },
                onDeviceDetach: function(dev) {
                    $("#list option[value='" + dev.getKey() + "']").remove();
                }
            });
            man.open();
        });
    </script>
</head>
</head>


<body>
<body>
<label> Attached Phidgets: </label>
    <label> Attached Phidgets: </label>
<div>
    <div>
<select multiple id="list" style="width: 500px;"></select>
        <select multiple id="list" style="width: 500px; height: 200px"></select>
</div>
    </div>
</body>
</body>
</html>
</html>
</syntaxhighlight>
</syntaxhighlight>
</div>


Pages that employ the use of Javascript are divided into two parts: HTML and Javascript. Code in {{Code|<script>}} tags is Javascript, and everything else is HTML. HTML will handle the parts of our program that will be visible to the user, and the Javascript will handle all of the behind-the-scenes processing. First, we list all of the Javascript libraries we're including. Next, we have our main script which makes a Phidget connection as soon as the page is ready and loaded. It also sets an attach handler and detach handler which will trigger any time a Phidget is connected or disconnected to the computer. Below this, we have a tiny bit of HTML which will display a select list that our Javascript code will interact with.
This code uses the [[Phidget Manager]] to list any Phidget accessible from your computer (either directly via USB or indirectly over the network).  


Now, in order to test our new program we have to run it on a server.
Finally, double click index.html to open it in a browser. You should see something like this:
[[File:Javascript_windows_example.png|link=|center]]


==== Setting up the Phidget Network Server ====
Open the developer console to get a better idea what is going on:
[[File:Javascript_windows_devconsole.png|link=|center]]


The easiest way to get our code up and running is to host it using the Phidget Network Server. Go to {{Code|C:\Program Files\Phidgets\Phidget22}} and open {{Code|networkserver.cfg}}.
For information about the Node.js examples, keep reading. Otherwise, skip ahead to the [[#Edit the Examples | edit the examples]] section located below.


000000000000000000000000000 Confirm paths later
== Node.js ==
=== Use Our Examples ===
One of the best ways to start programming with Phidgets is to use our example code as a guide. In order to run the examples, you will need to download and install [https://nodejs.org/ Node.js].


Find the {{Code|[webserver]}} section and change the docroot to the path of the HTML file you just wrote.  
Now that you have Node.js installed, select an example that will work with your Phidget:
*[{{SERVER}}?view=code_samples&lang=JavaScript&os=Nodejs JavaScript Examples (Node.js)]


Save, and then run NetworkServer.exe.
Navigate to the example folder that you previously downloaded, open the command prompt at this location and enter the following command:
<syntaxhighlight lang='bash'>
npm update
</syntaxhighlight>


[[image:js_networkservice.jpg|link=]]
[[File:Javascript_windows_npmupdate.png]]


A window like the one pictured should open.
Next, enter the following command to run the example (replacing Accelerometer with your example name):
<syntaxhighlight lang='bash'>
node Accelerometer localhost
</syntaxhighlight>
[[File:Javacsript_windows_nodeexample.png|link=|center]]
You should now have the example up and running. When you are ready, the next step is [[#Edit the Examples | editing the examples]].


====Running the Program====
== Edit the Examples ==
{{WriteCode_Intro|JavaScript}}


Now, open a web browser and type {{Code|localhost:8080}} in the address bar. You should see the HTML of the page we just wrote:
=== Step One: Connect===
In Javascript, you must first connect to the Phidget server using the {{Code|Connection}} object. Have a look at the Connection API for more details: {{Phidget22API}} -> Select JavaScript then select Connection API.


[[image:js-testpage.jpg|link=]]
Plugging in any Phidget should result in having an entry appear in the list. You will also see any [[Phidget Dictionary|Phidget dictionaries]] that are running on this network server. Unplugging the Phidgets should cause them to disappear from the list. You can open the browser's developer console to see the various messages we've been printing out and to set breakpoints in our Javascript code. In Chrome, for example, you can open the developer console with '''F12'''.
Now, let's change the program so that we can access a specific channel on a Phidget. In this example we'll read the voltage of a VoltageInput channel on the Phidget 1018_2. Insert a new function to run when the Phidget connection is made:
<div class="source">
<syntaxhighlight lang=javascript>
<syntaxhighlight lang=javascript>
function main() {
    var conn = new phidget22.Connection(5661, 'localhost');
    conn.connect().then(function () {
        console.log("Connected");
        runCode();
    }).catch(function (err) {
        console.error("Failed to connect", err);
    });
}
</syntaxhighlight>


conn.connect().then(function () {
Once a connection has been established, it will stay active until it is closed, even across network outages and server restarts.
console.log('connected');
readVoltage();
}).catch(function (err) {
alert('failed to connect to server:' + err);
});;


Multiple Connections can be created and connected at once. Any opened Phidget or Manager objects  will match against devices on all connections.


</syntaxhighlight>
=== Step Two: Create and Open===
</div>
After connecting, create a new channel object of the correct channel class, then call the {{Code|open()}} function to open the channel. Once it has successfully opened we can interact with it and start receiving data from it. We can also set up event handlers just before opening.


Then, define the function just below this one, but still inside the {{Code|<script>}} tags.
For example, if we were using an Digital Input as our device, it would look like this:


<div class="source">
<syntaxhighlight lang=javascript>
<syntaxhighlight lang=javascript>


function readVoltage() {
function runCode() {
    var ch = new phidget22.DigitalInput();


var ch = new jPhidgets.VoltageInput();
    ch.onAttach = digitalInput_attach;
    ch.onStateChange = digitalInput_change;


ch.onVoltageChange = function (voltage) {
    ch.open().then(function () {
$('#res').text(this.getVoltage());
        // code to execute after open succeeds
};
    }).catch(function (err) {
 
        // code to execute if open fails
ch.open();
    });
}
}


</syntaxhighlight>
</syntaxhighlight>
</div>


This function sets up a change handler which will update a piece of text every time the voltage changes. It will match to the first VoltageInput object that it finds.  
Once the channel successfully opens, you can access it and you will start to get events from it. We can define the event handler functions :


Lastly, add a line in the HTML section that adds an element where we can change the text to match the present voltage value:
<div class="source">
<syntaxhighlight lang=javascript>
<syntaxhighlight lang=javascript>


<body>
function digitalInput_attach(ch) {
<label> Attached Phidgets: </label>
    console.log(ch + ' attached');
<div>
}
<select multiple id="list" style="width: 500px;"></select>
</div>
<label> Voltage Input Value: </label> <label id="res"></label>
</body>


</syntaxhighlight>
function digitalInput_change(state) {
</div>
    console.log('state changed:' + state);
 
Now save your HTML file and refresh your browser. When you plug in a device with a VoltageInput channel, you should see the voltage value constantly update on the page.
 
If you wanted to open the VoltageInput object on a VINT Hub port, you would have to add the following two lines just before the {{Code|open()}} call:
 
<div class="source">
<syntaxhighlight lang=javascript>
ch.setHubPort(0); // open hub port 0
ch.setIsHubPort(true);
</syntaxhighlight>
</div>
 
== OS X ==
 
 
== Linux ==
 
== Edit the Examples ==
 
By following the instructions for your operating system and compiler above, you probably now have a working example and want to understand it better so you can change it to do what you want. This teaching section has resources for you to learn from the examples and write your own.
Your main reference for writing C# code will be the {{Phidget22API}} Manual.
 
=== Example Flow ===
 
{{ExamplePseudocode|In C#, you can name these '''event''' functions whatever you like.  You will add them to the Phidget library in the Main Code section.  This hooks them into the actual events when they occur.
 
 
In the example code, the event functions common to all Phidgets are things like attach, detach, and error handling.
 
Other event functions will be specific to each device, like when a tag is read on an RFID board, or when a sensor value changes on an Interface Kit.
|Creating a Phidget software object in C# is specific to the Phidget.  For a Phidget Spatial, for example, this would involve creating a {{Code|Spatial}} object.  The examples show how to do this and other API functions.
 
 
The object provides device specific methods and properties which are available from the API for your specific Phidget.|
[{{SERVER}}/documentation/Phidget22.NET.zip .NET API]}}
 
=== Code Snippets ===
 
==== Step One: Initialize and Open ====
The Open() function opens the software object, but not hardware. So, it is not a guarantee you can use the Phidget immediately.
 
For example, if we were using an Digital Input as our device, the create and open calls would look like this:
 
<div class="source">
<syntaxhighlight lang=csharp>
using Phidget22;
using Phidget22.Events;
 
namespace Program
{
    class Code
    {
        static void Main(string[] args)
        {
            try
            {
 
                // Declare a DigitalInput object
                DigitalInput device = new DigitalInput();
 
                // Hook in any event handlers
                // ...
 
                // Open the device
                device.Open();
 
            }
            catch (PhidgetException ex) { Console.WriteLine(ex.Description); }
        }
    }
}
}
</syntaxhighlight>
</div>


==== Step Two: Wait for Attachment (plugging in) of the Phidget ====
To use the Phidget, it must be plugged in (attached). We can handle this simply by calling open with a number as a parameter in place of the basic open. This function works for any Phidget. This will block until a connection is made to the Phidget, or the specified timeout is exceeded:
<div class="source">
<syntaxhighlight lang=C>
device.Open(5000);
</syntaxhighlight>
</syntaxhighlight>
</div>


Sometimes, it makes more sense to handle the attachment via an event. This would be in instances where the Phidget is being plugged and unplugged, and you want to handle these incidents. Or, when you want to use event-driven programming because you have a GUI-driven program. In these cases, an event-driven code snippet to handle the attachment might look something like this:
Now that they've been registered in the {{Code|runCode()}} function and the device has been opened, these event handlers will be able to trigger. The first one triggers when the DigitalInput channel attaches, and the second one will trigger whenever the state of the attached DigitalInput changes.
 
<div class="source">
<syntaxhighlight lang=CSharp>
void attachEventHandler(object sender, Phidget22.Events.AttachEventArgs e) {
{
  Phidget attachedDevice = (Phidget)sender;
  int serialNumber = attachedDevice.DeviceSerialNumber;
  string deviceName = attachedDevice.DeviceName;
  Console.WriteLine("Hello Device {0},  Serial Number: {1}!", deviceName, serialNumber.ToString());
}
</syntaxhighlight>
</div>


And the code to set up the event handler within the code opening your device might look like:
=== Step Three: Do Things with the Phidget ===
Some values can be directly read and set on the Phidget. These functions can be used inside a polling loop as an alternative to event driven programming. The lines inside the loop would be something like this, after which you could do something with the value:


<div class="source">
<syntaxhighlight lang=javascript>
<syntaxhighlight lang=CSharp>
//Code for -creating- device here....


device.Attach += attachEventHandler;
var di_state = ch.getState(); // get the state of the digital input


//Code for -opening- device here....
</syntaxhighlight>
</syntaxhighlight>
</div>


==== Step Three: Do Things with the Phidget ====
=== Step Four: Close ===
We recommend the use of event driven programming when working with Phidgets. This allows the program to execute other tasks until the Phidget generates a new event. You can hook a custom function into an event trigger like this, using a Digital Input Phidget as an example:
At the end of your program (or at least, at the end of the part that uses the Phidget), it is advisable to close your device. This ensures that the Phidget will be available to other programs that want to use it, since a channel can only be in use by one program at a time unless it's opened via the Phidget Server. It's not necessary to delete the object after closing in Javascript.
<div class="source">
<syntaxhighlight lang=csharp>
device.StateChange += input_change;
</syntaxhighlight>
</div>


The input_change method is defined as follows:
<syntaxhighlight lang=javascript>


<div class="source">
ch.close();
<syntaxhighlight lang=csharp>
void input_change(object sender, Phidget22.Events.DigitalInputStateChangeEventArgs e) {
    textBox1.Text = "State: " + e.State;
}
</syntaxhighlight>
</syntaxhighlight>
</div>
Some values can be directly read and set on the Phidget. These functions can be used inside a polling loop as an alternative to event driven programming. The line inside the loop would be something like this, after which you could do something with the value:
<div class="source">
<syntaxhighlight lang=csharp>
bool val = device.State;
device.State = true;
</syntaxhighlight>
</div>
==== Step Four: Close and Delete ====
At the end of your program, be sure to close your device.
<div class="source">
<syntaxhighlight lang=csharp>
private void Form1_FormClosing(object sender, FormClosingEventArgs e)  {
    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If device.Attached Then
            device.Close()
        End If
    End Sub
}
</syntaxhighlight>
</div>


== Further Reading ==
== Further Reading ==
[[Phidget Programming Basics]] - Here you can find the basic concepts to help you get started with making your own programs that use Phidgets.
[[Phidget Programming Basics]] - Here you can find the basic concepts to help you get started with making your own programs that use Phidgets.


Line 337: Line 226:
[[Logging, Exceptions, and Errors]] - Learn about all the tools you can use to debug your program.
[[Logging, Exceptions, and Errors]] - Learn about all the tools you can use to debug your program.


[[Phidget Network Service]] - Phidgets can be controlled and communicated with over your network- either wirelessly or over ethernet.
[[Phidget Network Server]] - Phidgets can be controlled and communicated with over your network- either wirelessly or over ethernet.

Revision as of 16:18, 9 April 2018

Quick Downloads

Documentation

Libraries

Example Code

Tools

OS Libraries

Getting Started with JavaScript

Welcome to using Phidgets with JavaScript! By using JavaScript, you will have access to the complete Phidget22 API, including events. We also provide example code in JavaScript for all Phidget devices.

Version Change

Note: The Phidgets JavaScript library has been bumped to version 2.x.x following a rewrite. The version 2 API is mostly identical to version 1, but does have some breaking changes. It is highly recommended that any code written against version 1 be updated to version 2, as version 1 is considered unstable.

Phidget Network Server

The JavaScript library requires the Phidget Network Server. Start by configuring the server for your OS:

The Phidget Server includes a built-in Webserver. This must be enabled when using the JavaScript library in browser, but can be left disabled when using the library from Node.js.

The Phidget Server Webserver can be used to serve files - such as the Phidget JavaScript library, or your own projects. By default, it serves the JavaScript control panel files. The main purpose of the Webserver is to support a Websockets connection for the Browser library - because regular sockets cannot be used in Browser. The Node.js library uses raw sockets to connect to the Phidget Server, and so does not require the Webserver or Websockets.

JavaScript Control Panel

The JavaScript control panel is a Browser version of our Phidget control panel. This can be used to view and control all Phidgets attached to a Phidget server. The JavaScript control panel is installed by default on Windows, macOS and PhidgetSBC. You can also download the source here.

Make sure the Phidget Server - Webserver is enabled, and running, then navigate to http://localhost:8989. You will now see a program written with JavaScript/HTML that mimics the Phidget Control Panel. It will show all the Phidgets attached to your machine. By double-clicking on the Phidgets, and example will launch.

Javascript windows controlpanel.png

Browser

Use Our Examples

One of the best ways to start programming with Phidgets is to use our example code as a guide. Our browser examples are available here.

Write Your Own Code

Let's start by writing a simple HTML page that makes a dynamic list of attached Phidgets visible to the user. We will be using the JavaScript library jQuery in these examples. jQuery is not required in order to use Phidgets, however, it will make it easier for us to access elements on an HTML page.

To start, create a new empty folder.

Next, download the latest JavaScript browser library from here and copy the files into the folder.

Next, create a file called index.html and copy the following code into it (Note: if you have a newer jQuery, modify the code below to match your version):

<!DOCTYPE html>
<html>
<head>
    <title>Phidget Manager</title>
    <script src="jquery-2.1.4.min.js"></script>
    <script src="sha256.min.js"></script>
    <script src="phidget22.min.js"></script>
    <script>
        $(document).ready(function() {
            var conn = new phidget22.Connection(8989, 'localhost');

            conn.connect().then(function() {
                console.log('connected');
            }).catch(function(err) {
                conn.delete();
                alert('failed to connect to server:' + err);
            });

            var man = new phidget22.Manager({
                onDeviceAttach: function(dev) {
                    $('#list').append(new Option(dev.getDeviceName(), dev.getKey()));
                },
                onDeviceDetach: function(dev) {
                    $("#list option[value='" + dev.getKey() + "']").remove();
                }
            });
            man.open();
        });
    </script>
</head>

<body>
    <label> Attached Phidgets: </label>
    <div>
        <select multiple id="list" style="width: 500px; height: 200px"></select>
    </div>
</body>
</html>

This code uses the Phidget Manager to list any Phidget accessible from your computer (either directly via USB or indirectly over the network).

Finally, double click index.html to open it in a browser. You should see something like this:

Javascript windows example.png

Open the developer console to get a better idea what is going on:

Javascript windows devconsole.png

For information about the Node.js examples, keep reading. Otherwise, skip ahead to the edit the examples section located below.

Node.js

Use Our Examples

One of the best ways to start programming with Phidgets is to use our example code as a guide. In order to run the examples, you will need to download and install Node.js.

Now that you have Node.js installed, select an example that will work with your Phidget:

Navigate to the example folder that you previously downloaded, open the command prompt at this location and enter the following command:

npm update

Javascript windows npmupdate.png

Next, enter the following command to run the example (replacing Accelerometer with your example name):

node Accelerometer localhost
Javacsript windows nodeexample.png

You should now have the example up and running. When you are ready, the next step is editing the examples.

Edit the Examples

By following the instructions for your operating system and compiler above, you now have working examples and a project that is configured. This teaching section will help you understand how the examples were written so you can start writing your own code.


Remember: your main reference for writing JavaScript code will be the Phidget22 API Manual and the example code.

Step One: Connect

In Javascript, you must first connect to the Phidget server using the Connection object. Have a look at the Connection API for more details: Phidget22 API -> Select JavaScript then select Connection API.

function main() {
    var conn = new phidget22.Connection(5661, 'localhost');
    conn.connect().then(function () {
        console.log("Connected");
        runCode();
    }).catch(function (err) {
        console.error("Failed to connect", err);
    });
}

Once a connection has been established, it will stay active until it is closed, even across network outages and server restarts.

Multiple Connections can be created and connected at once. Any opened Phidget or Manager objects will match against devices on all connections.

Step Two: Create and Open

After connecting, create a new channel object of the correct channel class, then call the open() function to open the channel. Once it has successfully opened we can interact with it and start receiving data from it. We can also set up event handlers just before opening.

For example, if we were using an Digital Input as our device, it would look like this:

function runCode() {
    var ch = new phidget22.DigitalInput();

    ch.onAttach = digitalInput_attach;
    ch.onStateChange = digitalInput_change;

    ch.open().then(function () {
        // code to execute after open succeeds
    }).catch(function (err) {
        // code to execute if open fails
    });
}

Once the channel successfully opens, you can access it and you will start to get events from it. We can define the event handler functions :

function digitalInput_attach(ch) {
    console.log(ch + ' attached');
}

function digitalInput_change(state) {
    console.log('state changed:' + state);
}

Now that they've been registered in the runCode() function and the device has been opened, these event handlers will be able to trigger. The first one triggers when the DigitalInput channel attaches, and the second one will trigger whenever the state of the attached DigitalInput changes.

Step Three: Do Things with the Phidget

Some values can be directly read and set on the Phidget. These functions can be used inside a polling loop as an alternative to event driven programming. The lines inside the loop would be something like this, after which you could do something with the value:

var di_state = ch.getState(); // get the state of the digital input

Step Four: Close

At the end of your program (or at least, at the end of the part that uses the Phidget), it is advisable to close your device. This ensures that the Phidget will be available to other programs that want to use it, since a channel can only be in use by one program at a time unless it's opened via the Phidget Server. It's not necessary to delete the object after closing in Javascript.

ch.close();

Further Reading

Phidget Programming Basics - Here you can find the basic concepts to help you get started with making your own programs that use Phidgets.

Data Interval/Change Trigger - Learn about these two properties that control how much data comes in from your sensors.

Using Multiple Phidgets - It can be difficult to figure out how to use more than one Phidget in your program. This page will guide you through the steps.

Polling vs. Events - Your program can gather data in either a polling-driven or event-driven manner. Learn the difference to determine which is best for your application.

Logging, Exceptions, and Errors - Learn about all the tools you can use to debug your program.

Phidget Network Server - Phidgets can be controlled and communicated with over your network- either wirelessly or over ethernet.