2016-06-24 7 views
1

Я пытаюсь реализовать bluetooth-плагин с помощью Onsenui в среде Monaca IDE. Я продолжаю получать сообщение об ошибке: bluetoothSerial не найден.Onsenui с плагином Bluetooth

Я хочу создать сервис, который требует плагин Bluetooth Serial. Затем просто вызовите это, чтобы выполнить вызов .isenabled(). Любая помощь будет большой.

app.service('iBeaconService', function() { 
    var bluetoothSerial = new cordova.plugins.bluetoothSerial; 

    return { 
     sendMessage: function(message) { 
      // interact with bluetoothSerial 
     } 
    }; 
}); 

app.controller('InfoPageCtrl', ['$scope', 'iBeaconService', function($scope, iBeaconService) { 
     bluetoothSerial.isEnabled(
      function() { 
       console.log("Bluetooth is enabled"); 
      }, 
      function() { 
       console.log("Bluetooth is *not* enabled"); 
      } 
     ); 
}]); 

app.controller('AppController', function($scope) { 
    $scope.load = function(page) { 
     $scope.mySplitterContent.load(page) 
    } 
    $scope.open = function() { 
     $scope.mySplitterSide.open(); 
    } 
}); 


    <ons-list ng-controller="InfoPageCtrl"> 
      <ons-list-item class="list-item-container" > 
       <ons-row> 
        <ons-col width="110px"> 
         <img src="{{beacon.icon}}" class="info-page-img"> 
        </ons-col> 
        <ons-col> 
         <div class="info-page-description"> 
          <p style="text-decoration: underline;">UUID</p> 
         {{beaconUuid}} 
        </div> 

        </ons-col> 
       </ons-row> 
      </ons-list-item> 
     </ons-list> 

ответ

0

Хорошо, извинения за задержку, но это заняло у меня немного исследований. После установки плагина с Monaca IDE и делать пользовательские сборки Android, я был в состоянии заставить его работать, используя следующий код:

ons.ready(function(){ 
     bluetoothSerial.isConnected(
      function() { 
       alert("Bluetooth is connected"); 
      }, 
      function() { 
       alert("Bluetooth is not connected"); 
      } 
     );  
    }); 

я могу опубликовать весь проект Monaca IDE для импорта, если вам нужно. Он будет содержать много другого кода из других потоков, где я помогал людям. Главное отметить, нужно проверить на ons.ready, а затем получить доступ к вашей переменной.

Удачи и надеюсь, что это поможет вам с проектом Arduino!

+0

Спасибо, что было бы полезно! – condo1234

+0

Мне хотелось бы узнать, как включить пример, который я разместил выше в коде Onsenui (ниже моего ответа) ... Я думаю, что соединение с мобильными приложениями Bluetooth очень популярно, поэтому многие люди посчитают это полезным! – condo1234

+0

Вы должны просто отредактировать свой оригинальный пост с кодом, над которым вы хотите работать. Отправка ответа, который не является ответом, - не лучший способ поделиться информацией, поскольку он не будет отображаться при поиске. – Munsterlander

0

Как включить этот код для использования Onsenui.

var app = { 
     initialize: function() { 
      this.bindEvents(); 
      this.showMainPage(); 
     }, 
     bindEvents: function() { 

      var TOUCH_START = 'touchstart'; 
      if (window.navigator.msPointerEnabled) { // windows phone 
       TOUCH_START = 'MSPointerDown'; 
      } 
      document.addEventListener('deviceready', this.onDeviceReady, false); 
      refreshButton.addEventListener(TOUCH_START, this.refreshDeviceList, false); 
      sendButton.addEventListener(TOUCH_START, this.sendData, false); 
      disconnectButton.addEventListener(TOUCH_START, this.disconnect, false); 
      deviceList.addEventListener('touchstart', this.connect, false); 
     }, 
     onDeviceReady: function() { 
      app.refreshDeviceList(); 
     }, 
     refreshDeviceList: function() { 
      bluetoothSerial.list(app.onDeviceList, app.onError); 
     }, 
     onDeviceList: function(devices) { 
      var option; 

      // remove existing devices 
      deviceList.innerHTML = ""; 
      app.setStatus(""); 

      devices.forEach(function(device) { 

       var listItem = document.createElement('li'), 
        html = '<b>' + device.name + '</b><br/>' + device.id; 

       listItem.innerHTML = html; 

       if (cordova.platformId === 'windowsphone') { 
        // This is a temporary hack until I get the list tap working 
        var button = document.createElement('button'); 
        button.innerHTML = "Connect"; 
        button.addEventListener('click', app.connect, false); 
        button.dataset = {}; 
        button.dataset.deviceId = device.id; 
        listItem.appendChild(button); 
       } else { 
        listItem.dataset.deviceId = device.id; 
       } 
       deviceList.appendChild(listItem); 
      }); 

      if (devices.length === 0) { 

       option = document.createElement('option'); 
       option.innerHTML = "No Bluetooth Devices"; 
       deviceList.appendChild(option); 

       if (cordova.platformId === "ios") { // BLE 
        app.setStatus("No Bluetooth Peripherals Discovered."); 
       } else { // Android or Windows Phone 
        app.setStatus("Please Pair a Bluetooth Device."); 
       } 

      } else { 
       app.setStatus("Found " + devices.length + " device" + (devices.length === 1 ? "." : "s.")); 
      } 

     }, 
     connect: function(e) { 
      var onConnect = function() { 
        // subscribe for incoming data 
        bluetoothSerial.subscribe('\n', app.onData, app.onError); 

        resultDiv.innerHTML = ""; 
        app.setStatus("Connected"); 
        app.showDetailPage(); 
       }; 

      var deviceId = e.target.dataset.deviceId; 
      if (!deviceId) { // try the parent 
       deviceId = e.target.parentNode.dataset.deviceId; 
      } 

      bluetoothSerial.connect(deviceId, onConnect, app.onError); 
     }, 
     onData: function(data) { // data received from Arduino 
      console.log(data); 
      resultDiv.innerHTML = resultDiv.innerHTML + "Received: " + data + "<br/>"; 
      resultDiv.scrollTop = resultDiv.scrollHeight; 
     }, 
     sendData: function(event) { // send data to Arduino 

      var success = function() { 
       console.log("success"); 
       resultDiv.innerHTML = resultDiv.innerHTML + "Sent: " + messageInput.value + "<br/>"; 
       resultDiv.scrollTop = resultDiv.scrollHeight; 
      }; 

      var failure = function() { 
       alert("Failed writing data to Bluetooth peripheral"); 
      }; 

      var data = messageInput.value; 
      bluetoothSerial.write(data, success, failure); 
     }, 
     disconnect: function(event) { 
      bluetoothSerial.disconnect(app.showMainPage, app.onError); 
     }, 
     showMainPage: function() { 
      mainPage.style.display = ""; 
      detailPage.style.display = "none"; 
     }, 
     showDetailPage: function() { 
      mainPage.style.display = "none"; 
      detailPage.style.display = ""; 
     }, 
     setStatus: function(message) { 
      console.log(message); 

      window.clearTimeout(app.statusTimeout); 
      statusDiv.innerHTML = message; 
      statusDiv.className = 'fadein'; 

      // automatically clear the status with a timer 
      app.statusTimeout = setTimeout(function() { 
       statusDiv.className = 'fadeout'; 
      }, 5000); 
     }, 
     onError: function(reason) { 
      alert("ERROR: " + reason); // real apps should use notification.alert 
     } 
    };