Skip to content

Instantly share code, notes, and snippets.

@sdkfz181tiger
Last active October 24, 2022 08:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sdkfz181tiger/ff9ee5eb6ff523ed6c15390bb98a46cb to your computer and use it in GitHub Desktop.
Save sdkfz181tiger/ff9ee5eb6ff523ed6c15390bb98a46cb to your computer and use it in GitHub Desktop.
BluetoothDevice x ChromeBrowser
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>
#include <BLE2902.h>
#define SERVICE_UUID "xxxxx"
#define CHARACTERISTIC_UUID "yyyyy"
#define DEVICE_NAME "BLE_Controller"
using namespace std;
BLEServer *pServer = NULL;
BLEService *pService = NULL;
BLECharacteristic *pCharacteristic = NULL;
int counter = 0;
// Send to browser
void sendMsg(const string msg){
if(!pServer && !pService) return;
pCharacteristic->setValue(msg.c_str());
pCharacteristic->notify();
Serial.println(msg.c_str());
}
// Receive from browser
class BLECallback: public BLECharacteristicCallbacks{
void onWrite(BLECharacteristic *characteristic){
string value = characteristic->getValue();
if (0 < value.length()) Serial.println(value.c_str());
}
};
void setup(){
Serial.begin(115200);
Serial.println("Starting BLE!!");
Serial.println(DEVICE_NAME);
// BLEDevice
BLEDevice::init(DEVICE_NAME);
pServer = BLEDevice::createServer();
pService = pServer->createService(SERVICE_UUID);
pCharacteristic = pService->createCharacteristic(CHARACTERISTIC_UUID,
BLECharacteristic::PROPERTY_READ |
BLECharacteristic::PROPERTY_WRITE |
BLECharacteristic::PROPERTY_NOTIFY |
BLECharacteristic::PROPERTY_INDICATE);
pCharacteristic->addDescriptor(new BLE2902());// Very important!!(using notification)
pCharacteristic->setCallbacks(new BLECallback());// Callback
//pCharacteristic->setValue("Hello World says Neil");
//pCharacteristic->notify();
// Start
pService->start();
// BLEAdvertising
BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
pAdvertising->addServiceUUID(SERVICE_UUID);
pAdvertising->setScanResponse(true);
pAdvertising->setMinPreferred(0x06);
pAdvertising->setMinPreferred(0x12);
BLEDevice::startAdvertising();
Serial.println("Characteristic defined!!");
}
void loop(){
Serial.println("BLE_Controller working...");
char msg[24];
sprintf(msg, "Hello, BLE:%01d", counter++);
sendMsg(msg);// Send
delay(2000);
}
"use strict";
//==========
// BluetoothDevice <-> Chrome連携
// GoogleChromeとBLE端末との連携手順
// 1, GoogleChromeで次のアドレスを入力
// chrome://flags/#enable-experimental-web-platform-features
// 2, Experimental Web Platform features
// Enabled
// 3, Console画面で次の命令を入力(接続可能デバイス検索)
// navigator.bluetooth.requestDevice({acceptAllDevices: true})
// 4, トラブルシューティング
// 4-1, ブラウザの更新からConnectでの再接続が出来ない
// AtomLiteの再起動(Upload, USBケーブルの抜き差し)
// BluetoothDeviceと合わせる事
const UUID_SERVICE = "xxxxx";
const UUID_CHARACTERISTIC = "yyyyy";
const DEVICE_NAME = "BLE_Controller";
const options = {
acceptAllDevices: false,
filters: [{namePrefix: DEVICE_NAME}],
optionalServices: [UUID_SERVICE]
}
let bleDevice = null;
let characteristic = null;
let counter = 0;
// Window
window.onload = (e)=>{
console.log("onload");
$("#btn_connect").click(()=>{
connect();
});
$("#btn_send").click(()=>{
sendMsg("Hello, Browser:" + counter++);
});
}
async function connect(){
emptyInfo();
// Bluetooth
navigator.bluetooth.requestDevice(options).then(device=>{
console.log("Device:", device);
addInfo("Device", device.id);
bleDevice = device;
bleDevice.addEventListener("gattserverdisconnected", onDisconnected);
return device.gatt.connect();
}).then(server=>{
console.log("Server:", server);
addInfo("Server", server.device.name);
return server.getPrimaryService(UUID_SERVICE);
}).then(service=>{
console.log("Service:", service);
addInfo("Service", service.uuid);
return service.getCharacteristic(UUID_CHARACTERISTIC);
}).then(chara=>{
console.log("Characteristic:", chara);
addInfo("Characteristic", chara.uuid);
characteristic = chara;
return chara.startNotifications().then(chara=>{
chara.addEventListener("characteristicvaluechanged", onValueChanged);
});
}).catch(error=>{
console.log(error);
addInfo(error);
});
}
function onDisconnected(event){
const name = event.target.name;
console.log("Disconnected:", name);
addInfo("Disconnected", name);
bleDevice.removeEventListener("gattserverdisconnected", onDisconnected);
characteristic.removeEventListener("characteristicvaluechanged", onValueChanged);
}
function onValueChanged(event){
const value = event.target.value;
const decoder = new TextDecoder("utf-8");
const str = decoder.decode(value);
console.log("Value:", str);
addInfo("Value", str);
}
function sendMsg(msg){
if(!bleDevice || !bleDevice.gatt.connected) return;
if(!characteristic) return;
console.log("sendMsg:", msg);
const value = new TextEncoder().encode(msg);
characteristic.writeValue(value);// Write
}
function emptyInfo(){
$("#info").empty();
}
function addInfo(tag, msg){
$("#info").prepend("<li>" + tag + ":" + msg + "</li>");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment