Skip to content

feat: add WASM/WebBluetooth support - #436

Merged
deadprogram merged 43 commits into
tinygo-org:devfrom
acouvreur:add-webbluetooth
Oct 9, 2026
Merged

deadprogram merged 43 commits into
tinygo-org:devfrom
acouvreur:add-webbluetooth

Conversation

@acouvreur

@acouvreur acouvreur commented Apr 10, 2026 •

Copy link
Copy Markdown
Member

This adds support for the Web Bluetooth API through WASM. The implementation should now be complete for the central role, and it builds with TinyGo and with the standard Go toolchain.

Supported

  • Adapter: Enable, Scan, StopScan, Connect, SetConnectHandler and Reset
  • Device: DiscoverServices, Disconnect and Connected
  • DeviceService: DiscoverCharacteristics
  • DeviceCharacteristic: Read, Write, WriteWithoutResponse, EnableNotifications and GetMTU

Limits of Web Bluetooth

  • Scan opens the device picker of the browser and gives one device. It returns ErrScanCanceled if the user closes the picker.
  • The browser opens the picker only after a recent user action, such as a click.
  • The scan result has the device name only. There is no RSSI and no advertisement data.
  • Address holds an opaque device ID instead of a MAC address.
  • Every service must be in Adapter.RequestedServices before Scan. This field exists only on WASM.
  • The browser does not give the negotiated MTU, so GetMTU returns 512.
  • There is no peripheral role.

Example

examples/webbluetooth gives the backend to a web page as a small JavaScript API. Its README has the build steps for both toolchains. The Linux CI job builds it with TinyGo.

AI Disclaimer: This was mostly implemented using Claude Opus 4.6

I had a lot of fun interacting with bluetooth device from a webpage through WASM with the same underlying code that can run in linux, mac, windows or embedded systems.

Comment thread examples/webbluetooth/html/wasm.wasm Resolved
Comment thread examples/webbluetooth/html/wasm_exec.js Resolved
@deadprogram

Copy link
Copy Markdown
Member

What is the status with this PR @acouvreur 😸

@acouvreur

Copy link
Copy Markdown
Member Author

What is the status with this PR @acouvreur 😸

Are you interested with bringing WASM / WebBluetooth support?

The current implementation is a load of duct taping but it works! I can polish the PR a little bit and we can merge it if you think that'd be a good addition.

@deadprogram

Copy link
Copy Markdown
Member

Are you interested with bringing WASM / WebBluetooth support?

I am indeed!

@acouvreur

Copy link
Copy Markdown
Member Author

Are you interested with bringing WASM / WebBluetooth support?

I am indeed!

Cool! Let me clean that up :)

@acouvreur
acouvreur marked this pull request as ready for review September 2, 2026 18:29
@acouvreur

Copy link
Copy Markdown
Member Author

@deadprogram looks good for me now...

Clean up the example so that the built wasm exposes functions to be used in a JS program to interact with the tinygo-org/bluetooth APIs.

Quite safe merge IMO.

Next step for me is to update #468. I would love to add cancellable operations to this library.

With JS you can easily map an AbortController Signal to a Go context.Context.

@deadprogram deadprogram left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this!

Here are some comments from an automated revview.

Overall

This is a good addition and it is near to merge. The structure agrees with the other backends. gap_js.go uses the same Address shape as the macOS backend (opaque ID, Set, no-op SetRandom), and the interface assertions (BLEAdapter, GAPDevice, GATTCService, GATTCCharacteristic) are all present. The known WASM traps are correct: user callbacks run on a new goroutine so that they do not stop the JS event loop, DataView values are read at their own offset and length, and js.Func values get released.

Points to think about

1. Adapter.RequestedServices is only on the js backend (adapter_js.go)

No other backend has an exported field on Adapter, so code that sets this field does not compile for Linux, macOS, or Windows. This makes the "same code everywhere" goal weaker. Two options: keep it and accept the limit (it is documented), or add the same field as a no-op to the other backends so that portable code compiles. This is the one API decision in the PR that is difficult to change later.

2. Adapter.Reset leaves a connection open (adapter_js.go)

Reset removes the disconnect listeners and clears the maps, but it does not disconnect the GATT server. The browser keeps the connection to a device that is connected. A gatt.disconnect() on each known device would make the reset complete.

3. EnableNotifications(nil) calls stopNotifications always (gattc_js.go)

If notifications were never started, the code still calls stopNotifications on the characteristic. This is harmless in Chrome, but a return after stopListening when c.listening is false is more clear.

4. Read truncates without a signal (gattc_js.go)

If the value is longer than data, Read gives the first len(data) bytes and no indication. Please make sure that this agrees with the macOS and Windows backends.

5. The example imports syscall/js with no build constraint

go build ./... on Linux now stops at examples/webbluetooth. CI does not use ./..., and examples/circuitplay already breaks it, so this changes nothing today. A //go:build js line in the example is still an inexpensive improvement.

6. requestDevice and user activation

