No último final de semana tive a oportunidade de participar do Startup Weekend MAKER Unifei e o grupo que participei definiu como projeto uma plataforma de interação em ambiente virtual (Google Cardboard).

Essa plataforma de interação foi um Joystick construído com módulo arduino e comunicação Bluetooth.
O objetivo deste artigo é mostrar a integração do Intel XDK com comunicação Bluetooth sendo útil para aqueles que querem implantar essa forma de comunicação em suas aplicações mobile criadas através do Intel XDK.
Uso de API para Bluetooth
Para isso, usamos a API disponível em: https://github.com/don/BluetoothSerial
Descrita como “This plugin enables serial communication over Bluetooth. It was written for communicating between Android or iOS and an Arduino.”
Essa mesma API foi criada para uso do arduino com dispositivos mobile. No nosso caso o arduino utilizava um shield do módulo Bluetooth HC-05.

Inserindo API no Intel XDK
Estou usando o Intel XDK versão 3522, neste caso, com o projeto já aberto:
- Clique em “Projects”
- Vá até o panel “Cordova Hybrid Mobile APP Settings”
- Clique em “Plugin Management”
- Clique em “Add Plugins to this Project”
- Clique em “Third-Party Plugins”
- Nesta parte você pode escolher colocar o link direto do repositório GIT do projeto (link acima) e opção “Git Repo” ou então “Import Local plugin” caso tenha feito download do plugin via Github do projeto. (Para usar a opção “Git Repo” é necessário ter o GIT instalado no computador)
- Em seguida clique em “Add Plugin”

Recebendo dados Bluetooth
Voltando para a aba “Develop” do Intel XDK é necessário editar o arquivo “www/js/app.js”, sugiro então modificá-lo para o exemplo “SimpleSerial” disponível no github do projeto, confome segue:
/* SimpleSerial index.js Created 7 May 2013 Modified 9 May 2013 by Tom Igoe */ var app = { macAddress: "AA:BB:CC:DD:EE:FF", // get your mac address from bluetoothSerial.list chars: "", /* Application constructor */ initialize: function() { this.bindEvents(); console.log("Starting SimpleSerial app"); }, /* bind any events that are required on startup to listeners: */ bindEvents: function() { document.addEventListener('deviceready', this.onDeviceReady, false); connectButton.addEventListener('touchend', app.manageConnection, false); }, /* this runs when the device is ready for user interaction: */ onDeviceReady: function() { // check to see if Bluetooth is turned on. // this function is called only //if isEnabled(), below, returns success: var listPorts = function() { // list the available BT ports: bluetoothSerial.list( function(results) { app.display(JSON.stringify(results)); }, function(error) { app.display(JSON.stringify(error)); } ); } // if isEnabled returns failure, this function is called: var notEnabled = function() { app.display("Bluetooth is not enabled.") } // check if Bluetooth is on: bluetoothSerial.isEnabled( listPorts, notEnabled ); }, /* Connects if not connected, and disconnects if connected: */ manageConnection: function() { // connect() will get called only if isConnected() (below) // returns failure. In other words, if not connected, then connect: var connect = function () { // if not connected, do this: // clear the screen and display an attempt to connect app.clear(); app.display("Attempting to connect. " + "Make sure the serial port is open on the target device."); // attempt to connect: bluetoothSerial.connect( app.macAddress, // device to connect to app.openPort, // start listening if you succeed app.showError // show the error if you fail ); }; // disconnect() will get called only if isConnected() (below) // returns success In other words, if connected, then disconnect: var disconnect = function () { app.display("attempting to disconnect"); // if connected, do this: bluetoothSerial.disconnect( app.closePort, // stop listening to the port app.showError // show the error if you fail ); }; // here's the real action of the manageConnection function: bluetoothSerial.isConnected(disconnect, connect); }, /* subscribes to a Bluetooth serial listener for newline and changes the button: */ openPort: function() { // if you get a good Bluetooth serial connection: app.display("Connected to: " + app.macAddress); // change the button's name: connectButton.innerHTML = "Disconnect"; // set up a listener to listen for newlines // and display any new data that's come in since // the last newline: bluetoothSerial.subscribe('\n', function (data) { app.clear(); app.display(data); }); }, /* unsubscribes from any Bluetooth serial listener and changes the button: */ closePort: function() { // if you get a good Bluetooth serial connection: app.display("Disconnected from: " + app.macAddress); // change the button's name: connectButton.innerHTML = "Connect"; // unsubscribe from listening: bluetoothSerial.unsubscribe( function (data) { app.display(data); }, app.showError ); }, /* appends @error to the message div: */ showError: function(error) { app.display(error); }, /* appends @message to the message div: */ display: function(message) { var display = document.getElementById("message"), // the message div lineBreak = document.createElement("br"), // a line break label = document.createTextNode(message); // create the label display.appendChild(lineBreak); // add a line break display.appendChild(label); // add the message node }, /* clears the message div: */ clear: function() { var display = document.getElementById("message"); display.innerHTML = ""; } }; // end of app
Modificações Necessárias
Para o plugin funcionar com seu dispositivo Bluetooth é necessário alterar a variável macAddress com o endereço MAC do seu dispositivo.
As mensagens Bluetooth são recebidas e tratadas na função display, caso seja necessário tomar decisões, basta avaliar os valores recebidos na variável “message”.
Mais informações podem ser obtidas na página da API ou qualquer dúvida, pode entrar em contato.