Language - JavaScript: Difference between revisions

From Phidgets Support
 
(55 intermediate revisions by 4 users not shown)
Line 1: Line 1:
{{#seo:|description=Learn how to use Phidget USB devices with JavaScript.}}
[[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.}}
==Get Started==
__TOC__
JavaScript is supported for browser and Node.js applications. Phidget devices can be accessed either directly through a [[#USB Connection | USB Connection]] or indirectly through a [[#Network Connection | Network Connection]].


== Introduction ==
==JavaScript Libraries==
 
===Browser Applications===
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.
For browser applications, you can load the library directly from UNPKG:
 
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.
 
== Quick Downloads ==
 
'''<span style="color:#FF0000">List of download links, to be added once files are available</span>'''
 
=== Documentation ===
=== Example Code ===
=== Libraries and Drivers ===
 
== Getting Started with Javascript ==
 
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:
*[[#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.
 
===Visual Studio Code===
 
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====
 
0000000000000000000000000000what will the customers see when they get the examples?
 
====Write Your Own Code====
 
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.
 
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:
 
<div class="source">
<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 () {
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>
 
</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.
 
Now, in order to test our new program we have to run it on a server.
 
==== 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}}.
 
000000000000000000000000000 Confirm paths later
 
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.
 
[[image:js_networkservice.jpg|link=]]
 
A window like the one pictured should open.
 
====Running the Program====
 
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=]]
 
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=]]
 
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>
 
conn.connect().then(function () {
console.log('connected');
readVoltage();
}).catch(function (err) {
alert('failed to connect to server:' + err);
});;
 
 
</syntaxhighlight>
</div>
 
Then, define the function just below this one, but still inside the {{Code|<script>}} tags.
 
<div class="source">
<syntaxhighlight lang=javascript>
<syntaxhighlight lang=javascript>
 
<script src="https://unpkg.com/phidget22@3.x/browser/phidget22.min.js"></script>
function readVoltage() {
 
var ch = new jPhidgets.VoltageInput();
 
ch.onVoltageChange = function (voltage) {
$('#res').text(this.getVoltage());
};
 
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.


Lastly, add a line in the HTML section that adds an element where we can change the text to match the present voltage value:
Compiled and minified library files are also available [https://www.phidgets.com/downloads/phidget22/libraries/any/Phidget22JavaScript.zip here].


<div class="source">
===Node.js Applications===
For Node.js applications, a [https://www.npmjs.com/package/phidget22 npm package] is available and can be installed with the following command:
<syntaxhighlight lang=javascript>
<syntaxhighlight lang=javascript>
 
npm install phidget22
<body>
<label> Attached Phidgets: </label>
<div>
<select multiple id="list" style="width: 500px;"></select>
</div>
<label> Voltage Input Value: </label> <label id="res"></label>
</body>
 
</syntaxhighlight>
</syntaxhighlight>
</div>


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.  
==USB Connection==
Browser and Node.js applications can access Phidget devices directly via USB.


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:
===Supported Devices===
USB connections with JavaScript are supported on Phidget devices running a PHIDUSB USB stack. To determine what USB stack your Phidget device is on, navigate to the product page and then to the specification tab, and look for the ''USB Stack'' specification. If you are using a VINT device, navigate to the product page for the VINT Hub you are using.


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


[[Image:Javascript_networkserver_webusb_spec.png|center|500px|link=https://cdn.phidgets.com/docs/images/8/80/Javascript_networkserver_webusb_spec.png]]
<br><br>


In the example code, the event functions common to all Phidgets are things like attach, detach, and error handling.
===Browser Applications===
====Supported Browsers====
In-browser USB connections are achieved through the WebUSB API. This API is currently supported by Chromium-based browsers like Google Chrome and Microsoft Edge.


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.
====JavaScript Control Panel (USB)====
|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.
You can experiment with browser-based USB applications by opening the JavaScript Phidget Control Panel:
* [https://www.phidgets.com/controlpanel phidgets.com/controlpanel]




The object provides device specific methods and properties which are available from the API for your specific Phidget.|
Click on the ''Connect USB Device'' button to give the website permission to access your device.
[{{SERVER}}/documentation/Phidget22.NET.zip .NET API]}}


=== Code Snippets ===


==== Step One: Connect====
[[Image:Javascript_networkserver_webusb_contropanel1.jpg|600px|center|link=https://cdn.phidgets.com/docs/images/9/9d/Javascript_networkserver_webusb_contropanel1.jpg]]
In Javascript, you must first connect to the Phidget server using the {{Code|Connection}} object.


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


function main() {
After granting permission, your device will be accessible from the control panel.


...
====USB Permission====
As demonstrated above, websites must request access to communicate with USB devices. This must be implemented through an interactive element, like a button. Use the '''requestWebUSBDeviceAccess''' method in the Phidget USBConnection API for this purpose.


var conn = new jPhidget22.Connection(url, { name: n, passwd: p });
[[Image:Javascript_networkserver_browser_api.png|center|500px|link=https://cdn.phidgets.com/docs/images/8/88/Javascript_networkserver_browser_api.png]]
conn.connect()
  .then(runCode);
}


</syntaxhighlight>
===Example Code===
</div>
Navigate to our [https://www.phidgets.com/?view=code_samples Code Sample Generator] to view code samples for both browser and Node.js applications that are tailored to your specific device.


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====
Make sure to '''uncheck''' the ''Remote (Network)'' box when using a direct USB connection. If you leave this box checked, your application will look for a [[#Network Connection | Network Connection]].


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.
[[Image:Javascript_networkserver_webusb_codesample.png|center|500px|link=https://cdn.phidgets.com/docs/images/5/5f/Javascript_networkserver_webusb_codesample.png]]
<br><br>


For example, if we were using an Digital Input as our device, it would look like this:
==Network Connection==
Browser and Node.js applications can connect to Phidget devices through the [[Phidget Network Server]]. In this configuration, client applications can run on machines that don't have Phidget devices physically connected to them.


<div class="source">
===Running the Phidget Network Server===
<syntaxhighlight lang=javascript>
Before starting, ensure you are [{{SERVER}}/docs/Network_Server_Guide#Running_the_Phidget_Network_Server  running the Phidget Network Server] on your host machine.
===Browser Considerations===
When using a Network Connection in a browser-based application, you must [{{SERVER}}/docs/Network_Server_Guide#Enabling_the_Webserver  enable the web server] on your host machine.


function runCode() {
====JavaScript Control Panel (Network)====
var ch = new jPhidget22.DigitalInput();
You can experiment with browser-based Network applications by opening the JavaScript Phidget Control Panel:
* If your host is a Windows or macOS machine, visit port 8989 (http://localhost:8989).
* If your host is a Linux machine, a PhidgetSBC, or a Wireless VINT Hub, visit port 8080 (http://localhost:8080).


ch.onAttach = digitalInput_attach;
If you are accessing the JavaScript Control Panel from a machine that is not the host, you will need to enter the IP address or hostname in place of localhost (e.g. http://phidgetsbc:8080).
ch.onStateChange = digitalInput_change;
 
ch.open().then(function() {
// code to execute after open succeeds
}).catch(function (err) {
// code to execute if open fails
});
 
}
 
</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 :
 
<div class="source">
<syntaxhighlight lang=javascript>
 
function digitalInput_attach(ch) {
console.log(ch + ' attached');
}
 
function digitalInput_change(state) {
console.log('state changed:' + state);
}
 
</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.
 
==== 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>
 
var di_state = ch.getState(); // get the state of the digital input
 
ch.setState(1); // set the state of the digital input
 
</syntaxhighlight>
</div>
 
==== 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.
 
<div class="source">
<syntaxhighlight lang=javascript>
 
ch.close();
</syntaxhighlight>
</div>


== 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.
[[Image:Networkserver_webserver_controlpanel.jpg|center|500px|link=https://cdn.phidgets.com/docs/images/c/c7/Networkserver_webserver_controlpanel.jpg]]


[[Data Interval/Change Trigger]] - Learn about these two properties that control how much data comes in from your sensors.
===Example Code===
Navigate to our [https://www.phidgets.com/?view=code_samples Code Sample Generator] to view code samples for both browser and Node.js applications that are tailored to your specific device.


[[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.
Make sure the '''Remote (Network)''' box is checked when using the Phidget Network Server. If you do not check this box, your example will look for a [[#USB Connection | USB Connection]].


[[Logging, Exceptions, and Errors]] - Learn about all the tools you can use to debug your program.
[[Image:Javascript_networkserver_browser_codesample.png|center|500px|link=https://cdn.phidgets.com/docs/images/5/5e/Javascript_networkserver_browser_codesample.png]]


[[Phidget Network Service]] - Phidgets can be controlled and communicated with over your network- either wirelessly or over ethernet.
==Version History==
The Phidget JavaScript Libraries version history is reviewed here:<br><br>
'''1.x.x''' - Initial release. Unstable.<br>
'''2.x.x''' - Improved stability issues.<br>
'''3.x.x''' - WebUSB support added.

Latest revision as of 19:31, 15 April 2025

Get Started

JavaScript is supported for browser and Node.js applications. Phidget devices can be accessed either directly through a USB Connection or indirectly through a Network Connection.

JavaScript Libraries

Browser Applications

For browser applications, you can load the library directly from UNPKG:

<script src="https://unpkg.com/phidget22@3.x/browser/phidget22.min.js"></script>

Compiled and minified library files are also available here.

Node.js Applications

For Node.js applications, a npm package is available and can be installed with the following command:

npm install phidget22

USB Connection

Browser and Node.js applications can access Phidget devices directly via USB.

Supported Devices

USB connections with JavaScript are supported on Phidget devices running a PHIDUSB USB stack. To determine what USB stack your Phidget device is on, navigate to the product page and then to the specification tab, and look for the USB Stack specification. If you are using a VINT device, navigate to the product page for the VINT Hub you are using.


Javascript networkserver webusb spec.png



Browser Applications

Supported Browsers

In-browser USB connections are achieved through the WebUSB API. This API is currently supported by Chromium-based browsers like Google Chrome and Microsoft Edge.

JavaScript Control Panel (USB)

You can experiment with browser-based USB applications by opening the JavaScript Phidget Control Panel:


Click on the Connect USB Device button to give the website permission to access your device.


Javascript networkserver webusb contropanel1.jpg


After granting permission, your device will be accessible from the control panel.

USB Permission

As demonstrated above, websites must request access to communicate with USB devices. This must be implemented through an interactive element, like a button. Use the requestWebUSBDeviceAccess method in the Phidget USBConnection API for this purpose.

Javascript networkserver browser api.png

Example Code

Navigate to our Code Sample Generator to view code samples for both browser and Node.js applications that are tailored to your specific device.


Make sure to uncheck the Remote (Network) box when using a direct USB connection. If you leave this box checked, your application will look for a Network Connection.

Javascript networkserver webusb codesample.png



Network Connection

Browser and Node.js applications can connect to Phidget devices through the Phidget Network Server. In this configuration, client applications can run on machines that don't have Phidget devices physically connected to them.

Running the Phidget Network Server

Before starting, ensure you are running the Phidget Network Server on your host machine.

Browser Considerations

When using a Network Connection in a browser-based application, you must enable the web server on your host machine.

JavaScript Control Panel (Network)

You can experiment with browser-based Network applications by opening the JavaScript Phidget Control Panel:

If you are accessing the JavaScript Control Panel from a machine that is not the host, you will need to enter the IP address or hostname in place of localhost (e.g. http://phidgetsbc:8080).


Networkserver webserver controlpanel.jpg

Example Code

Navigate to our Code Sample Generator to view code samples for both browser and Node.js applications that are tailored to your specific device.


Make sure the Remote (Network) box is checked when using the Phidget Network Server. If you do not check this box, your example will look for a USB Connection.

Javascript networkserver browser codesample.png

Version History

The Phidget JavaScript Libraries version history is reviewed here:

1.x.x - Initial release. Unstable.
2.x.x - Improved stability issues.
3.x.x - WebUSB support added.