Language - JavaScript: Difference between revisions

From Phidgets Support
No edit summary
(24 intermediate revisions by 3 users not shown)
Line 1: Line 1:
[[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 ===
 
*{{Phidget22API}} (Select JavaScript from drop-down menu)
 
=== Example Code ===
 
*{{SampleCode|JavaScript|JavaScript Examples (Node.js)}}
*[{{SERVER}}/downloads/phidget22/tools/any/Phidget22JavaScriptControlPanel.zip Javascript Examples (HTML)]
 
=== Libraries ===
 
*[{{SERVER}}/downloads/phidget22/libraries/any/Phidget22JavaScript.zip JavaScript Library Download]
{{AllQuickDownloads}}
 
== 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.
 
If you are developing for Windows, keep reading. Otherwise, select your operating system to jump ahead:
*[[#macOS | macOS]]
*[[#Linux | Linux]]
 
== Windows ==
{{Windows_Languages}}


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.
===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 graphical and are installed with the Phidget libraries. In order to check them out, first open the Phidget Control Panel and navigate to the Network Server tab:
[[File:Windows_networkserver.PNG|link=|center]]


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


Javascript does not require any special programming environment to write. Just use your favourite text editor to write .html and .js files.  
Next, make sure the Webserver is enabled (''Enabled'' checkbox in ''Webserver'' section), and start the Phidget Network Server by clicking on the ''Start'' button at the bottom of the window. Click on the hyperlink as shown in the image below (or navigate to http://localhost:8989):
[[File:Javascript_windows_localhost.png|link=|center]]


== Quick Downloads ==


'''<span style="color:#FF0000">List of download links, to be added once files are available</span>'''
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:
[[File:Javascript_windows_controlpanel.png|link=|center]]


=== Documentation ===
=== Example Code ===
=== Libraries and Drivers ===


== Getting Started with Javascript ==
To view the source code that drives the examples, navigate to the following location:
*C:/Program Files/Phidgets/Phidget22/html


If you are new to writing code for Phidgets, we recommend starting by running, then modifying existing examples. This will allow you to:
{{ExampleCodeReasons}}


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


== Windows ==
===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.
Here you can view the code that was written to create the main webpage as well as all of the examples.  


===Browser Example (Visual Studio Code)===
====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 [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.


This section will outline how to get a Javascript example running in an internet browser. 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.


====Use Our Examples====
To start, create a new folder that looks like this:
[[File:Javascript_windows_folderlibraries.png|link=|center]]


The Javascript examples that we provide are designed to work with [[Language_-_JavaScript#node.js|node.js]], but you can easily modify them to work in a browser. Follow the steps in the next section below, and once you get the HTML page working, copy the contents of the {{Code|runExample()}} function into the function in your code that is called after connecting. Then, change any instance of {{Code|jPhidget22}} with {{Code|jPhidgets}}. When you visit the page, open up the developer's console (F12 is the hotkey for Chrome) and you'll be able to see the normal output for the examples in the console window.


====Write Your Own Code====
The referenced libraries are installed with the Phidget libraries and can be found at the following location:
*C:/Program Files/Phidgets/Phidget22/html


We'll be using the Javascript library [https://jquery.com/download/ jQuery] in these examples. While it's not required in order to use Phidgets, jQuery will make it easier for us to access elements on an html page.


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:
Next, create a file called ''index.html'' and copy the following code into it (Note: if you have newer JavaScript libraries, modify the code below to match your version numbers):


<div class="source">
<syntaxhighlight lang=javascript>
<syntaxhighlight lang=javascript>
<!DOCTYPE html>
<!DOCTYPE html>
<html>
<html>
<head>
<head>
Line 93: Line 106:


</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.
After copying the code above into your ''index.html'' file, your folder should look like this:
[[File:Javascript windows folder.png|link=|center]]
 
 
Next, open the Network Server tab in the Phidget Control Panel and modify the Webserver ''Docroot'' to your folders location:
[[File:Javascript_windows_docrootchange.png|link=|center]]
 
 
Finally, click on the hyperlink to see the example (or navigate to http://localhost:8989):
[[File:Javascript_windows_example.png|link=|center]]
 
 
Open the developer console to get a better idea what is going on:
[[File:Javascript_windows_devconsole.png|link=|center]]
 
 
For information about the Node.js examples, keep reading. Otherwise, skip ahead to the [[#Edit the Examples | 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 [https://nodejs.org/ Node.js].
 
 
Now that you have Node.js installed, select an example that will work with your Phidget:
*{{SampleCode|JavaScript|JavaScript Examples}}
 
 
Next, navigate to the Network Server tab in the Phidget Control Panel and press the ''Start'' button after ensuring the Webserver is enabled (''Enabled'' checkbox in ''Webserver'' section).
[[File:Windows_networkserver.PNG|link=|center]]
 
 
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>
 
[[File:Javascript_windows_npmupdate.png]]
 
 
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]].
 
==macOS==
=== Browser Example===
====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 graphical and are installed with the Phidget libraries. In order to check them out, first open the Phidget Control Panel and navigate to the Network Server tab:
[[File:Macos_networkserver_run.png|link=|center]]
 
 
Next, make sure the Webserver is enabled (''Enabled'' checkbox in ''Webserver'' section), and start the Phidget Network Server by clicking on the ''Start'' button at the top of the window. A button labelled ''View in Browser...'' will appear. Click on it now (or navigate to http://localhost:8989).
[[File:Javascript_macos_viewinbrowswer.png|link=|center]]
 


Now, in order to test our new program we have to run it on a server.
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:
[[File:Javascript_macos_browserexample.png|link=|center]]


==== Setting up the Phidget Network Server ====


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}}.
To view the source code that drives the examples, navigate to the following location:
*/Library/Application Support/Phidgets/Phidget22NetworkServer/html


Find the {{Code|[webserver]}} section and change the docroot to the path of the HTML file you just wrote.


Save, and then run NetworkServer.exe.  
[[File:Javascript_macos_filelocation.png|link=|center]]


[[image:js_networkservice.jpg|link=]]


A window like the one pictured should open.
Here you can view the code that was written to create the main webpage as well as all of the examples.


====Running the Program====
====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 [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.


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:


[[image:js-testpage.jpg|link=]]
To start, create a new folder that looks like this:
[[File:Javascript_macos_folderlibraries.png|link=|center]]


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''':


[[image:js-chromedev.jpg|900px|link=]]
The referenced libraries are installed with the Phidget libraries and can be found at the following location:
*/Library/Application Support/Phidgets/Phidget22NetworkServer/html


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">
Next, create a file called ''index.html'' and copy the following code into it (Note: if you have newer JavaScript libraries, modify the code below to match your version numbers):
 
<syntaxhighlight lang=javascript>
<syntaxhighlight lang=javascript>
<!DOCTYPE html>
<html>
<head>
<title>Javascript Test Program</title>
<script src="jquery-2.1.4.min.js"></script>
<script src="sha256.js"></script>
<script src="jphidgets22.1.0.0.min.js"></script>
<script>
$(document).ready(function () {
var conn = new jPhidgets.Connection('ws://' + window.location.host + '/phidgets', { name: window.location.host });


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


conn.onattach = function(dev) {
$('#list').append(new Option(dev.name,dev.phid));
}
conn.ondetach = function(dev) {
$("#list option[value='" + dev.phid + "']").remove();
}
});
</script>
</head>
<body>
<label> Attached Phidgets: </label>
<div>
<select multiple id="list" style="width: 500px;"></select>
</div>
</body>
</html>


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


Then, define the function just below this one, but still inside the {{Code|<script>}} tags.
After copying the code above into your ''index.html'' file, your folder should look like this:
[[File:Javascript_macos_folder.png|link=|center]]
 
 
Next, open the Network Server tab in the Phidget Control Panel and modify the Webserver ''Docroot'' to your folders location:
[[File:Javascript_macos_docrootchange.png|link=|center]]
 
 
Finally, click on the hyperlink (or navigate to http://localhost:8989) to see the example:
[[File:Javascript_macos_example.png|link=|center]]
 
 
Open the developer console to get a better idea what is going on:
[[File:Javascript_macos_devconsole.png|link=|center]]
 
 
For information about the Node.js example, keep reading. Otherwise, skip ahead to the [[#Edit the Examples | 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 [https://nodejs.org/ Node.js].
 
 
Now that you have Node.js installed, select an example that will work with your Phidget:
*{{SampleCode|JavaScript|JavaScript Examples}}


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


function readVoltage() {
Next, navigate to the Network Server tab in the Phidget Control Panel and press the ''Start Network Server'' button after ensuring the Webserver is enabled (''Enabled'' checkbox in ''Webserver'' section).
[[File:Macos_networkserver_run.png|link=|center]]


var ch = new jPhidgets.VoltageInput();


ch.onVoltageChange = function (voltage) {
Navigate to the example folder that you previously downloaded, open the command prompt at this location and enter the following command:
$('#res').text(this.getVoltage());
<syntaxhighlight lang='bash'>
};
sudo npm update
</syntaxhighlight>


ch.open();
[[File:Javascript_macos_npmupdate.png ‎]]
}


Next, enter the following command to run the example (replacing Accelerometer with your example name):
<syntaxhighlight lang='bash'>
node Accelerometer localhost
</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.  
[[File:Javascript_macos_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]].
 


Lastly, add a line in the HTML section that adds an element where we can change the text to match the present voltage value:
== Linux ==
===Browser Example===
====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 graphical and can be downloaded here:
*[{{SERVER}}/downloads/phidget22/tools/any/Phidget22JavaScriptControlPanel.zip Javascript Examples (HTML)]


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


<body>
After unpacking the examples, navigate to the following location:
<label> Attached Phidgets: </label>
*/etc/phidgets
<div>
 
<select multiple id="list" style="width: 500px;"></select>
 
</div>
Open the file named ''phidget22networkserver.pc'' and navigate to the ''www'' section, you should see something like this:
<label> Voltage Input Value: </label> <label id="res"></label>
[[File:Javacsript_linux_networkconfig.PNG|link=|center]]
</body>
 
 
As you can see from the image above, our ''docroot'' location is defined as the following location:
*/var/phidgets/www
 


Create the docroot location (if it doesn't exist already) and copy the contents of the example you downloaded into it by entering the following commands into the terminal:
<syntaxhighlight lang='bash'>
mkdir /var/phidgets
mkdir /var/phidgets/www
cp -a YOUR_SOURCE_FOLDER/. /var/phidgets/www
</syntaxhighlight>
</syntaxhighlight>
</div>
[[File:Javascript_linux_mkdir.PNG|link=|center]]


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:
Now that the example code is located at the ''docroot'' location, and the Phidget Webserver is enabled (can be seen in ''www'' section of ''phidget22networkserver.pc''), navigate to http://localhost:8080. You will see a program written with JavaScript/HTML that mimics the Phidget Control Panel (available on macOS and Windows). It will show all the Phidgets attached to your machine. By double-clicking on the Phidgets, and example will launch:
[[File:Javascript_linux_graphicalexample.PNG|link=|center]]


<div class="source">
 
Take a look at the source files that are now located at /var/phidgets/www
 
===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 [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.
 
To start, create a new folder that looks like this:
[[File:Javascript_linux_folderlibraries.PNG|link=|center]]
 
 
The referenced libraries can be found in the [{{SERVER}}/downloads/phidget22/tools/any/Phidget22JavaScriptControlPanel.zip Javascript Examples (HTML)] that we provide.
 
 
Next, create a file called index.html and copy the following code into it (Note: if you have newer JavaScript libraries, modify the code below to match your version numbers):
<syntaxhighlight lang=javascript>
<syntaxhighlight lang=javascript>
ch.setHubPort(0); // open hub port 0
<!DOCTYPE html>
ch.setIsHubPort(true);
<html>
</syntaxhighlight>
<head>
</div>
<title>Javascript Test Program</title>
<script src="jquery-2.1.4.min.js"></script>
<script src="sha256.js"></script>
<script src="jphidgets22.1.0.0.min.js"></script>


===node.js===
<script>


node.js is a Javascript runtime that will allow us to run Javascript code via the Windows command prompt. Download the latest version of node.js [https://nodejs.org/ here]. The installer will also set the class path and install '''npm''' (the node.js package manager), both of which are necessary for the next steps. Once it's been installed, open up a command prompt by searching for "cmd" in the start menu.  
$(document).ready(function () {
var conn = new jPhidgets.Connection('ws://' + window.location.host + '/phidgets', { name: window.location.host });


You can download our Javascript examples [[#Quick Downloads|here]].
conn.connect().then(function () {
console.log('connected');
}).catch(function (err) {
alert('failed to connect to server:' + err);
});;


In the command prompt, navigate to the folder that contains the Phidgets Javascript examples. There, type the following command:
conn.onattach = function(dev) {
$('#list').append(new Option(dev.name,dev.phid));
}
 
conn.ondetach = function(dev) {
$("#list option[value='" + dev.phid + "']").remove();
}
});


{{Code|npm update}}
</script>
</head>


This will cause the package manager to look at {{Code|package.json}} and update the Phidgets libraries.
<body>
<label> Attached Phidgets: </label>
<div>
<select multiple id="list" style="width: 500px;"></select>
</div>
</body>
</html>


====Use Our Examples====
</syntaxhighlight>


To run the examples, go to {{Code|C:\Program Files\Phidgets\Phidget22\}} and run {{Code|NetworkServer.exe}}. A window like the one below should open:


[[image:js_networkservice.jpg|link=]]
After copying the code above into your ''index.html'' file, your folder should look like this:
[[File:Javascript_linux_folder.PNG|link|center]]


In the other command prompt window, navigate to the folder that contains the Phidgets Javascript examples and type


{{Code|node <example> <address>}}
Next, modify the ''phidget22networkserver.pc'' file that is located at ''/etc/phidgets''. Navigate to the ''www'' section and change the ''docroot'' location to match the location of your ''index.html'' file:
[[File:Javascript_linux_modifydocroot.PNG|link=|center]]


where {{Code|<example>}} is the filename of the example you want to run (i.e. DigitalInput.js) and {{Code|<address>}} is the address of the Phidget server. In our case, it will be "localhost" because we're hosting it on the same computer:


{{Code|node DigitalInput.js localhost}}
After modifying the docroot location, ensure you restart the Phidget Network Server. After restarting the Phidget Network Server, navigate to http://localhost:8080 to view the example:
[[File:Javascript_linux_example.PNG|link=|center]]


This should result in a simple text-based example to be launched:


[[image:js_nodeexample.jpg|link=]]
Try opening the developer console for your web browser to see the Phidget JavaScript code executing and to get a better feel for the program.


====Write Your Own Code====
====Node.js====
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].


== OS X ==


Now that you have Node.js installed, select an example that will work with your Phidget:
*{{SampleCode|JavaScript|JavaScript Examples}}


== Linux ==


== Edit the Examples ==
Navigate to the example folder that you previously downloaded, open the terminal at this location and enter the following command:
<syntaxhighlight lang='bash'>
npm update
</syntaxhighlight>


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.
[[File:Javascript_linux_npmupdate.PNG|link=|center]]
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.
Next, enter the following command to run the example (replacing Accelerometer with your example name):
<syntaxhighlight lang='bash'>
node Accelerometer localhost
</syntaxhighlight>


[[File:Javascript_macos_nodeexample.png|link=|center]]


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.
You should now have the example up and running. When you are ready, the next step is [[#Edit the Examples | editing the examples]].
|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.


== 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.


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 ===
Remember: your main reference for writing Objective-C code will be the {{Phidget22API}} Manual and the example code.


==== Step One: Connect====
=== Step One: Connect===
In Javascript, you must first connect to the Phidget server using the {{Code|Connection}} object.
In Javascript, you must first connect to the Phidget server using the {{Code|Connection}} object.


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


Line 259: Line 437:


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


Where {{Code|url}}, {{Code|n}}, and {{Code|p}} are variables defined elsewhere in the program. If the connection is successful, we call another function that contains the rest of our code.
Where {{Code|url}}, {{Code|n}}, and {{Code|p}} are variables defined elsewhere in the program. If the connection is successful, we call another function that contains the rest of our code.


==== Step Two: Create and Open====
=== Step Two: Create and Open===
 
After connecting, the {{Code|Open()}} function opens the software object, and 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.
After connecting, the {{Code|Open()}} function opens the software object, and 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:
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>


Line 287: Line 462:


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


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


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


Line 303: Line 476:


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


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.
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.


==== Step Three: Do Things with the Phidget ====
=== 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:
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=javascript>


Line 318: Line 489:


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


==== Step Four: Close ====
=== 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 remotely. It's not necessary to delete the object after closing in Javascript.
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 remotely. It's not necessary to delete the object after closing in Javascript.


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


Line 329: Line 498:
</syntaxhighlight>
</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 343: Line 510:
[[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 17:53, 28 June 2017

Quick Downloads

Documentation

Example Code

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.

If you are developing for Windows, keep reading. Otherwise, select your operating system to jump ahead:

Windows

If you haven't already, please visit the Windows page before you continue reading. There you will be instructed on how to properly set up your Windows machine so you can follow the guides below!

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 graphical and are installed with the Phidget libraries. In order to check them out, first open the Phidget Control Panel and navigate to the Network Server tab:

Windows networkserver.PNG


Next, make sure the Webserver is enabled (Enabled checkbox in Webserver section), and start the Phidget Network Server by clicking on the Start button at the bottom of the window. Click on the hyperlink as shown in the image below (or navigate to http://localhost:8989):

Javascript windows localhost.png


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


To view the source code that drives the examples, navigate to the following location:

  • C:/Program Files/Phidgets/Phidget22/html


Javascript windows filelocation.png


Here you can view the code that was written to create the main webpage as well as all of the examples.

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 folder that looks like this:

Javascript windows folderlibraries.png


The referenced libraries are installed with the Phidget libraries and can be found at the following location:

  • C:/Program Files/Phidgets/Phidget22/html


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

<!DOCTYPE html>
<html>
<head>
<title>Javascript Test Program</title>
<script src="jquery-2.1.4.min.js"></script>
<script src="sha256.js"></script>
<script src="jphidgets22.1.0.0.min.js"></script>

<script>

	$(document).ready(function () {
		var conn = new jPhidgets.Connection('ws://' + window.location.host + '/phidgets', { name: window.location.host });

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

		conn.onattach = function(dev) {
			$('#list').append(new Option(dev.name,dev.phid));
		}

		conn.ondetach = function(dev) {
			$("#list option[value='" + dev.phid + "']").remove();
		}
	});

</script>
</head>

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

After copying the code above into your index.html file, your folder should look like this:

Javascript windows folder.png


Next, open the Network Server tab in the Phidget Control Panel and modify the Webserver Docroot to your folders location:

Javascript windows docrootchange.png


Finally, click on the hyperlink to see the example (or navigate to http://localhost:8989):

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:


Next, navigate to the Network Server tab in the Phidget Control Panel and press the Start button after ensuring the Webserver is enabled (Enabled checkbox in Webserver section).

Windows networkserver.PNG


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.

macOS

Browser Example

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 graphical and are installed with the Phidget libraries. In order to check them out, first open the Phidget Control Panel and navigate to the Network Server tab:

Macos networkserver run.png


Next, make sure the Webserver is enabled (Enabled checkbox in Webserver section), and start the Phidget Network Server by clicking on the Start button at the top of the window. A button labelled View in Browser... will appear. Click on it now (or navigate to http://localhost:8989).

Javascript macos viewinbrowswer.png


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 macos browserexample.png


To view the source code that drives the examples, navigate to the following location:

  • /Library/Application Support/Phidgets/Phidget22NetworkServer/html


Javascript macos filelocation.png


Here you can view the code that was written to create the main webpage as well as all of the examples.

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 folder that looks like this:

Javascript macos folderlibraries.png


The referenced libraries are installed with the Phidget libraries and can be found at the following location:

  • /Library/Application Support/Phidgets/Phidget22NetworkServer/html


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

<!DOCTYPE html>
<html>
<head>
<title>Javascript Test Program</title>
<script src="jquery-2.1.4.min.js"></script>
<script src="sha256.js"></script>
<script src="jphidgets22.1.0.0.min.js"></script>

<script>

	$(document).ready(function () {
		var conn = new jPhidgets.Connection('ws://' + window.location.host + '/phidgets', { name: window.location.host });

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

		conn.onattach = function(dev) {
			$('#list').append(new Option(dev.name,dev.phid));
		}

		conn.ondetach = function(dev) {
			$("#list option[value='" + dev.phid + "']").remove();
		}
	});

</script>
</head>

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

After copying the code above into your index.html file, your folder should look like this:

Javascript macos folder.png


Next, open the Network Server tab in the Phidget Control Panel and modify the Webserver Docroot to your folders location:

Javascript macos docrootchange.png


Finally, click on the hyperlink (or navigate to http://localhost:8989) to see the example:

Javascript macos example.png


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

Javascript macos devconsole.png


For information about the Node.js example, 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:


Next, navigate to the Network Server tab in the Phidget Control Panel and press the Start Network Server button after ensuring the Webserver is enabled (Enabled checkbox in Webserver section).

Macos networkserver run.png


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

sudo npm update

Javascript macos npmupdate.png


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

node Accelerometer localhost
Javascript macos nodeexample.png


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


Linux

Browser Example

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 graphical and can be downloaded here:


After unpacking the examples, navigate to the following location:

  • /etc/phidgets


Open the file named phidget22networkserver.pc and navigate to the www section, you should see something like this:

Javacsript linux networkconfig.PNG


As you can see from the image above, our docroot location is defined as the following location:

  • /var/phidgets/www


Create the docroot location (if it doesn't exist already) and copy the contents of the example you downloaded into it by entering the following commands into the terminal:

mkdir /var/phidgets
mkdir /var/phidgets/www
cp -a YOUR_SOURCE_FOLDER/. /var/phidgets/www
Javascript linux mkdir.PNG


Now that the example code is located at the docroot location, and the Phidget Webserver is enabled (can be seen in www section of phidget22networkserver.pc), navigate to http://localhost:8080. You will see a program written with JavaScript/HTML that mimics the Phidget Control Panel (available on macOS and Windows). It will show all the Phidgets attached to your machine. By double-clicking on the Phidgets, and example will launch:

Javascript linux graphicalexample.PNG


Take a look at the source files that are now located at /var/phidgets/www

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 folder that looks like this:

Javascript linux folderlibraries.PNG


The referenced libraries can be found in the Javascript Examples (HTML) that we provide.


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

<!DOCTYPE html>
<html>
<head>
<title>Javascript Test Program</title>
<script src="jquery-2.1.4.min.js"></script>
<script src="sha256.js"></script>
<script src="jphidgets22.1.0.0.min.js"></script>

<script>

	$(document).ready(function () {
		var conn = new jPhidgets.Connection('ws://' + window.location.host + '/phidgets', { name: window.location.host });

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

		conn.onattach = function(dev) {
			$('#list').append(new Option(dev.name,dev.phid));
		}

		conn.ondetach = function(dev) {
			$("#list option[value='" + dev.phid + "']").remove();
		}
	});

</script>
</head>

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


After copying the code above into your index.html file, your folder should look like this:

link


Next, modify the phidget22networkserver.pc file that is located at /etc/phidgets. Navigate to the www section and change the docroot location to match the location of your index.html file:

Javascript linux modifydocroot.PNG


After modifying the docroot location, ensure you restart the Phidget Network Server. After restarting the Phidget Network Server, navigate to http://localhost:8080 to view the example:

Javascript linux example.PNG


Try opening the developer console for your web browser to see the Phidget JavaScript code executing and to get a better feel for the program.

Node.js

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 terminal at this location and enter the following command:

npm update
Javascript linux npmupdate.PNG


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

node Accelerometer localhost
Javascript macos 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 Objective-C 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.

function main() {

	...

	var conn = new jPhidget22.Connection(url, { name: n, passwd: p });
	conn.connect()
	  .then(runCode);
}

Where url, n, and p are variables defined elsewhere in the program. If the connection is successful, we call another function that contains the rest of our code.

Step Two: Create and Open

After connecting, the Open() function opens the software object, and 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 jPhidget22.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 object 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

ch.setState(1); // set 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 remotely. 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.