블루투스

이 문서에서는 블루투스, 블루투스 소켓저전력 블루투스 API를 사용하여 블루투스 및 저전력 블루투스 기기와 통신하는 방법을 설명합니다.

블루투스에 대한 배경 정보는 공식 블루투스 사양을 참조하세요.

매니페스트 요구사항

블루투스를 사용하는 Chrome 앱의 경우 매니페스트에 bluetooth 항목을 추가하고, 해당하는 경우 구현하려는 프로필, 프로토콜 또는 서비스의 UUID와 소켓 또는 저전력 API로 구현할지 여부를 지정합니다.

소켓 구현의 예는 다음과 같습니다.

"bluetooth": {
  "uuids": [ "1105", "1106" ],
  "socket": true
}

저전력 구현의 경우:

"bluetooth": {
  "uuids": [ "180D", "1809", "180F" ],
  "low_energy": true
}

어댑터 상태에만 액세스하고, 근처 기기를 찾고, 기기에 관한 기본 정보를 가져오려면 항목만 있으면 됩니다.

"bluetooth": {}

어댑터 정보

어댑터 상태 가져오기

블루투스 어댑터의 상태를 가져오려면 bluetooth.getAdapterState 메서드를 사용합니다.

chrome.bluetooth.getAdapterState(function(adapter) {
  console.log("Adapter " + adapter.address + ": " + adapter.name);
});

어댑터 알림

어댑터 상태가 변경될 때마다 bluetooth.onAdapterStateChanged 이벤트가 전송됩니다. 예를 들어, 이는 어댑터 라디오의 전원이 켜지거나 꺼지는 시점을 확인하는 데 사용할 수 있습니다.

var powered = false;
chrome.bluetooth.getAdapterState(function(adapter) {
  powered = adapter.powered;
});

chrome.bluetooth.onAdapterStateChanged.addListener(
  function(adapter) {
    if (adapter.powered != powered) {
      powered = adapter.powered;
      if (powered) {
        console.log("Adapter radio is on");
      } else {
        console.log("Adapter radio is off");
      }
    }
  });

기기 정보입니다.

알려진 기기 나열 중

블루투스 어댑터에 알려진 기기 목록을 가져오려면 bluetooth.getDevices 메서드를 사용하세요.

chrome.bluetooth.getDevices(function(devices) {
  for (var i = 0; i < devices.length; i++) {
    console.log(devices[i].address);
  }
});

페어링된 기기 및 최근에 발견된 기기를 비롯한 모든 기기가 반환됩니다. 새 기기 검색은 시작하지 않습니다 (주변 기기 검색 참고).

기기 알림 수신

bluetooth.getDevices를 반복적으로 호출하는 대신 bluetooth.onDeviceAdded, bluetooth.onDeviceChangedbluetooth.onDeviceRemoved 이벤트를 사용하여 알림을 수신할 수 있습니다.

어댑터에서 기기를 검색하거나 어댑터에 연결할 때마다 bluetooth.onDeviceAdded 이벤트가 전송됩니다.

chrome.bluetooth.onDeviceAdded.addListener(function(device) {
  console.log(device.address);
});

이 이벤트에 리스너를 추가해도 기기 검색이 시작되지는 않습니다 (주변 기기 검색 참고).

이전에 발견된 기기가 페어링되는 등의 기기 변경사항은 bluetooth.onDeviceChanged 이벤트를 통해 알림을 받습니다.

chrome.bluetooth.onDeviceChanged.addListener(function(device) {
  console.log(device.address);
});

마지막으로 페어링된 기기가 시스템에서 삭제되거나 검색된 기기가 최근에 확인되지 않을 때마다 bluetooth.onDeviceRemoved 이벤트가 전송됩니다.

chrome.bluetooth.onDeviceRemoved.addListener(function(device) {
  console.log(device.address);
});

근처 기기 검색 중

근처 기기 검색을 시작하려면 bluetooth.startDiscovery 메서드를 사용합니다. 검색은 리소스를 많이 사용할 수 있으므로 완료되면 bluetooth.stopDiscovery를 호출해야 합니다.

