|
|
(24 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. |
|
| |
|
| === Documentation === | | === Documentation === |
|
| |
|
| *{{Phidget22API}} (Select Javascript from drop-down menu) | | *{{Phidget22API}} (Select JavaScript from drop-down menu) |
|
| |
|
| === Example Code === | | === Libraries === |
|
| |
|
| *{{SampleCode|JavaScript|JavaScript Examples (Node.js)}} | | *'''Browser''': [https://cdn.phidgets.com/downloads/phidget22/libraries/any/Phidget22JavaScript.zip JavaScript Library Download] |
| *[{{SERVER}}/downloads/phidget22/tools/any/Phidget22JavaScriptControlPanel.zip Javascript Examples (HTML)]
| | *'''Node.js''': npm install phidget22 |
|
| |
|
| === Libraries and Drivers === | | === Example Code === |
|
| |
|
| *[{{SERVER}}/downloads/phidget22/libraries/any/Phidget22JavaScript.zip JavaScript Library Download] | | *[{{SERVER}}?view=code_samples&lang=JavaScript&os=Nodejs JavaScript Examples (Node.js)] |
| {{AllQuickDownloads}} | | *[{{SERVER}}?view=code_samples&lang=JavaScript&os=Browser JavaScript Examples (Browser)] |
|
| |
|
| == Getting Started with Javascript == | | === Tools === |
|
| |
|
| If you are new to writing code for Phidgets, we recommend starting by running, then modifying existing examples. This will allow you to:
| | *[https://cdn.phidgets.com/downloads/phidget22/tools/any/Phidget22JavaScriptControlPanel.zip JavaScript Control Panel Source] |
| {{ExampleCodeReasons}}
| |
|
| |
|
| Instructions are divided up by operating system. Choose:
| | === OS Libraries === |
| *[[#Windows|Windows XP / Vista / 7]]
| |
| *[[#OS X |OS X]]
| |
| *[[#Linux | Linux]] (including PhidgetSBC)
| |
|
| |
|
| == Windows ==
| | {{AllQuickDownloads}} |
| ===Description of Library Files===
| |
| Javascript programs depend on the following files, which the installers above put onto your system:
| |
| | |
| *'''jphidgets22.x.x.x.min.js''' is the Javascript library for Phidget22. The x's in the filename denote the version of the library.
| |
| | |
| ===Browser Example (Visual Studio Code)===
| |
| | |
| 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====
| |
| | |
| 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 from the example of your choice 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====
| |
| | |
| 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:
| |
| | |
| <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>
| |
| | |
| 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}}.
| |
| | |
| 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:
| |
| | |
| <syntaxhighlight lang=javascript>
| |
| | |
| conn.connect().then(function () {
| |
| console.log('connected');
| |
| readVoltage();
| |
| }).catch(function (err) {
| |
| alert('failed to connect to server:' + err);
| |
| });;
| |
| | |
| | |
| </syntaxhighlight>
| |
| | |
| Then, define the function just below this one, but still inside the {{Code|<script>}} tags.
| |
| | |
| <syntaxhighlight lang=javascript>
| |
| | |
| function readVoltage() {
| |
| | |
| var ch = new jPhidgets.VoltageInput();
| |
| | |
| ch.onVoltageChange = function (voltage) {
| |
| $('#res').text(this.getVoltage());
| |
| };
| |
| | |
| ch.open();
| |
| }
| |
| | |
| </syntaxhighlight>
| |
| | |
| 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:
| |
| | |
| <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>
| |
| | |
| 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 {{VINTHub}} port, you would have to add the following two lines just before the {{Code|open()}} call:
| |
| | |
| <syntaxhighlight lang=javascript>
| |
| ch.setHubPort(0); // open hub port 0
| |
| ch.setIsHubPort(true);
| |
| </syntaxhighlight>
| |
| | |
| ===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.
| |
| | |
| You can download our Javascript examples [[#Quick Downloads|here]].
| |
| | |
| In the command prompt, navigate to the folder that contains the Phidgets Javascript examples. There, type the following command:
| |
| | |
| {{Code|npm update}}
| |
| | |
| This will cause the package manager to look at {{Code|package.json}} and update the Phidgets libraries.
| |
| | |
| ====Use Our Examples====
| |
| | |
| 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=]]
| |
| | |
| In the other command prompt window, navigate to the folder that contains the Phidgets Javascript examples and type
| |
| | |
| {{Code|node <example> <address>}}
| |
| | |
| 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 localhost}}
| |
| | |
| This should result in a simple text-based example to be launched:
| |
| | |
| [[image:js_nodeexample.jpg|link=]]
| |
| | |
| ====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 {{Code|runExample()}} function to suit your needs:
| |
| | |
| # Change {{Code|jPhidget22.VoltageInput}} to the object you want to open.
| |
| # Set new handlers for this channel (for example, {{Code|ch.onIlluminanceChange}} if you're using a light sensor).
| |
| # Set new parameters to open a specific channel (for example, {{Code|ch.setDeviceSerialNumber()}} or {{Code|ch.setIsHubPort()}}).
| |
| # You can open multiple channels by declaring different variables for each one and repeating the same process of assigning handlers and calling {{Code|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 [[#Quick Downloads|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 [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.
| |
| | |
| Download our Javascript examples [[#Quick Downloads|here]].
| |
| | |
| In the terminal, navigate to the folder that contains the Phidgets Javascript examples. There, type the following command:
| |
| | |
| {{Code|npm update}}
| |
| | |
| This will cause the package manager to look at {{Code|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
| |
| | |
| {{Code|node <example> <address>}}
| |
| | |
| 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 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 {{Phidget22API}} 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 {{Code|Connection}} object.
| |
| | |
| <syntaxhighlight lang=javascript>
| |
| | |
| function main() {
| |
| | |
| ...
| |
| | |
| var conn = new jPhidget22.Connection(url, { name: n, passwd: p });
| |
| conn.connect()
| |
| .then(runCode);
| |
| }
| |
| | |
| </syntaxhighlight>
| |
| | |
| 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====
| |
| | |
| 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:
| |
| | |
| <syntaxhighlight lang=javascript>
| |
| | |
| 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
| |
| });
| |
| | |
| }
| |
| | |
| </syntaxhighlight>
| |
| | |
| 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 :
| |
| | |
| <syntaxhighlight lang=javascript>
| |
| | |
| function digitalInput_attach(ch) {
| |
| console.log(ch + ' attached');
| |
| }
| |
| | |
| function digitalInput_change(state) {
| |
| console.log('state changed:' + state);
| |
| }
| |
| | |
| </syntaxhighlight>
| |
| | |
| 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:
| |
| | |
| <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>
| |
| | |
| ==== 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.
| |
| | |
| <syntaxhighlight lang=javascript>
| |
| | |
| ch.close();
| |
|
| |
| </syntaxhighlight>
| |
| | |
| == 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.
| |