### Use JavaScript API Binding

Some hints on how to use the Tinkerforge JavaScript Binding in conjunction with B4J WebApps.
Information JavaScript Binding:
http://www.tinkerforge.com/en/doc/Software/API_Bindings_JavaScript.html
TinkerForge JavaScript Binding Location
Store the TinkerForge JavaScript Binding in a www subfolder tinkerforge.
Example: www/tinkerforge/tinkerforge.js.
When referencing this binding, ensure to use the right case, e.g. TinkerForge is not equal tinkerforge in JavaScript.
JavaScript reference example:
<script src="./tinkerforge/tinkerforge.js" type='text/javascript'></script>
<script type='text/javascript'>
Get Function Value via Callback
Almost all functions in the JavaScript binding are callbacks.
Below examples show how to get a value from a function. The code is included in the html file script section.
Get ChipTemperature from Bricklet Barometer and show in a TextArea
Reference: http://www.tinkerforge.com/en/doc/Software/Bricklets/Barometer_Bricklet_JavaScript.html#barometer-bricklet-javascript-api
<script type='text/javascript'>
...
// Create device object
var b = new Tinkerforge.BrickletBarometer(UIDBAROMETER, ipcon);
...
// Define vars to capture Temperature and Pressure
var cT = 0;
var cP = 0;
// Register air pressure callback
b.on(Tinkerforge.BrickletBarometer.CALLBACK_AIR_PRESSURE,
// Callback function for air pressure callback (parameter has unit mbar/1000)
function(ap) {
cP = ap/1000;
b.getChipTemperature(
function(ap) {
cT = ap
}
);
textArea.value += 'P: '+ cP +' mbar' + ', T: ' + cT + '\n';
}
);
...
</script>
Get AirPressure and Altitude from Bricklet Barometer
Connect first. Don't use the device before ipcon is connected.
ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
function(connectReason) {
// Get current air pressure (unit is mbar/1000) and current altitude (unit is cm)
b.getAirPressure(
function(ap) {
textArea.value += 'Air pressure: '+ap/1000+' mbar\n';
},
function(error) {
textArea.value += 'Error: '+error+'\n';
}
);
b.getAltitude(
function(alt) {
textArea.value += 'Altitude: '+alt/100+' m\n';
},
function(error) {
textArea.value += 'Error: '+error+'\n';
}
);
}
);
Browser and Websockets
(Raspberry Pi)
If using the browser, ensure the websocket listen port is defined in the Brick Deamon Configuration file /etc/brickd.conf.
sudo nano /etc/brickd.conf
listen.address = 0.0.0.0
listen.plain_port = 4223
listen.websocket_port = 4280

Changed: , Category: TinkerForge, File: T6C264M1966.htm, ID: 1966