Language - JavaScript: Difference between revisions

From Phidgets Support
No edit summary
No edit summary
 
(58 intermediate revisions by 4 users not shown)
Line 1: Line 1:
<metadesc>Communicate over USB with sensors, controllers and relays with Phidgets! Our Visual Basic .NET library supports Windows using Visual Studio or Mono.</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.}}
__NOTOC__
__TOC__
We provide support for the JavaScript language for both browsers and node.js. We also provide instructions on how to get your project started in a number of common development environments. Select your operating system and preferred development environment below, and follow the instructions to get your project running with Phidgets.


== Introduction ==
General information of how to use Phidgets with JavaScript can be found in the '''Write Code''' section of each development environment page. This information is consistent across all pages.


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


Javascript is capable of using the complete {{Phidget22API}}, including events. We also provide example code in Javascript for all Phidget objects.
<div class="phd-deck-sequence">
{{PT3_JS_CHOOSE}}{{PT3_JS_ANY_BROWSER}}{{PT3_JS_ANY_NODE}}
</div>


Javascript does not require any special programming environment to write. Just use your favourite text editor to write .html and .js files.


== Quick Downloads ==
== Quick Downloads ==
 
If you already know what you're doing and just need the files, you can find them all below.
'''<span style="color:#FF0000">List of download links, to be added once files are available</span>'''


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


== Getting Started with Javascript ==
*{{Phidget22API}} (Select JavaScript from drop-down menu)


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


Instructions are divided up by operating system. Choose:
*'''Browser''': [https://cdn.phidgets.com/downloads/phidget22/libraries/any/Phidget22JavaScript.zip JavaScript Library Download]
*[[#Windows|Windows XP / Vista / 7]]
*'''Node.js''': npm install phidget22
*[[#OS X |OS X]]
*[[#Linux | Linux]] (including PhidgetSBC)


== Windows ==
=== Example Code ===
===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 {{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.
 
<<picture of network server window>>
 
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:
 
<<picture of page>>
 
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. Removing the Phidgets should cause them to disappear from the list.
 
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>
 
function readVoltage() {
 
var ch = new jPhidgets.VoltageInput();
 
ch.onVoltageChange = function (voltage) {
$('#res').text(this.getVoltage());
};
 
ch.open();
}
 
</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:
 
<div class="source">
<syntaxhighlight lang=javascript>
 
<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>
</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.
 
00000000000000000000000000000000what about VINT hub
 
== 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>
</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:
 
<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:
 
<div class="source">
<syntaxhighlight lang=CSharp>
//Code for -creating- device here....
 
device.Attach += attachEventHandler;
 
//Code for -opening- device here....
</syntaxhighlight>
</div>
 
==== Step Three: Do Things with the Phidget ====
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:
<div class="source">
<syntaxhighlight lang=csharp>
device.StateChange += input_change;
</syntaxhighlight>
</div>
 
The input_change method is defined as follows:
 
<div class="source">
<syntaxhighlight lang=csharp>
void input_change(object sender, Phidget22.Events.DigitalInputStateChangeEventArgs e) {
    textBox1.Text = "State: " + e.State;
}
</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 ==
 
[[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.
*[{{SERVER}}?view=code_samples&lang=JavaScript&os=Nodejs JavaScript Examples (Node.js)]
*[{{SERVER}}?view=code_samples&lang=JavaScript&os=Browser JavaScript Examples (Browser)]


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


[[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.
*[https://cdn.phidgets.com/downloads/phidget22/tools/any/Phidget22JavaScriptControlPanel.zip JavaScript Control Panel Source]


[[Logging, Exceptions, and Errors]] - Learn about all the tools you can use to debug your program.
=== OS Libraries ===


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

Latest revision as of 22:16, 17 October 2023


We provide support for the JavaScript language for both browsers and node.js. We also provide instructions on how to get your project started in a number of common development environments. Select your operating system and preferred development environment below, and follow the instructions to get your project running with Phidgets.

General information of how to use Phidgets with JavaScript can be found in the Write Code section of each development environment page. This information is consistent across all pages.

Setup Guide

JavaScript - Select Development Environment

Select your Development Environment:

Any OS

Language - JavaScript

JavaScript in Browser

Welcome to using Phidgets with JavaScript! By using JavaScript, you will have access to the complete Phidget22 API, including events.

Using JavaScript with a browser provides a good way to create a powerful web interface for your Phidgets programs.

Requirements

First, make sure you have the following installed:

● Phidgets Drivers on the computer that will be running the server (see Part 1 of this user guide)

● The Phidgets JavaScript Library for Browsers


Version History

1.x.x - Initial Release (unstable- highly recommend updating to 2.x.x or newer)

2.x.x - Fixed stability issues

3.x.x - Added WebUSB support for VINT devices

Each release has potential breaking changes, so you should always revisit your code when updating to a new major release.

Phidget Network Server

The Phidgets JavaScript library requires the Phidget Network Server. Go to the page below and select the tab with your OS to get the Network Server set up:

Phidget Network Server


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.

Phidget Network Server

If you're on Windows or Mac, you can enable the Webserver in the Phidget Control Panel:

If you're using Linux, you can enable it in the Network Server config file located at:

/etc/phidgets/phidget22networkserver.pc

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. (If you changed the port setting on the Webserver, replace '8989' with your selected port)

JavaScript Control Panel

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.

Use Our Examples

Now that you've confirmed the webserver is running properly by testing your Phidgets through the JavaScript Control Panel, you can try running some of our sample code:

JavaScript Browser Examples

Download the example(s) that correspond to your Phidget's channel classes. You can find them listed on the enclosure in most cases, or on the API tab of the product page.

Use Our Examples

Unpack the example and double click on the HTML file to open a simple graphical example.

If there are any issues, open the browser's developer console to see if there are any warnings or errors. If your Web Server is configured with a port or hostname other than the default (localhost, 8989), you'll have to update the code in the HTML file.

Write Your Own Code

To write your own JavaScript code, we recommend that you download one of the examples to use as a starting point. You can also start from scratch in a new HTML file- all you need is a copy of phidget22.min.js and sha256.min.js in the same folder. You can find these files packaged with our examples, or downloaded here.

What's Next?

Now that you've set up Phidgets in your programming environment, you should read our guide on Phidget Programming Basics to learn the fundamentals of programming with Phidgets.

Continue reading below for advanced information and troubleshooting for your device.

«
»

Language - JavaScript

JavaScript in Node.js

Welcome to using Phidgets with JavaScript! By using JavaScript, you will have access to the complete Phidget22 API, including events.

Node.js is an open-source, cross-platform JavaScript run-time environment that allows programs written in JavaScript to be run locally.

Requirements

First, make sure you have the following installed:

● Phidgets Drivers on the computer that will be running the server (see Part 1 of this user guide)

Node.js


Version History

1.x.x - Initial Release (unstable- highly recommend updating to 2.x.x or newer)

2.x.x - Fixed stability issues

3.x.x - Added WebUSB support for VINT devices

Each release has potential breaking changes, so you should always revisit your code when updating to a new major release.

JavaScript using the Phidget Network Server

Go to the this page and select the tab with your OS to get the Network Server set up.

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.

In order to connect remotely, you need to use the NetworkConnection object. When you download a code sample later in this guide, make sure the Remote box is checked.

JavaScript using WebUSB

For library version 3.x.x or newer, you can connect to Phidgets plugged in locally via USB without having the Network Server running. This feature is only supported on VINT Phidgets.

In order to connect using USB, you need to use the USBConnection object. When you download a code sample later in this guide, make sure the Remote box is unchecked.

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. (If you changed the port setting on the Webserver, replace '8989' with your selected port)

JavaScript Control Panel

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.

Using the Code Samples

Now that you've confirmed the webserver is running properly by testing your Phidgets through the JavaScript Control Panel, you can try running some of our sample code. On the Code Samples page and select your device from the drop-down menu.

Using the Code Samples

If it's unclear what any of the options do, click on the nearby '?' for more info.

Once you've made your selections, click the Download Example button to download a sample script.

Using the Code Samples

Next, unpack the example and open the command prompt in the folder you extracted to and enter the following commands:

npm install phidget22
npm update

Then enter the following command to run the example (replacing example.js with your example name):

node example.js

Success! Your program is now running with Phidgets.

What's Next?

Now that you've set up Phidgets in your programming environment, you should read our guide on Phidget Programming Basics to learn the fundamentals of programming with Phidgets.

Continue reading below for advanced information and troubleshooting for your device.

«
»


Quick Downloads

If you already know what you're doing and just need the files, you can find them all below.

Documentation

Libraries

Example Code

Tools

OS Libraries