Blazor Web Bluetooth – Android – Part 3

To write to an characteristic of an connected BLE device, we first add an an input field to enter the value. As well as a button to submit and handler function, that just calls a Javascript function and passes the ValueToWrite.

@@ -7,9 +7,16 @@
 <div>
   @Message
 </div>
+<div>
+  <p>
+    Value to Write: <input @bind=ValueToWrite />
+    <button @onclick="SendCharac">SendCharac</button>
+  </p>
+</div>

 @code{
   protected string Message = "Nothing yet";
+  protected string ValueToWrite = "";
   private DotNetObjectReference<Bluetooth>? objRef;

   protected override void OnInitialized()
@@ -23,6 +30,11 @@
     await JS.InvokeVoidAsync("ConnectBluetooth");
   }

+  public async Task SendCharac()
+  {
+    await JS.InvokeVoidAsync("WriteToCharac", ValueToWrite);
+  }
+
   [JSInvokable]
   public async Task Status(string value)
   {

On the Javascript side, we get the writable characteristic and store it in a global variable, so that we can access it later.

Writing to the characteristic is then done by calling writeToCharac function and passing a string as argument.
The passed value is then encoded to utf-8, as writeValue expects a BufferSource. (doc)

@@ -3,6 +3,7 @@ async function setNetRef(ref) {
   netRef = ref;
 }

+let charac_writeable;
 async function ConnectBluetooth() {
   if(!navigator.bluetooth) {
     console.error("No access to bluetooth");
@@ -25,6 +26,9 @@ async function ConnectBluetooth() {
   let charac_deviceTime = await service.getCharacteristic('00000002-5239-4069-806d-7e5c97393755');
   console.log({charac_deviceTime});

+  charac_writeable = await service.getCharacteristic('00000004-5239-4069-806d-7e5c97393755');
+  console.log({charac_writeable});
+
   charac_deviceTime.addEventListener('characteristicvaluechanged', (event) => {
     console.log(event.target);

@@ -39,3 +43,13 @@ async function ConnectBluetooth() {
 //  console.log((await charac_deviceTime.readValue()).getFloat32(0, true));
   await charac_deviceTime.startNotifications();
 }
+
+async function WriteToCharac(value) {
+  if(!charac_writeable) {
+    console.error(`Connect Device first`);
+    return;
+  }
+  console.log(`Writing '${value}' to ${charac_writeable}'`)
+  const encoder = new TextEncoder('utf-8')
+  charac_writeable.writeValue(encoder.encode(value));
+}

How it looks in the browser

Browser console:

Serial Log on ESP32 BLE

New value: Hi There
Uptime: 1838.84
Send BLE Characteristics
New value: Hi There
New value: Hi There

Code can be found here: https://github.com/sukapx/tryout_blazor_webbluetooth/tree/797a7af305a4af0ad7e49eec9f85a028740107cf

Leave a Reply

Your email address will not be published. Required fields are marked *