To external connection, you have to prepare services and characteristics, and set them to obniz.
Services and characteristics class
Dedicated classes are provided for services and characteristic.
For example, the services whose UUID is 1234 can be created as follows.
// Javascript Example
var service = new obniz.ble.service({ uuid : "1234" });
service.advData stores advertisement information necessary to output with ble.advertisement, so it can be used as it is.
// Javascript Example
var service = new obniz.ble.service({ uuid : "1234" });
obniz.ble.advertisement.setAdvData(service.advData);
In order to generate characteristics, UUID is also needed. Additionally, create a value using "data."
// Javascript Example
var characteristic = new obniz.ble.characteristic({ uuid : "7777", data: [1, 2, 3]});
Registration
You can add characteristics to a service by service.addCharacteristic(), and services to a peripheral by peripheral.addService(). By adding it to peripheral, when someone connects to it, they can see, read and write these services and characteristics.
// Javascript Full Example
var obniz = new Obniz("OBNIZ_ID_HERE");
obniz.onconnect = async function () {
await obniz.ble.initWait();
var service = new obniz.ble.service({ uuid : "1234" });
var characteristic = new obniz.ble.characteristic({ uuid : "7777", data: [1, 2, 3]});
service.addCharacteristic(characteristic);
obniz.ble.peripheral.addService(service);
obniz.ble.advertisement.setAdvData(service.advData);
obniz.ble.advertisement.setScanRespData({
localName : "obniz BLE",
});
obniz.ble.advertisement.start();
}
Connection notification
Your peripheral device may actually be connected from another device. Use peripheral.onconnectionupdates know that it is connected. The function set in this property is called when another device starts connecting. The argument have the address and connection status of the other device. This function is called not only when connecting but also when disconnecting. When the device is connected, data.status="connected." When disconnected, data.status="disconnected."
// Javascript Full Example
var obniz = new Obniz("OBNIZ_ID_HERE");
obniz.onconnect = async function () {
await obniz.ble.initWait();
obniz.ble.peripheral.onconnectionupdates = function(data){
if (data.status === "connected") {
console.log("connected from remote device ", data.address)
} else if (data.status === "disconnected") {
console.log("disconnected from remote device ", data.address)
}
};
var service = new obniz.ble.service({ uuid : "1234" });
var characteristic = new obniz.ble.characteristic({ uuid : "7777", data: [1, 2, 3]});
service.addCharacteristic(characteristic);
obniz.ble.peripheral.addService(service);
obniz.ble.advertisement.setAdvData(service.advData);
obniz.ble.advertisement.setScanRespData({
localName : "obniz BLE",
});
obniz.ble.advertisement.start();
}