Language - JavaScript: Difference between revisions
No edit summary |
|||
Line 1: | Line 1: | ||
[[Category:Language]] | [[Category:Language]] | ||
__TOC__ | __TOC__ | ||
== Quick Downloads == | == Quick Downloads == | ||
=== Documentation === | === Documentation === | ||
*{{Phidget22API}} (Select | *{{Phidget22API}} (Select JavaScript from drop-down menu) | ||
=== Example Code === | === Example Code === | ||
Line 22: | Line 12: | ||
*[{{SERVER}}/downloads/phidget22/tools/any/Phidget22JavaScriptControlPanel.zip Javascript Examples (HTML)] | *[{{SERVER}}/downloads/phidget22/tools/any/Phidget22JavaScriptControlPanel.zip Javascript Examples (HTML)] | ||
=== Libraries | === Libraries === | ||
*[{{SERVER}}/downloads/phidget22/libraries/any/Phidget22JavaScript.zip JavaScript Library Download] | *[{{SERVER}}/downloads/phidget22/libraries/any/Phidget22JavaScript.zip JavaScript Library Download] | ||
{{AllQuickDownloads}} | {{AllQuickDownloads}} | ||
== Getting Started with | == 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}} | |||
===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]] | |||
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 (or navigate to http://localhost:8989) as shown in the image below: | |||
[[File:Javascript_windows_localhost.png|link=|center]] | |||
You will now see a program that mimics the Phidget Control Panel (and was written entirely with JavaScript/HTML). 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]] | |||
* | To view the source code, navigate to the following location: | ||
*C:/Program Files/Phidgets/Phidget22/html | |||
[[File:Javascript_windows_filelocation.png|link=|center]] | |||
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==== | ====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_windows_folderlibraries.png|link=|center]] | |||
As stated above, you must download the jQuery library. The rest of the 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): | |||
<syntaxhighlight lang=javascript> | <syntaxhighlight lang=javascript> | ||
<!DOCTYPE html> | <!DOCTYPE html> | ||
<html> | <html> | ||
<head> | <head> | ||
<title>Javascript Test Program</title> | <title>Javascript Test Program</title> | ||
<script src="jquery-2.1 | <script src="jquery-3.2.1.min.js"></script> | ||
<script src="sha256.js"></script> | <script src="sha256.js"></script> | ||
<script src="jphidgets22.1.0.0.min.js"></script> | <script src="jphidgets22.1.0.0.min.js"></script> | ||
Line 101: | Line 107: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
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 (or navigate to http://localhost:8989) to see the example: | |||
[[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 example, keep reading. Otherwise, skip ahead to the [[#Edit the Examples | edit the examples]] section located below. | |||
=== | ===Node.js=== | ||
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. | 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. |
Revision as of 18:40, 23 June 2017
Quick Downloads
Documentation
- Phidget22 API (Select JavaScript from drop-down menu)
Example Code
Libraries
- Windows Drivers Installer (32-Bit)
- Windows Drivers Installer (64-Bit)
- Windows Development Libraries
- macOS Installer
- Linux Libraries
- Linux Phidget Network Server
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:
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 (or navigate to http://localhost:8989) as shown in the image below:
You will now see a program that mimics the Phidget Control Panel (and was written entirely with JavaScript/HTML). It will show all the Phidgets attached to your machine. By double-clicking on the Phidgets, and example will launch:
To view the source code, navigate to the following location:
- C:/Program Files/Phidgets/Phidget22/html
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:
As stated above, you must download the jQuery library. The rest of the 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-3.2.1.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:
Next, open the Network Server tab in the Phidget Control Panel and modify the Webserver Docroot to your folders location:
Finally, click on the hyperlink (or navigate to http://localhost:8989) to see the example:
Open the developer console to get a better idea what is going on:
For information about the Node.js example, keep reading. Otherwise, skip ahead to the edit the examples section located below.
Node.js
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 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.
You can download our Javascript examples here.
In the command prompt, navigate to the folder that contains the Phidgets Javascript examples. There, type the following command:
npm update
This will cause the package manager to look at package.json
and update the Phidgets libraries.
Use Our Examples
To run the examples, go to C:\Program Files\Phidgets\Phidget22\
and run NetworkServer.exe
. A window like the one below should open:
In the other command prompt window, navigate to the folder that contains the Phidgets Javascript examples and type
node <example> <address>
where <example>
is the filename of the example you want to run (i.e. DigitalInput.js) and <address>
is the address of the Phidget server. In our case, it will be "localhost" because we're hosting it on the same computer:
node DigitalInput localhost
This should result in a simple text-based example to be launched:
Write Your Own Code
After testing with our node.js examples, it will be easy for you to write your own programs. Open up one of the examples and edit the runExample()
function to suit your needs:
- Change
jPhidget22.VoltageInput
to the object you want to open. - Set new handlers for this channel (for example,
ch.onIlluminanceChange
if you're using a light sensor). - Set new parameters to open a specific channel (for example,
ch.setDeviceSerialNumber()
orch.setIsHubPort()
). - You can open multiple channels by declaring different variables for each one and repeating the same process of assigning handlers and calling
open()
on the channel. - Edit the contents of the event handlers to do different things with the data. Instead of printing the data to console, you could log it to a .csv file, or perform custom processing on the data (i.e. rolling average).
When you're done writing your program, you'll be able to run it in the same way as described in the previous section.
OS X
Browser Example (Visual Studio Code)
node.js
Linux
Browser Example
Download our Javascript libraries here and follow the instructions in the README to get in-browser Javascript running.
node.js
node.js is a Javascript runtime that will allow us to run Javascript code via the terminal. Download the latest version of node.js 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.
Download our Javascript examples here.
In the terminal, navigate to the folder that contains the Phidgets Javascript examples. There, type the following command:
npm update
This will cause the package manager to look at package.json
and update the Phidgets libraries.
Follow the README in the Javascript libraries to get the Phidget network server running.
In the terminal, navigate to the folder that contains the Phidgets Javascript examples and type
node <example> <address>
where <example>
is the filename of the example you want to run (i.e. DigitalInput.js) and <address>
is the address of the Phidget server. In our case, it will be "localhost" because we're hosting it on the same computer:
node DigitalInput localhost
This should result in a simple text-based example to be launched inside the terminal.
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 Javascript code will be the Phidget22 API Manual. The following code snippets will also provide a quick reference on how to do specific tasks in Javascript.
Code Snippets
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.