앱이 근처 기기를 검색해야 할 때마다 bluetooth.startDiscovery를 호출해야 합니다. bluetooth.AdapterStatediscovering 속성을 조건부로 호출하지 않습니다. 이 호출은 다른 앱이 근처 기기를 검색하는 경우에도 성공하며, 다른 앱이 중지된 후에도 어댑터가 계속 검색을 실행합니다.

새로 검색된 각 기기에 관한 정보는 bluetooth.onDeviceAdded 이벤트를 사용하여 수신합니다. 최근에 이미 검색되었거나 이전에 페어링되었거나 연결된 기기의 경우 이벤트가 전송되지 않습니다. 대신 bluetooth.getDevices를 호출하여 현재 정보를 가져오고 bluetooth.onDeviceChanged 이벤트를 사용하여 탐색의 결과로 해당 정보가 변경된 경우 알림을 받아야 합니다.

예:

var device_names = {};
var updateDeviceName = function(device) {
  device_names[device.address] = device.name;
};
var removeDeviceName = function(device) {
  delete device_names[device.address];
}

// Add listeners to receive newly found devices and updates
// to the previously known devices.
chrome.bluetooth.onDeviceAdded.addListener(updateDeviceName);
chrome.bluetooth.onDeviceChanged.addListener(updateDeviceName);
chrome.bluetooth.onDeviceRemoved.addListener(removeDeviceName);

// With the listeners in place, get the list of devices found in
// previous discovery sessions, or any currently active ones,
// along with paired devices.
chrome.bluetooth.getDevices(function(devices) {
  for (var i = 0; i < devices.length; i++) {
    updateDeviceName(devices[i]);
  }
});

// Now begin the discovery process.
chrome.bluetooth.startDiscovery(function() {
  // Stop discovery after 30 seconds.
  setTimeout(function() {
    chrome.bluetooth.stopDiscovery(function() {});
  }, 30000);
});

사용자가 블루투스 무선 기능을 끄면 무선 기능이 켜졌을 때 모든 검색 세션이 종료되고 자동으로 재개되지 않습니다. 앱에 중요한 경우 bluetooth.onAdapterStateChanged 이벤트를 관찰해야 합니다. discovering 속성이 false로 변경되면 앱에서 bluetooth.startDiscovery를 다시 호출하여 재개해야 합니다. 리소스 집약적인 검색 특성에 주의하세요.

기기 식별

bluetooth.getDevices 및 관련 이벤트를 통해 반환된 기기를 식별하기 위한 다양한 옵션이 제공됩니다.

기기에서 블루투스 기기 ID 사양을 지원하면 해당 사양에서 정의한 필드가 포함된 여러 속성이 기기 객체에 추가됩니다. 예:

chrome.bluetooth.getDevices(function(devices) {
  for (var i = 0; i < devices.length; i++) {
    if (devices[0].vendorIdSource != undefined) {
      console.log(devices[0].address + ' = ' +
                  devices[0].vendorIdSource + ':' +
                  devices[0].vendorId.toString(16) + ':' +
                  devices[0].productId.toString(16) + ':' +
                  devices[0].deviceId.toString(16));
    }
  }
});

일반적으로 기기 ID 사양으로 공급업체가 제공한 기기의 특정 모델과 버전까지도 충분히 식별할 수 있습니다. 이 속성이 없는 경우 대신 기기의 클래스 또는 유형에 관한 정보를 사용해야 하며 선택적으로 address의 제조업체 접두사와 결합해야 합니다.

대부분의 블루투스 기기는 기기 클래스 정보를 베이스밴드 할당 번호 문서에 따라 해석되는 비트 필드로 제공합니다. 이 비트 필드는 deviceClass 속성에서 사용할 수 있습니다.

chrome.bluetooth.getDevices(function(devices) {
  for (var i = 0; i < devices.length; i++) {
    if (devices[0].vendorIdSource != undefined) {
      console.log(devices[0].address + ' = ' +
                  devices[0].deviceClass.toString(16));
    }
  }
});

필드 파싱은 복잡할 수 있으므로 가장 일반적인 기기 유형의 경우 Chrome에서 이를 처리하고 type 필드를 설정합니다. 이 방법을 사용할 수 없거나 요구사항에 부합하지 않는 경우 deviceClass를 직접 파싱해야 합니다.