Scan calls navigator.bluetooth.requestDevice from a goroutine, so the call leaves the task of the click. Chrome accepts this while the transient activation is valid (some seconds), which is why the example works. A note in the README that the page must call requestDevice immediately after a user action would prevent a difficult bug report later.

Nits

  • examples/webbluetooth/html/.gitignore has no final newline.
  • The WASM installation steps are given two times (repository README and example README). This is not incorrect, only repetition.

Comment thread Makefile Resolved
@deadprogram

Copy link
Copy Markdown
Member

Thanks for this. I built the branch with both toolchains and go vet for GOOS=js is clean. The file layout follows the other backends well.

Some points from a read of the code.

1. RequestedServices is a WASM-only public field (adapter_js.go:30)

This is the only new public item that portable code must set. A program for Linux and for the browser cannot set it without a build tag, which removes much of the value of the shared API. We can put the field on every Adapter as a no-op elsewhere, or give the list to Scan or to ConnectionParams. It is public API, so it is better to decide now.

2. The notification listeners leak (gattc_js.go:262)

Adapter.Reset releases the gattserverdisconnected listeners, but no path releases the characteristicvaluechanged listeners. Device.Disconnect does not release them either. A page that connects and disconnects many times keeps one js.Func for each subscription until the page closes.

3. A user cancel looks like a failure (gattc_js.go:290)

jsError gives a plain string, so Scan returns NotFoundError: User cancelled the requestDevice() chooser. A cancel is a normal flow. A sentinel error for that case lets the caller tell the two apart.

Smaller items

  • Enable does not check window.isSecureContext. A page on plain HTTP fails later with an opaque error from requestDevice.
  • Device.Disconnect returns nil when the device is not connected. gap_linux.go:540 gives the error of the underlying call.
  • The listener in setDisconnectHandler (gap_js.go:181) calls listener.Release() inside its own invocation. It works, but a defer is easier to read.
  • The maxAttributeValueLength comment quotes 4 lines of the specification. Please keep it to 2 lines. The URL is enough.

@deadprogram

Copy link
Copy Markdown
Member

@acouvreur did you see my last set of feedback? What do you think?

@acouvreur

Copy link
Copy Markdown
Member Author

Thanks for this. I built the branch with both toolchains and go vet for GOOS=js is clean. The file layout follows the other backends well.

Some points from a read of the code.

1. RequestedServices is a WASM-only public field (adapter_js.go:30)

This is the only new public item that portable code must set. A program for Linux and for the browser cannot set it without a build tag, which removes much of the value of the shared API. We can put the field on every Adapter as a no-op elsewhere, or give the list to Scan or to ConnectionParams. It is public API, so it is better to decide now.

I agree that this would break single code to multiple OS compatibility as RequestedServices won't compile to any other platforms.

However, implementing it as a no-op to every other platforms might be worse I think. What do you suggest ?

2. The notification listeners leak (gattc_js.go:262)

Adapter.Reset releases the gattserverdisconnected listeners, but no path releases the characteristicvaluechanged listeners. Device.Disconnect does not release them either. A page that connects and disconnects many times keeps one js.Func for each subscription until the page closes.

OK

3. A user cancel looks like a failure (gattc_js.go:290)

jsError gives a plain string, so Scan returns NotFoundError: User cancelled the requestDevice() chooser. A cancel is a normal flow. A sentinel error for that case lets the caller tell the two apart.

OK -> Extracting errors from promise now.

Smaller items

* `Enable` does not check `window.isSecureContext`. A page on plain HTTP fails later with an opaque error from `requestDevice`.

OK

* `Device.Disconnect` returns `nil` when the device is not connected. `gap_linux.go:540` gives the error of the underlying call.

OK

* The listener in `setDisconnectHandler` (`gap_js.go:181`) calls `listener.Release()` inside its own invocation. It works, but a `defer` is easier to read.

OK

* The `maxAttributeValueLength` comment quotes 4 lines of the specification. Please keep it to 2 lines. The URL is enough.

OK

@deadprogram

Copy link
Copy Markdown
Member

However, implementing it as a no-op to every other platforms might be worse I think. What do you suggest ?

Well, WASM being WASM, and also executing in the browser, there are some things that we just have to accept, I think. So just add to WASM for now, and let's see if that is an issue in the future.

@deadprogram

Copy link
Copy Markdown
Member

What is the status on this @acouvreur ?

@acouvreur

Copy link
Copy Markdown
Member Author

What is the status on this @acouvreur ?

I'm busy this weekend, will finish this next week 😃

@acouvreur

Copy link
Copy Markdown
Member Author

Thanks for the review. All points are fixed.

  • RequestedServices stays WASM only.
  • The characteristicvaluechanged listeners are released on gattserverdisconnected. This covers Device.Disconnect and a remote disconnect. Reset releases them too.
  • Scan returns ErrScanCanceled when the user closes the picker. Enable now checks getAvailability(), so a NotFoundError from requestDevice means that the user chose no device.
  • Enable checks isSecureContext.
  • Device.Disconnect returns an error when not connected.
  • The disconnect listener uses defer for Release.
  • The maxAttributeValueLength comment is 2 lines.

