Language - JavaScript: Difference between revisions
(version 2) |
|||
Line 1: | Line 1: | ||
<metadesc>Communicate | <metadesc>Communicate with sensors, controllers and relays with Phidgets! Our JavaScript API supports Node.js and Browsers.</metadesc> | ||
[[Category:Language]] | [[Category:Language]] | ||
__TOC__ | __TOC__ | ||
Line 7: | Line 7: | ||
*{{Phidget22API}} (Select JavaScript from drop-down menu) | *{{Phidget22API}} (Select JavaScript from drop-down menu) | ||
=== Libraries === | |||
*'''Browser''': [{{SERVER}}/downloads/phidget22/libraries/any/Phidget22JavaScript.zip JavaScript Library Download] | |||
*'''Node.js''': npm install phidget22 | |||
=== Example Code === | === Example Code === | ||
*{{ | *[{{SERVER}}?view=code_samples&lang=JavaScript&os=Nodejs JavaScript Examples (Node.js)] | ||
*[{{SERVER}} | *[{{SERVER}}?view=code_samples&lang=JavaScript&os=Browser JavaScript Examples (Browser)] | ||
=== Tools === | |||
=== Libraries === | *[{{SERVER}}/downloads/phidget22/tools/any/Phidget22JavaScriptControlPanel.zip JavaScript Control Panel Source] | ||
=== OS Libraries === | |||
{{AllQuickDownloads}} | {{AllQuickDownloads}} | ||
Line 21: | Line 29: | ||
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. | 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. | ||
=== Version Change === | |||
'''Note:''' The Phidgets JavaScript library has been bumped to version 2.x.x following a rewrite. The version 2 API is mostly identical to version 1, but does have some breaking changes. It is highly recommended that any code written against version 1 be updated to version 2, as version 1 is considered unstable. | |||
== Phidget Network Server == | |||
The JavaScript library requires the [[Phidget Network Server]]. Start by configuring the server for your OS: | |||
* [[OS - Windows#Phidget Network Server|Windows]] | |||
* [[OS - OS X#Phidget Network Server|macOS]] | |||
* [[OS - Linux#Phidget Network Server|Linux]] | |||
* [[OS - Phidget SBC#Phidget Network Server|PhidgetSBC]] | |||
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. | |||
== 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 [{{SERVER}}/downloads/phidget22/tools/any/Phidget22JavaScriptControlPanel.zip here]. | |||
Make sure the Phidget Server - Webserver is enabled, and running, then navigate to http://localhost:8989. 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]] | [[File:Javascript_windows_controlpanel.png|link=|center]] | ||
== 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 available [{{SERVER}}?view=code_samples&lang=JavaScript&os=Browser here]. | |||
=== 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. | 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. | 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 empty folder. | |||
Next, download the latest JavaScript browser library from [{{SERVER}}/downloads/phidget22/libraries/any/Phidget22JavaScript.zip here] and copy the files into the folder. | |||
[ | |||
Next, create a file called ''index.html'' and copy the following code into it (Note: if you have a newer jQuery, modify the code below to match your version): | |||
Next, create a file called ''index.html'' and copy the following code into it (Note: if you have newer | |||
<syntaxhighlight lang=javascript> | <syntaxhighlight lang=javascript> | ||
Line 70: | Line 69: | ||
<html> | <html> | ||
<head> | <head> | ||
<title> | <title>Phidget Manager</title> | ||
<script src="jquery-2.1.4.min.js"></script> | <script src="jquery-2.1.4.min.js"></script> | ||
<script src="sha256.js"></script> | <script src="sha256.min.js"></script> | ||
<script src=" | <script src="phidget22.min.js"></script> | ||
<script> | |||
<script> | $(document).ready(function() { | ||
var conn = new phidget22.Connection(8989, 'localhost'); | |||
conn.connect().then(function() { | |||
console.log('connected'); | |||
}).catch(function(err) { | |||
conn.delete(); | |||
alert('failed to connect to server:' + err); | |||
}); | |||
var man = new phidget22.Manager({ | |||
onDeviceAttach: function(dev) { | |||
$('#list').append(new Option(dev.getDeviceName(), dev.getKey())); | |||
}, | |||
onDeviceDetach: function(dev) { | |||
$("#list option[value='" + dev.getKey() + "']").remove(); | |||
} | |||
}); | |||
man.open(); | |||
}); | |||
</script> | |||
</script> | |||
</head> | </head> | ||
<body> | <body> | ||
<label> Attached Phidgets: </label> | |||
<div> | |||
<select multiple id="list" style="width: 500px; height: 200px"></select> | |||
</div> | |||
</body> | </body> | ||
</html> | </html> | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Finally, double click index.html to open it in a browser. You should see something like this: | |||
[[File:Javascript_windows_example.png|link=|center]] | [[File:Javascript_windows_example.png|link=|center]] | ||
Open the developer console to get a better idea what is going on: | Open the developer console to get a better idea what is going on: | ||
[[File:Javascript_windows_devconsole.png|link=|center]] | [[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. | 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]. | 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: | Now that you have Node.js installed, select an example that will work with your Phidget: | ||
*{{ | *[{{SERVER}}?view=code_samples&lang=JavaScript&os=Nodejs JavaScript Examples (Node.js)] | ||
Navigate to the example folder that you previously downloaded, open the command prompt at this location and enter the following command: | Navigate to the example folder that you previously downloaded, open the command prompt at this location and enter the following command: | ||
Line 146: | Line 127: | ||
[[File:Javascript_windows_npmupdate.png]] | [[File:Javascript_windows_npmupdate.png]] | ||
Next, enter the following command to run the example (replacing Accelerometer with your example name): | Next, enter the following command to run the example (replacing Accelerometer with your example name): | ||
Line 153: | Line 133: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
[[File:Javacsript_windows_nodeexample.png|link=|center]] | [[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]]. | You should now have the example up and running. When you are ready, the next step is [[#Edit the Examples | editing the examples]]. | ||
Line 422: | Line 139: | ||
=== 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. Have a look at the Connection API for more details: {{Phidget22API}} -> Select JavaScript then select Connection API. | ||
<syntaxhighlight lang=javascript> | <syntaxhighlight lang=javascript> | ||
function main() { | function main() { | ||
var conn = new phidget22.Connection(5661, 'localhost'); | |||
conn.connect().then(function () { | |||
console.log("Connected"); | |||
runCode(); | |||
}).catch(function (err) { | |||
console.error("Failed to connect", err); | |||
}); | |||
} | } | ||
</syntaxhighlight> | |||
Once a connection has been established, it will stay active until it is closed, even across network outages and server restarts. | |||
Multiple Connections can be created and connected at once. Any opened Phidget or Manager objects will match against devices on all connections. | |||
=== Step Two: Create and Open=== | === Step Two: Create and Open=== | ||
After connecting, the {{Code| | After connecting, create a new channel object of the correct channel class, then call the {{Code|open()}} function to open the channel. 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: | ||
Line 447: | Line 165: | ||
function runCode() { | function runCode() { | ||
var ch = new phidget22.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> | </syntaxhighlight> | ||
Once the | Once the channel 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> | <syntaxhighlight lang=javascript> | ||
function digitalInput_attach(ch) { | function digitalInput_attach(ch) { | ||
console.log(ch + ' attached'); | |||
} | } | ||
function digitalInput_change(state) { | function digitalInput_change(state) { | ||
console.log('state changed:' + state); | |||
} | } | ||
Line 484: | Line 201: | ||
var di_state = ch.getState(); // get the state of the digital input | var di_state = ch.getState(); // get the state of the digital input | ||
</syntaxhighlight> | </syntaxhighlight> | ||
=== 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 | 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 via the Phidget Server. It's not necessary to delete the object after closing in Javascript. | ||
<syntaxhighlight lang=javascript> | <syntaxhighlight lang=javascript> |
Revision as of 23:56, 7 March 2018
Quick Downloads
Documentation
- Phidget22 API (Select JavaScript from drop-down menu)
Libraries
- Browser: JavaScript Library Download
- Node.js: npm install phidget22
Example Code
Tools
OS 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.
Version Change
Note: The Phidgets JavaScript library has been bumped to version 2.x.x following a rewrite. The version 2 API is mostly identical to version 1, but does have some breaking changes. It is highly recommended that any code written against version 1 be updated to version 2, as version 1 is considered unstable.
Phidget Network Server
The JavaScript library requires the Phidget Network Server. Start by configuring the server for your OS:
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.
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. 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.
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 available here.
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 empty folder.
Next, download the latest JavaScript browser library from here and copy the files into the folder.
Next, create a file called index.html and copy the following code into it (Note: if you have a newer jQuery, modify the code below to match your version):
<!DOCTYPE html>
<html>
<head>
<title>Phidget Manager</title>
<script src="jquery-2.1.4.min.js"></script>
<script src="sha256.min.js"></script>
<script src="phidget22.min.js"></script>
<script>
$(document).ready(function() {
var conn = new phidget22.Connection(8989, 'localhost');
conn.connect().then(function() {
console.log('connected');
}).catch(function(err) {
conn.delete();
alert('failed to connect to server:' + err);
});
var man = new phidget22.Manager({
onDeviceAttach: function(dev) {
$('#list').append(new Option(dev.getDeviceName(), dev.getKey()));
},
onDeviceDetach: function(dev) {
$("#list option[value='" + dev.getKey() + "']").remove();
}
});
man.open();
});
</script>
</head>
<body>
<label> Attached Phidgets: </label>
<div>
<select multiple id="list" style="width: 500px; height: 200px"></select>
</div>
</body>
</html>
Finally, double click index.html to open it in a browser. You should see something like this:
Open the developer console to get a better idea what is going on:
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:
Navigate to the example folder that you previously downloaded, open the command prompt at this location and enter the following command:
npm update
Next, enter the following command to run the example (replacing Accelerometer with your example name):
node Accelerometer localhost
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 JavaScript 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. Have a look at the Connection API for more details: Phidget22 API -> Select JavaScript then select Connection API.
function main() {
var conn = new phidget22.Connection(5661, 'localhost');
conn.connect().then(function () {
console.log("Connected");
runCode();
}).catch(function (err) {
console.error("Failed to connect", err);
});
}
Once a connection has been established, it will stay active until it is closed, even across network outages and server restarts.
Multiple Connections can be created and connected at once. Any opened Phidget or Manager objects will match against devices on all connections.
Step Two: Create and Open
After connecting, create a new channel object of the correct channel class, then call the open()
function to open the channel. 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 phidget22.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 channel 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
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 via the Phidget Server. 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.