chrome.bluetooth.getDevices(function(devices) {
  for (var i = 0; i < devices.length; i++) {
    if (devices[0].vendorIdSource != undefined) {
      console.log(devices[0].address + ' = ' + devices[0].type);
    }
  }
});

RFCOMM 및 L2CAP 사용

Chrome 앱은 RFCOMM 또는 L2CAP 서비스를 지원하는 모든 기기에 연결할 수 있습니다. 여기에는 시중의 대부분의 기존 블루투스 기기가 포함됩니다.

소켓에 연결

기기에 연결하려면 세 가지가 필요합니다. 연결할 소켓으로, bluetoothSocket.create를 사용하여 만들어집니다. 연결하려는 기기의 주소 및 서비스 자체의 UUID입니다.

연결하기 전에 bluetooth.getDevice 또는 기기 검색 API를 사용하여 어댑터가 기기를 인식하고 있는지 확인해야 합니다.

RFCOMM 또는 L2CAP 프로토콜을 사용해야 하는지, 기기에서 SDP 검색을 사용하여 가져오는 채널 또는 PSM을 비롯하여 기본 연결을 설정하는 데 필요한 정보.

예:

var uuid = '1105';
var onConnectedCallback = function() {
  if (chrome.runtime.lastError) {
    console.log("Connection failed: " + chrome.runtime.lastError.message);
  } else {
    // Profile implementation here.
  }
};

chrome.bluetoothSocket.create(function(createInfo) {
  chrome.bluetoothSocket.connect(createInfo.socketId,
    device.address, uuid, onConnectedCallback);
});

나중에 이 소켓으로 데이터 (bluetoothSocket.send)를 전송할 수 있도록 socketId에 핸들을 유지합니다.

소켓에서 수신 및 소켓 전송

소켓에서 데이터를 수신하고 전송하는 데는 ArrayBuffer 객체가 사용됩니다. ArrayBuffer에 관한 자세한 내용은 개요, JavaScript 유형 배열 및 튜토리얼, ArrayBuffer를 String으로 또는 String에서 변환하는 방법을 참고하세요.

arrayBuffer에 있는 데이터를 전송하려면 bluetoothSocket.send를 사용합니다.

chrome.bluetoothSocket.send(socketId, arrayBuffer, function(bytes_sent) {
  if (chrome.runtime.lastError) {
    console.log("Send failed: " + chrome.runtime.lastError.message);
  } else {
    console.log("Sent " + bytes_sent + " bytes")
  }
})

데이터를 전송하는 메서드와 달리 데이터는 이벤트(bluetoothSocket.onReceive)로 수신됩니다. 소켓은 일시중지되지 않은 상태로 생성되므로 (bluetoothSocket.setPaused 참고) 이 이벤트의 리스너는 일반적으로 bluetoothSocket.createbluetoothSocket.connect 사이에 추가됩니다.

chrome.bluetoothSocket.onRecieve.addListener(function(receiveInfo) {
  if (receiveInfo.socketId != socketId)
    return;
  // receiveInfo.data is an ArrayBuffer.
});

소켓 오류 수신 및 연결 해제

연결 해제를 비롯한 소켓 오류에 대한 알림을 받으려면 bluetoothSocket.onReceiveError 이벤트에 리스너를 추가합니다.

chrome.bluetoothSocket.onReceiveError.addListener(function(errorInfo) {
  // Cause is in errorInfo.error.
  console.log(errorInfo.errorMessage);
});

소켓에서 연결 해제

연결을 끊고 소켓을 분리하려면 bluetoothSocket.disconnect를 사용합니다.

chrome.bluetoothSocket.disconnect(socketId);

게시 서비스

Chrome 앱은 기기에 대한 아웃바운드 연결 외에도 RFCOMM 또는 L2CAP를 지원하는 모든 기기에서 사용할 수 있는 서비스를 게시할 수 있습니다.

소켓에서 수신 대기

두 가지 유형의 게시된 서비스가 지원됩니다. RFCOMM은 가장 일반적으로 사용되며 대부분의 기기와 프로필을 포함합니다.

var uuid = '1105';
chrome.bluetoothSocket.create(function(createInfo) {
  chrome.bluetoothSocket.listenUsingRfcomm(createInfo.socketId,
    uuid, onListenCallback);
});

L2CAP는 다른 기기 유형 및 펌웨어 업로드와 같은 공급업체별 용도를 다룹니다.

var uuid = '0b87367c-f188-47cd-bc20-a5f4f70973c6';
chrome.bluetoothSocket.create(function(createInfo) {
  chrome.bluetoothSocket.listenUsingL2cap(createInfo.socketId,
    uuid, onListenCallback);
});

두 경우 모두 선택적 bluetoothSocket.ListenOptions를 전달하여 특정 채널이나 PSM을 할당할 수 있습니다. 콜백은 chrome.runtime.lastError를 통해 오류가 발생했고 그렇지 않은 경우 성공을 나타냅니다. 나중에 이 소켓의 연결(bluetoothSocket.onAccept)을 수락할 수 있도록 socketId에 핸들을 유지합니다.

클라이언트 연결 수락

클라이언트 연결이 수락되고 bluetoothSocket.onAccept 이벤트를 통해 애플리케이션에 전달됩니다.

chrome.bluetoothSocket.onAccept.addListener(function(acceptInfo) {
  if (info.socketId != serverSocketId)
    return;

  // Say hello...
  chrome.bluetoothSocket.send(acceptInfo.clientSocketId,
    data, onSendCallback);

  // Accepted sockets are initially paused,
  // set the onReceive listener first.
  chrome.bluetoothSocket.onReceive.addListener(onReceive);
  chrome.bluetoothSocket.setPaused(false);
});

클라이언트 연결 수락 중지

클라이언트 연결 수락을 중지하고 서비스를 게시 취소하려면 bluetoothSocket.disconnect를 사용합니다.

chrome.bluetoothSocket.disconnect(serverSocketId);

저전력 기기와 상호작용

저전력 블루투스 또는 (블루투스 스마트)는 전력 소비 절감을 목표로 하는 무선 기술입니다. Bluetooth Low Energy API를 사용하면 애플리케이션이 주변기기에 대한 저전력 연결에서 중심적인 역할을 구현할 수 있습니다. 다음 섹션에서는 저전력 블루투스 주변기기를 검색하고 연결하고 상호작용하는 방법을 설명합니다.

주변기기 검색 및 연결

기존 블루투스 기기와 마찬가지로 LE 주변기기는 주변 기기 검색에 설명된 방법을 사용하여 찾을 수 있습니다 . 저전력 기기는 '광고 데이터'라는 데이터 패킷을 전송하여 스스로를 검색할 수 있으며, 기기가 광고 모드에 있다고 말합니다. 광고 데이터에는 기기에서 사용 가능한 서비스의 UUID가 포함될 수 있습니다. UUID가 있는 경우 상응하는 bluetooth.Device 객체의 uuids 속성을 사용하여 액세스할 수 있습니다.

검색이 완료되면 애플리케이션이 서비스와 상호작용할 수 있도록 bluetoothLowEnergy.connect를 호출하여 저전력 기기에 연결할 수 있습니다.

chrome.bluetooth.onDeviceAdded.addListener(function(device) {
  var uuid = '0000180d-0000-1000-8000-00805f9b34fb';
  if (!device.uuids || device.uuids.indexOf(uuid) < 0)
    return;

  // The device has a service with the desired UUID.
  chrome.bluetoothLowEnergy.connect(device.address, function () {
    if (chrome.runtime.lastError) {
      console.log('Failed to connect: ' + chrome.runtime.lastError.message);
      return;
    }

    // Connected! Do stuff...
    ...
  });
});

연결되면 해당하는 bluetooth.Device 객체의 connected 속성 값이 true가 됩니다. bluetoothLowEnergy.connect를 호출하면 애플리케이션에 대한 클레임이 기기에 실제로 연결됩니다. 기기와의 실제 연결은 bluetoothLowEnergy.connect를 호출하지 않아도 존재할 수 있습니다 (예: 다른 애플리케이션으로 인해). 이 경우에도 애플리케이션이 여전히 기기의 서비스와 상호작용할 수 있지만 다른 애플리케이션이 실제 링크의 연결을 끊지 않도록 항상 bluetoothLowEnergy.connect를 호출해야 합니다.

애플리케이션에 더 이상 연결할 필요가 없으면 bluetoothLowEnergy.disconnect를 호출하여 연결에 대한 클레임을 삭제할 수 있습니다.

chrome.bluetoothLowEnergy.disconnect(deviceAddress);

기기에 대한 활성 연결이 있는 다른 애플리케이션이 있을 수 있으므로 이 경우 기기의 실제 링크가 반드시 파괴되는 것은 아닙니다. 애플리케이션에서 제어할 수 없는 원인으로 인해 기기가 연결 해제되는 경우가 있습니다 (예: 기기가 운영체제의 유틸리티를 통해 사용자가 사라지거나 명시적으로 연결 해제되는 경우). 애플리케이션은 bluetooth.onDeviceChanged 이벤트를 관찰하여 연결 변경사항에 관한 알림을 받고 필요한 경우 다시 연결해야 합니다.

연결되면 Chrome을 실행하는 기기는 이른바 중앙 역할이 되고 원격 기기는 주변기기 역할에 배치된다고 합니다. 이 시점에서 애플리케이션은 다음 섹션에 설명된 방법을 사용하여 기기의 서비스와 상호작용할 수 있습니다. 참고: API는 현재 LE 주변기기 역할을 지원하지 않습니다. 앱은 중앙 역할만 구현할 수 있습니다.

서비스, 특성, 설명어

저전력 블루투스는 속성 프로토콜(ATT)이라는 간단한 요청-응답 프로토콜을 기반으로 합니다. ATT를 사용하면 중앙 기기는 일반 속성 프로필 (GATT)이라는 특수한 블루투스 프로필을 준수하여 주변기기의 속성과 상호작용합니다. GATT는 다음과 같은 대략적인 개념을 정의합니다.

  • 서비스: GATT 서비스는 기기의 특정 기능을 달성하기 위한 데이터 및 관련 동작의 모음을 나타냅니다. 예를 들어 심박수 모니터에는 일반적으로 하나 이상의 '심박수 서비스'가 있습니다. GATT 서비스에 관한 정보는 bluetoothLowEnergy.Service 객체에 포함되어 있습니다.
  • 특성: GATT 특성은 GATT 서비스를 구성하는 데 사용되는 기본 데이터 요소로, 값에 액세스할 수 있는 방법을 정의하는 속성과 값이 포함됩니다. 예를 들어 '심박수 서비스'에는 사용자의 심박수 값을 가져오는 데 사용되는 '심박수 측정' 특성이 있습니다. GATT 특성에 관한 정보는 bluetoothLowEnergy.Characteristic 객체에 포함됩니다.
  • 설명어: GATT 특성 설명자에는 특성에 대한 추가 정보가 포함됩니다. GATT 특성 설명어에 관한 정보는 bluetoothLowEnergy.Descriptor 객체에 포함되어 있습니다.

Bluetooth Low Energy API를 사용하면 애플리케이션이 bluetoothLowEnergy.getServices, bluetoothLowEnergy.getCharacteristicsbluetoothLowEnergy.getDescriptors를 호출하여 기기의 서비스, 특성, 설명어에 관한 정보를 찾을 수 있습니다. 앱은 uuid 필드를 원하는 GATT UUID와 비교하여 서비스, 특성, 설명어를 필터링할 수 있습니다.

chrome.bluetoothLowEnergy.getServices(deviceAddress, function(services) {
  ...
  for (var i = 0; i < services.length; i++) {
    if (services[i].uuid == HEART_RATE_SERVICE_UUID) {
      heartRateService = services[i];
      break;
    }
  }
  ...
});

API를 통해 액세스할 수 있는 각 서비스, 특성, 설명어에는 고유한 인스턴스 식별자가 할당되며, 이 식별자는 instanceId 필드를 사용하여 가져올 수 있습니다. 이 인스턴스 ID는 GATT 객체를 식별하고 이 객체에 관해 특정 작업을 실행하는 데 사용할 수 있습니다.

chrome.bluetoothLowEnergy.getCharacteristics(heartRateService.instanceId,
                                             function(chracteristics) {
  ...
  for (var i = 0; i < characteristics.length; i++) {
    if (characteristics[i].uuid == HEART_RATE_MEASUREMENT_UUID) {
      measurementChar = characteristics[i];
      break;
    }
  }
  ...
  chrome.bluetoothLowEnergy.getDescriptors(measurementChar.instanceId,
                                           function(descriptors) {
    ...
  });
});

서비스 이벤트

기기가 연결되면 Chrome에서 서비스를 검색합니다. 각 서비스가 검색되고 삭제될 때 애플리케이션은 bluetoothLowEnergy.onServiceAddedbluetoothLowEnergy.onServiceRemoved 이벤트를 수신합니다.

  var initializeService = function(service) {
    if (!service) {
      console.log('No service selected!');
      // Reset UI, etc.
      ...
      return;
    }

    myService = service;

    // Get all the characteristics and descriptors and bootstrap the app.
    ...
  };

  chrome.bluetoothLowEnergy.onServiceAdded.addListener(function(service) {
    if (service.uuid == MY_SERVICE_UUID)
      initializeService(service);
  });

  chrome.bluetoothLowEnergy.onServiceRemoved.addListener(function(service) {
    if (service.instanceId == myService.instanceId)
      initializeService(null);
  });

Chrome은 서비스의 모든 특성과 설명어를 비동기식으로 검색하고 검색이 완료되면 bluetoothLowEnergy.onServiceAdded 이벤트를 전송합니다. 주변기기 연결이 종료되면 Chrome은 모든 관련 서비스를 삭제하고 bluetoothLowEnergy.onServiceRemoved 이벤트를 전송합니다.

일부 주변기기는 서비스를 수정할 수 있습니다. 예를 들어 서비스의 특성이 변경되거나 서비스가 추가 및 완전히 삭제될 수 있습니다. Chrome은 bluetoothLowEnergy.onServiceChanged, bluetoothLowEnergy.onServiceAdded, bluetoothLowEnergy.onServiceRemoved 이벤트를 사용하여 이러한 변경사항을 앱에 알립니다.

  chrome.bluetoothLowEnergy.onServiceChanged.addListener(function(service) {
    if (service.instanceId != myService.instanceId)
      return;

    updateMyService(service);
  });

특성 값 읽기 및 쓰기

GATT 특성은 서비스의 한 측면을 인코딩합니다. 중앙 앱은 특성의 값에 따라 작동하여 주변기기 서비스의 상태를 읽고, 실행하고, 수정합니다. 특성 값은 일련의 바이트이며 그 의미는 특정 특성을 정의하는 상위 수준 사양에 의해 정의됩니다. 예를 들어 심박수 측정 특성 값은 사용자의 심박수와 총 칼로리 소모량을 인코딩하는 반면 신체 센서 위치 특성은 신체 중 심박수 센서를 착용해야 하는 위치를 인코딩합니다.

Chrome은 bluetoothLowEnergy.readCharacteristicValue 메서드를 제공하여 특성 값을 읽습니다.

chrome.bluetoothLowEnergy.readCharacteristicValue(chrc.instanceId,
                                                  function(result) {
  if (chrome.runtime.lastError) {
    console.log('Failed to read value: ' + chrome.runtime.lastError.message);
    return;
  }

  var bytes = new Uint8Array(result.value);

  // Do stuff with the bytes.
  ...
});

일부 특성은 쓰기가 가능하고, 특히 '컨트롤 포인트'로 동작하는 특성은 쓰기가 가능합니다. 여기서 값을 쓰면 부작용이 발생합니다. 예를 들어 심박수 제어 지점 특성은 심박수 센서에 총 칼로리 소모량을 재설정하도록 지시하는 데 사용되며 쓰기만 지원됩니다. 이를 위해 Chrome은 bluetoothLowEnergy.writeCharacteristicValue 메서드를 제공합니다.

var myBytes = new Uint8Array([ ... ]);
chrome.bluetoothLowEnergy.writeCharacteristicValue(chrc.instanceId,
                                                   myBytes.buffer,
                                                   function() {
  if (chrome.runtime.lastError) {
    console.log('Failed to write value: ' +
                chrome.runtime.lastError.message);
    return;
  }

  // Value is written now.
});

특성 설명어는 동일한 방식으로 작동하며 읽기 및/또는 쓰기가 가능합니다. Chrome은 설명어의 값을 읽고 쓸 수 있도록 bluetoothLowEnergy.readDescriptorValuebluetoothLowEnergy.writeDescriptorValue 메서드를 제공합니다.

특성이 읽기 또는 쓰기를 지원하는지 확인하기 위해 애플리케이션은 bluetoothLowEnergy.Characteristic 객체의 properties 필드를 확인할 수 있습니다. 이 필드에는 값에 액세스하기 위한 보안 요구사항에 대한 정보가 포함되어 있지 않지만 특성이 일반적으로 지원하는 값 작업은 설명합니다.

값 알림 처리

일부 특성은 알림 또는 표시를 통해 값을 알 수 있습니다. 예를 들어 심박수 측정 특성은 읽거나 쓸 수 없지만 일정한 간격으로 현재 값에 관한 업데이트를 전송합니다. 애플리케이션은 bluetoothLowEnergy.onCharacteristicValueChanged 이벤트를 사용하여 이러한 알림을 수신 대기할 수 있습니다.

  chrome.bluetoothLowEnergy.onCharacteristicValueChanged.addListener(
      function(chrc) {
    if (chrc.instanceId != myCharId)
      return;

    var bytes = new Uint8Array(chrc.value);

    // Do stuff with the bytes.
    ...
  });

특성이 알림/표시를 지원하더라도 기본적으로 사용 설정되지 않습니다. 애플리케이션은 bluetoothLowEnergy.startCharacteristicNotificationsbluetoothLowEnergy.stopCharacteristicNotifications 메서드를 호출하여 bluetoothLowEnergy.onCharacteristicValueChanged 이벤트 수신을 시작하거나 중지해야 합니다.

  // Start receiving characteristic value notifications.
  var notifying = false;
  chrome.bluetoothLowEnergy.startCharacteristicNotifications(chrc.instanceId,
                                                             function() {
    if (chrome.runtime.lastError) {
      console.log('Failed to enable notifications: ' +
                  chrome.runtime.lastError.message);
      return;
    }

    notifying = true;
  });

  ...

  // No longer interested in notifications from this characteristic.
  if (notifying) {
    chrome.bluetoothLowEnergy.stopCharacteristicNotifications(
        chrc.instanceId);
  }

알림이 시작되면 애플리케이션은 특성에서 알림 또는 표시가 수신될 때마다 bluetoothLowEnergy.onCharacteristicValueChanged를 수신합니다. 특성이 읽기를 지원하는 경우 bluetoothLowEnergy.readCharacteristicValue 호출이 성공한 후에 이 이벤트도 전송됩니다. 이를 통해 앱은 읽기 요청 및 알림을 통해 트리거된 값 업데이트의 제어 흐름을 통합할 수 있습니다.

  chrome.bluetoothLowEnergy.onCharacteristicValueChanged.addListener(
      function(chrc) {
    // Process the value.
    ...
  });

  chrome.bluetoothLowEnergy.startCharacteristicNotifications(chrc.instanceId,
                                                             function() {
    // Notifications started. Read the initial value.
    chrome.bluetoothLowEnergy.readCharacteristicValue(chrc.instanceId,
                                                      function(result) {
      ...
      // No need to do anything here since onCharacteristicValueChanged
      // will handle it.
    });
  });

특성이 알림을 지원하면 properties 필드에 "notify" 또는 "indicate" 속성이 포함됩니다.

참고: 특성이 알림/표시를 지원하는 경우 알림을 사용 설정/사용 중지하기 위한 '클라이언트 특성 구성' 설명자가 있습니다. Chrome은 앱이 이 설명자에 쓰는 것을 허용하지 않습니다. 앱에서는 대신 bluetoothLowEnergy.startCharacteristicNotificationsbluetoothLowEnergy.stopCharacteristicNotifications 메서드를 사용해야 알림 동작을 제어합니다.