I also rebased on dev and fixed a panic when a promise rejects with a value that is not an object.

@deadprogram

Copy link
Copy Markdown
Member

Thanks for the fixes. I checked them in the code. The library and the example build for WASM with Go and with TinyGo. Some changes are still necessary because dev changed.

1. Read must agree with #497 (gattc_js.go)

#497 is merged. Now Read returns the number of bytes copied into data, and io.ErrShortBuffer when the value is longer than data. The WASM Read returns the full value length, and its comment says that the other backends do the same. Please compare the result of js.CopyBytesToGo with the value length, return io.ErrShortBuffer when the value does not fit, and update the comment.

2. Use the sentinel errors for "not found" (gattc_js.go)

8c63642 added ErrServiceNotFound and ErrCharacteristicNotFound. When a requested UUID is not there, DiscoverServices and DiscoverCharacteristics return the browser NotFoundError. Please use isDOMError(err, "NotFoundError") and return the sentinel errors.

Smaller items

  • Scan before Enable panics, because a.bluetooth is undefined and a.devices is a nil map. Please return an error.
  • examples/webbluetooth/main.go has no //go:build js line.

The listening flag was never set to true, so EnableNotifications(nil) kept
the JS listener attached and released no resources. A late event then found
a nil callback. A second call added a duplicate listener.
A wrapped Go function blocks the JS event loop until it returns. A callback
that calls back into this package waits for a promise and deadlocks the page.
A DataView can be a window into a larger ArrayBuffer. Wrapping only the
buffer gave the wrong bytes.
Calling toString on undefined or null throws inside the catch handler and
stops the program.
Package level maps grew for the life of the page and were shared by all
adapters.
StopScan now returns errNotScanning when no scan runs, and Scan returns
errScanning for a second scan. This agrees with the other backends.
Read now has a value receiver, and a UUID that does not parse gives an error
instead of a zero UUID.
The module now exports globalThis.ble with a function for each operation, and
the page does all of the display work. Each export returns a Promise and runs
the work on a new goroutine, because a function that JavaScript calls must not
block the event loop.
Battery Level sends a new value every second, so the notifications panel shows
data immediately. The examples/battery peripheral serves it.
Reset releases the disconnect listeners and drops the known devices, so that
Enable can run again. BLEAdapter needs this method.
The screenshot did not show the current page.
512 is the maximum length of an attribute value, not the maximum ATT MTU.
Write can use a long write up to the maximum attribute value length. A write
without response must fit the negotiated MTU, which GetMTU does not give.
requestDevice gives only an id and a name, so the RSSI is 0 and the payload
has no service UUIDs.
TinyGo gives a smaller module and a faster build than the standard toolchain.
Linux, macOS and Windows give the length of the value, even when it is longer
than the buffer. The caller can then see that the value was cut.
Reset removed the listeners but left the browser connected to the device.
The browser refuses requestDevice when the user activation is too old.
A characteristic that comes from a second discovery has listening false while
the browser still sends notifications.
The browser drops the characteristics of a device when it disconnects, but
each listener kept its js.Func until the page closed. Reset now releases them
too, and keeps empty maps so that a stale characteristic cannot panic.
A page on plain HTTP has no navigator.bluetooth, and Enable said that the
browser has no support. Enable now also fails when getAvailability is false,
as the other backends do when there is no adapter.
A closed picker rejects with a NotFoundError. Scan returned it as a plain
string, so a caller could not tell a cancel from a failure. jsError now keeps
the name of the DOMException.
Linux gives the error of the underlying call in this case.
The page now shows a closed picker as a normal result, not as an error.
Value.Call panics on a value that is not an object, such as a string.
Read now gives the number of bytes copied, as the other backends do since
5b474bc.
The browser rejects with a NotFoundError when a requested UUID is not there.
It also rejects a discovery of all children that finds none, where the other
backends give an empty result.
Scan called requestDevice on an undefined value and panicked.
The example imports syscall/js, so go build ./... stopped at it on other
platforms.
@acouvreur

Copy link
Copy Markdown
Member Author

Thanks. I rebased on dev and fixed all four points.

  • Read now returns the number of bytes copied, and io.ErrShortBuffer when the value does not fit. The comment is now the same as on the other backends.
  • DiscoverServices and DiscoverCharacteristics return ErrServiceNotFound and ErrCharacteristicNotFound when a requested UUID is not there. With a nil list, the browser also rejects with a NotFoundError when it finds nothing (GetGATTChildren). That case now gives an empty result, as on the other backends.
  • Scan before Enable returns an error. This also covers Scan after Reset.
  • examples/webbluetooth/main.go has a //go:build js line.

@deadprogram deadprogram left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for all the work on this. I checked the fixes, and the library and the example build for WASM with Go and with TinyGo.

@deadprogram
deadprogram merged commit 07d3b10 into tinygo-org:dev Oct 9, 2026
4 checks passed
@deadprogram

Copy link
Copy Markdown
Member

Amazing work @acouvreur thank you so very much!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants