Onsenui с Bluetooth-плагином

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

Я хочу создать службу, для которой требуется подключаемый модуль 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>

person condo1234    schedule 24.06.2016    source источник


Ответы (2)


Как включить этот код для использования в 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
        }
    };
person condo1234    schedule 28.06.2016

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

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

Важно отметить, что вам нужно проверить ons.ready, а затем получить доступ к вашей переменной.

person Munsterlander    schedule 27.06.2016
comment
Спасибо, это было бы полезно! - person condo1234; 28.06.2016
comment
Я хотел бы знать, как превратить пример, который я разместил выше, в код Onsenui (под моим ответом) ... Я думаю, что Bluetooth-соединение с мобильными приложениями довольно популярно, поэтому многие люди сочтут это полезным! - person condo1234; 28.06.2016
comment
Вам нужно просто отредактировать исходный пост, указав код, над которым вы хотите, чтобы мы поработали. Публикация ответа, который не является ответом, - не лучший способ поделиться информацией, поскольку она не появится при поиске. - person Munsterlander; 29.06.2016
comment
Поскольку мы обсуждаем это снаружи, для других здесь приведено полное обсуждение: community.onsen .io/topic/517/onsenui-bluetooth-tutorial - person Munsterlander; 29.06.2016