Bluetooth Services
Everything on this page needs Kamoji firmware 0.3.0 or later.
Older firmware ignores the manifest's ble object and has no ble
table in Lua, so set "min_firmware": "0.3.0" in a mini app that uses them.
A Kamoji Mini App can add its own Bluetooth services to Kamoji. Kamoji then acts as a Bluetooth peripheral with your services next to its own, and a phone app, a web page or a gadget can connect to Kamoji and read, write and subscribe to them like to any other Bluetooth device. Your Lua script gets what they write and can answer with notifications.
What this makes possible:
- Standing in for another device. Kamoji can offer exactly the services of a head-up display or a navigation screen, so the phone app made for that device talks to Kamoji instead. The GOFA HUD, WazeMod HUD and NAV-OSM mini apps do this.
- Your own protocol between your phone app, script or gadget and your mini app: values, text, small pictures, routes.
- Data from the Kamoji app. A service can be limited to phones Kamoji trusts. The Navigation mini app receives turn-by-turn directions from the Kamoji app this way.
This page is the reference. If you'd rather start from working code, see A complete example at the end.
How it works
- Your manifest declares the services and characteristics, and the permission
ble.gatt. - When the mini app is installed, Kamoji checks them. They go live when Kamoji restarts, and the Kamoji app asks the user to do that right after the install (see Installing and restarting).
- From then on, your services are always part of Kamoji's Bluetooth table, whichever mode is on screen. A phone can connect and see them at any time.
- Your Lua runs only while your mini app is on screen. Writes that arrive
then go to your handlers. While it is not on screen, Kamoji can keep the last
values written (
retain), so your mini app can pick them up when it opens. - Kamoji takes one Bluetooth connection at a time: while the Kamoji app is connected, no other phone can connect, and the other way round.
The manifest
Add the permission ble.gatt and a ble object:
{
"id": "my-hud",
"name": "My HUD",
"version": "1.0.0",
"api_version": 1,
"min_firmware": "0.3.0",
"permissions": ["ble.gatt"],
"ble": {
"services": [
{
"id": "hud",
"uuid": "6f1c0001-3b7a-4d2e-9c55-0a1b2c3d4e5f",
"access": "open",
"characteristics": [
{ "id": "speed", "uuid": "6f1c0002-3b7a-4d2e-9c55-0a1b2c3d4e5f",
"properties": ["write", "write_no_response"], "max_length": 16, "retain": true },
{ "id": "status", "uuid": "6f1c0003-3b7a-4d2e-9c55-0a1b2c3d4e5f",
"properties": ["read", "notify"], "max_length": 64, "value": "ready" }
]
}
],
"advertising": { "name": "My HUD", "service_uuid": "6f1c0001-3b7a-4d2e-9c55-0a1b2c3d4e5f" }
}
}
A manifest with a ble object but without the ble.gatt permission is refused
at install, and a mini app installed that way is listed as unavailable. The
Kamoji app shows the permission to the user before an install, and the Mini Apps
store tags the mini app Bluetooth services (GATT) automatically (see
Feature tags).
ble
| Field | Required | Meaning |
|---|---|---|
services | Yes | A list of one or more services (below) |
device_info | No | A Device Information service (0x180A). See device_info |
advertising | No | An extra advertisement while your mini app is on screen. See Advertising |
Services
| Field | Required | Meaning |
|---|---|---|
id | Yes | Your name for it: lowercase letters, digits and _, 1 to 24 characters |
uuid | Yes | The service UUID. See UUIDs |
access | No | "open" (the default) or "kamoji_app". See Access |
characteristics | Yes | A list of one or more characteristics (below) |
Characteristics
| Field | Required | Meaning |
|---|---|---|
id | Yes | Your name for it, used in Lua (ble.on_write("speed", …)): lowercase letters, digits and _, 1 to 24 characters, unique within the mini app (across all its services) |
uuid | Yes | The characteristic UUID |
properties | Yes | One or more of "read", "write" (with response), "write_no_response", "notify" |
max_length | No | The longest value, in bytes: 1 to 512, default 512. For a chunked characteristic, the longest assembled value: 1 to 4096 |
value | No | What a phone reads before your Lua sets anything, as a JSON string ("ready"; "\u0000" for a zero byte). At most max_length and 512 bytes |
retain | No | true: Kamoji keeps the last complete value written, also while your mini app is not on screen. See Retained values |
retain_writes | No | 1 to 8: keep the last n values instead of one. Implies retain |
chunked | No | true: values longer than one write arrive in numbered pieces that Kamoji puts back together. See Chunked values |
retain, retain_writes and chunked need write or write_no_response.
Descriptors and security settings can't be declared yet: a manifest with a
descriptors or security field is refused. Kamoji adds the standard
notification descriptor to every notify characteristic itself.
UUIDs
A UUID is written either as 4 hex digits for a 16-bit UUID on the
Bluetooth base ("2a60" means 00002a60-0000-1000-8000-00805f9b34fb), or in
the full 128-bit form with dashes ("6f1c0001-3b7a-4d2e-9c55-0a1b2c3d4e5f").
Upper or lower case both work.
- For your own protocol, generate random 128-bit UUIDs (any UUID generator,
uuidgenon macOS and Linux). 16-bit UUIDs are assigned by the Bluetooth SIG: use them only to imitate a device that uses them. - A UUID can be used only once among all installed mini apps: a mini app whose UUID another installed mini app already uses is refused. Two mini apps that imitate the same device can't be installed together.
- Reserved, and refused:
1800and1801(Generic Access and Attribute),180a(Device Information, only throughdevice_info), Kamoji's own service and characteristics (12345678-1234-5678-1234-56789abcdef0to…def3, see Bluetooth Protocol), and the Nordic UART UUIDs6e400001/2/3-b5a3-f393-e0a9-e50e24dcca9ethat Kamoji uses for the Chronos watch app.
Access: open or kamoji_app
Each service says who may use it:
access | Who can read, write and subscribe | Use it for |
|---|---|---|
"open" (default) | Any phone or gadget connected to Kamoji | Imitating a device whose phone app knows nothing about Kamoji; anything that is not private |
"kamoji_app" | Only a connection that completed Kamoji's authorization: the Kamoji app, or your own tool that authorizes the same way | Data only a trusted phone may send |
A connection that is not authorized gets Read Not Permitted (0x02) on reads
and Write Not Permitted (0x03) on writes to a kamoji_app service. Its
subscription is accepted but held: nothing is sent to it, and your app gets no
ble.on_subscribe, until the connection authorizes. Kamoji never asks a phone
to pair.
With "open", anyone in Bluetooth range can write to your service while no
other phone is connected to Kamoji. Treat what arrives as untrusted input:
check lengths and values, and never let a write do something harmful. An open
service gives no access to Kamoji's own commands, which always need
authorization.
How the two kinds of phone get along with Kamoji's other rules is described in Connections.
Retained values: retain and retain_writes
Without retain, a value written while your mini app is not on screen is lost
(a write with response is refused, see ATT errors). With
"retain": true, Kamoji keeps the last complete value written to that
characteristic:
- also while your mini app is not on screen, and over updates of the mini app that keep the same Bluetooth services;
- until Kamoji restarts, the mini app is removed, or an update changes its Bluetooth services;
- in Kamoji's memory only, never in its storage.
Your Lua reads it with ble.value(id) (and its age with
ble.value_age_ms(id)), typically when the mini app opens.
"retain_writes": n (1 to 8) keeps the last n complete values, oldest
dropped first. Use it when the sender spreads one message over several plain
writes, for example a route sent as several 500-byte writes: ble.values(id)
returns them oldest to newest, so your mini app can replay them on opening.
Chunked values
A single write carries at most 512 bytes (and a phone may cut it to its MTU).
For bigger values, such as a small picture, declare "chunked": true and send
each value as numbered pieces. Every write to a chunked characteristic is:
byte 0 index 0 … count − 1, the piece's position
byte 1 count 1 … 32, how many pieces the value has
byte 2 … data this piece's bytes
- Send the pieces in order, from index 0 to
count − 1, with the samecountin each. Each write, header included, is at most 512 bytes (and within the connection's MTU for a write without response). - Index 0 starts a new value; an unfinished value is dropped.
- The value is complete when the piece
count − 1arrives after all the others. Kamoji removes the headers and hands your Lua the assembled bytes, in oneble.on_writecall and asble.value. - A piece out of order, with another
count, a bad header (shorter than 2 bytes,count0 or over 32,indexnot belowcount), or a value growing pastmax_lengthdrops the unfinished value. A write with response then gets an ATT error; the sender should start again from index 0. - A value in one piece is
00 01followed by the data; an empty value is just00 01.
max_length is the assembled size, up to 4096 bytes. Kamoji sets aside
that much memory for each chunked characteristic.
device_info
"device_info": { "manufacturer": "GOFA", "model": "EX1", "firmware": "G1.1.2" }
Registers the standard Device Information service (0x180A) with Manufacturer
Name (2a29), Model Number (2a24) and Firmware Revision (2a26), each up to
64 bytes, read only. Some phone apps check these before they accept a device.
Only one installed mini app can have device_info; a second one is refused.
Advertising
Kamoji always advertises as KMJ-XXXX, and any phone can connect to that and
find your services. Some phone apps, though, only connect to a device whose
advertisement has a certain name or service UUID. For them, add:
"advertising": { "name": "HUD_Kamoji", "service_uuid": "00002a60-0000-1000-8000-{bt_mac}" }
| Field | Meaning |
|---|---|
service_uuid | The UUID put in the advertisement. Required: without it, nothing extra is advertised. It is always advertised as a 128-bit UUID |
name | The name in the scan response, up to 29 bytes |
service_uuid may end in {bt_mac} instead of its last 12 hex digits:
Kamoji fills in the address it advertises from there (lowercase hex, in the
order it is usually printed), for devices whose phone app expects the
address inside the UUID.
From firmware 0.3.4, Kamoji advertises from its own fixed address, which differs from its Bluetooth MAC: a phone app that remembered Kamoji before the update finds it again by scanning once.
This advertisement takes turns with Kamoji's own, every 2 seconds, only while your mini app is on screen and no phone is connected. That way both your phone app and the Kamoji app can find Kamoji. As soon as a phone connects, all advertising follows Kamoji's usual rules (see Finding and connecting).
Limits
For all installed mini apps together:
| What | Limit |
|---|---|
| Mini apps with Bluetooth services | 8 |
| Services | 16 (not counting device_info) |
| Characteristics | 64 |
| The services of all mini apps, as Kamoji stores them | 4 KB (a profile like GOFA HUD's, one service with six characteristics, takes about 330 bytes), and room left in Kamoji's settings storage |
| Memory for retained and chunked values | 64 KB: the sum over all characteristics of max_length × (retain_writes + 1 if chunked) |
Per value and per mini app:
| What | Limit |
|---|---|
| One write, one read value | 512 bytes |
| A chunked value | 4096 bytes, in at most 32 pieces |
| Retained values per characteristic | 8 (retain_writes) |
| Values waiting for your Lua | 16 (a write that finds the queue full is not handed to ble.on_write) |
| Notifications waiting to be sent | 8 KB |
An install that would go over a limit, uses a reserved UUID or a UUID another
mini app has, or breaks any rule above is refused: the Kamoji app reports that
the mini app could not be installed, and tool builders get
APP:ERR:bad_ble.
The mini app already installed, if any, stays as it was.
Installing and restarting
Kamoji builds its Bluetooth table once, when it starts. So:
- Installing a mini app with new Bluetooth services, or an update that
changes them, needs a restart. "Changes" means anything in the table:
services or characteristics added or removed, a UUID, an
id,properties,max_length,access,retain,retain_writes,chunked,device_infooradvertising. - An update that keeps them as they are needs no restart: a new
main.lua,layout.json, settings, or a different initialvalue. It works at once.
What the user sees:
- The install finishes as usual. The Kamoji app then asks "Restart Kamoji to enable your mini app", with Later and Restart. Restart reboots Kamoji (nothing is erased); Later leaves it for now, and several installs can share one restart.
- Until the restart, your mini app shows a card "Restart Kamoji to enable your mini app" instead of running. Its old services, after an update, refuse writes.
- After the restart, the services are live and the mini app runs.
Safety net. If Kamoji fails to stay up for a minute after starting with a new set of services (a crash or a power cut), the next start goes back to the last set that worked, or to Kamoji's own services only, and does not try the failed set again until a mini app is installed or removed. A mini app whose services could not start shows "Bluetooth services could not start (see logs)".
Removing a mini app stops its services at once: they refuse writes, and its retained values are gone. They disappear from the table at the next restart.
Phones cache Bluetooth tables. After a restart that changed the services, a phone that knew Kamoji before may still show the old list. In a Bluetooth tool, refresh the services, or turn the phone's Bluetooth off and on.
For tool builders, APP_STATUS:<app id> tells where a mini app stands:
see APP_STATUS.
Foreground only
Like everything in a mini app, your Lua runs only while the mini app is on screen. Your services, though, are there all the time, so a phone can write whenever it likes. What happens to a write:
| Your mini app | Characteristic | The write |
|---|---|---|
| On screen | any | Goes to ble.on_write (and is kept, if retained) |
| Not on screen | retain | Kept: ble.value / ble.values return it when your mini app opens. Accepted without an error |
| Not on screen | not retained | Lost. A write with response gets ATT error 0x03 |
| Removed, or its update waits for a restart | any | Refused with ATT error 0x03 |
Handlers are not replayed. When your mini app opens, nothing that arrived
while it was away is passed to ble.on_write. Read your starting state
instead:
-- main.lua: start from what Kamoji kept, then follow new writes.
apply_speed(ble.value("speed"))
ble.on_write("speed", apply_speed)
Kamoji starts delivering writes to your mini app just before main.lua runs,
so nothing is missed in between. The flip side: a value written during that
moment is both in ble.value and passed to ble.on_write once more. Write
your handlers so that applying the same value twice does no harm.
Reads are always answered, also while your mini app is not on screen: a
phone reads the last value your Lua set with ble.set_value, or the
manifest's value.
Lua: the ble table
With the ble.gatt permission, the global ble exists while your mini app is
on screen. Values are Lua strings of raw bytes: zero bytes and binary data
are kept as they are. Use string.unpack / string.pack for binary formats
and json.decode for JSON. id is always a characteristic id from your
manifest; any other name raises a Lua error.
| Function | Returns |
|---|---|
ble.on_write(id, fn) | Calls fn(value, conn) for every complete value written to id while your mini app is on screen |
ble.on_subscribe(id, fn) | Calls fn(conn, subscribed) when a phone turns notifications of id on (true) or off (false) |
ble.on_connect(fn) | Calls fn() when a phone connects to Kamoji |
ble.on_disconnect(fn) | Calls fn() when it disconnects |
ble.connected() | true while any phone is connected to Kamoji |
ble.value(id) | The newest retained value of id, or nil |
ble.values(id) | The retained values of id, oldest first: a list of up to retain_writes strings, {} when none |
ble.value_age_ms(id) | Milliseconds since the newest retained value arrived, or nil |
ble.set_value(id, bytes) | true; false when bytes is longer than max_length or 512 |
ble.notify(id, bytes) | true when the value is sent or queued; false otherwise (below) |
ble.mtu() | The connection's ATT MTU; 23 without a connection |
Handlers
ble.on_write, ble.on_subscribe, ble.on_connect and ble.on_disconnect
each keep one function: calling one again replaces the previous function. They
run on Kamoji's main loop like every other handler,
with the same 200 ms CPU limit, and all bindings are refreshed right after.
valueis the whole value: for achunkedcharacteristic, the assembled bytes without the piece headers. A characteristic without anon_writehandler still keeps its retained values.connis a number that identifies the connection. Since Kamoji has one connection at a time, you rarely need it.ble.on_connectandble.on_disconnectare called for any phone, including the Kamoji app, and only for changes while your mini app is on screen. A phone connected before your mini app opened does not callon_connect: checkble.connected()inmain.lua.ble.on_subscribeis likewise only called for changes while your mini app is on screen. A subscription made earlier still counts:ble.notifyreaches that phone.
ble.set_value
Sets what a phone reads from a read characteristic. It stays after your
mini app leaves the screen, so a phone can read it at any time. Kamoji goes
back to the manifest's value when it restarts and whenever a mini app is
installed or removed: set your read values in main.lua if they matter.
ble.notify
Sends bytes to the connected phone as notifications of id, if it
subscribed. It returns false, and sends nothing, when:
- the characteristic has no
notifyproperty, or no phone subscribed to it; - no phone is connected;
- the service is
kamoji_appand the connection is not authorized; bytesis longer than the characteristic'smax_length;- the queue of notifications waiting to go out (8 KB) has no room for it.
A value longer than the connection's MTU − 3 bytes is split into several notifications, sent in order, with no header: the receiver sees a stream of pieces, so your protocol must say where a value ends (a length, a newline, a fixed size). Pieces the radio can't take at once wait in the 8 KB queue and go out over the next moments; a value is either queued whole or not at all. Waiting pieces are dropped if the phone disconnects.
ble.mtu() tells you the piece size (MTU − 3). Phones usually raise the MTU
just after connecting, so it is 23 at first. An empty bytes sends one empty
notification.
-- A newline-ended JSON reply, one ble.notify per message.
local function send(t)
if not ble.notify("tx", json.encode(t) .. "\n") then
state.dropped = (state.dropped or 0) + 1
end
end
Connections
One phone at a time
Kamoji keeps one Bluetooth connection. While the Kamoji app is connected, your phone app can't connect, and while your phone app is connected, the Kamoji app can't. To use a phone app that talks to your mini app's services:
- Open your mini app on Kamoji.
- Disconnect the Kamoji app (close it, or disconnect in it).
- Connect from the other phone app.
Kamoji's link to a paired OBD-II adapter is separate and not affected.
Authorization and profile peers
Kamoji normally disconnects a connection that has not completed its authorization within 30 seconds, so a stranger can't keep Kamoji busy. A phone app made for another device never authorizes, so Kamoji makes an exception:
- A connection that writes to an
openservice of the mini app on screen, and whose write is handed to that mini app, becomes a profile peer. Kamoji no longer disconnects it for lacking authorization. It stays a profile peer until it disconnects. - So the phone must write within 30 seconds of connecting, while your mini app
is on screen. A phone that only reads or subscribes, or writes while your mini
app is not on screen, is disconnected after 30 seconds. If your protocol has the
phone wait for a notification first, send that notification from
ble.on_subscribe. - A profile peer still can't use Kamoji's own commands, and writes to a
kamoji_appservice never make a profile peer.
A connection that did authorize (the Kamoji app, or your tool) can use both
open and kamoji_app services.
ATT errors
What a phone can get back from a write with response (a write without response fails silently, and Kamoji counts it in its log):
| Error | Code | When |
|---|---|---|
| Read Not Permitted | 0x02 | A read of a kamoji_app service, and the connection did not authorize |
| Write Not Permitted | 0x03 | The value is not retained and your mini app is not on screen, or the queue of values waiting for your Lua is full; or the mini app was removed, or its updated services wait for a restart; or a kamoji_app service, and the connection did not authorize |
| Invalid Attribute Value Length | 0x0D | Longer than max_length (or 512); for a chunked value, the assembled value would pass max_length |
| Insufficient Resources | 0x11 | Kamoji had no memory for a chunked value |
| Value Not Allowed | 0x13 | A chunk with a bad header, out of order, or with another count: the unfinished value is dropped |
A write that is accepted means Kamoji received it, not that your Lua has processed it yet.
Testing
- A Bluetooth tool on a phone is the quickest way to try your services:
nRF Connect (Android, iOS) or LightBlue (iOS, Android). Open your mini app on
Kamoji, disconnect the Kamoji app, then connect to Kamoji in the tool (it
shows as
KMJ-XXXX, or under your advertising name every other 2 seconds). Your services are listed with their UUIDs; write values as text or hex, read them, and turn notifications on. - Write within 30 seconds of connecting with an
openservice, or Kamoji disconnects the tool (see profile peers). - Chunked values by hand: write
00 02+ the first half, then01 02+ the second half, as hex. - Your own scripts: any Bluetooth LE library works, for example
bleak in Python (see
DIY with Python for
connecting). To use a
kamoji_appservice, authorize first, as described in Bluetooth Protocol. - The log (over USB, see Debugging)
shows why an install was refused (
APP_COMMIT <id>: …), how many writes were dropped (dropped: … write(s) not taken, … chunked value(s)), and your ownprintoutput. - Test on Kamoji after a restart, and remember the phone may have cached the old services.
A complete example
Folder ble-hello. A phone writes a message and a 32 × 32 picture to
Kamoji; Kamoji shows them, counts taps on its top and sends the count back as
a notification. It shows a retained text value, a retained binary value drawn
with a bitmap widget, a read value
kept up to date with ble.set_value, notifications, connection state, and
advertising under its own name.
Generate your own UUIDs before you publish a mini app; these are only for the example.
ble-hello/manifest.json
{
"id": "ble-hello",
"name": "BLE Hello",
"version": "1.0.0",
"author": "Your Name",
"api_version": 1,
"min_firmware": "0.3.0",
"permissions": ["ble.gatt", "touch"],
"ble": {
"services": [
{
"id": "hello",
"uuid": "7d1e0001-5a8c-4c1e-9b3a-2f6d0c8e4a10",
"characteristics": [
{ "id": "message", "uuid": "7d1e0002-5a8c-4c1e-9b3a-2f6d0c8e4a10",
"properties": ["write", "write_no_response"], "max_length": 64, "retain": true },
{ "id": "icon", "uuid": "7d1e0003-5a8c-4c1e-9b3a-2f6d0c8e4a10",
"properties": ["write"], "max_length": 128, "retain": true },
{ "id": "taps", "uuid": "7d1e0004-5a8c-4c1e-9b3a-2f6d0c8e4a10",
"properties": ["read", "notify"], "max_length": 8, "value": "0" }
]
}
],
"advertising": { "name": "Kamoji Hello", "service_uuid": "7d1e0001-5a8c-4c1e-9b3a-2f6d0c8e4a10" }
}
}
ble-hello/main.lua
-- BLE Hello: a phone writes `message` (text) and `icon` (32x32, 1 bit per pixel);
-- a tap on the top counts, and the count is readable and notified as `taps`.
state.taps = 0
state.linked = ble.connected() -- a phone connected before we opened
ble.set_value("taps", "0")
-- Start from what Kamoji kept while we were not on screen.
state.message = ble.value("message") or "Write me a message"
icon = ble.value("icon") -- nil until a phone sends one
ble.on_write("message", function(bytes)
state.message = bytes ~= "" and bytes or "(empty)"
end)
ble.on_write("icon", function(bytes)
icon = bytes -- the bitmap hides itself if it is short
end)
ble.on_connect(function() state.linked = true end)
ble.on_disconnect(function() state.linked = false end)
-- Send the current count as soon as a phone subscribes.
ble.on_subscribe("taps", function(conn, subscribed)
if subscribed then ble.notify("taps", tostring(state.taps)) end
end)
function on_top_tap()
state.taps = state.taps + 1
local v = tostring(state.taps)
ble.set_value("taps", v)
ble.notify("taps", v) -- false when nobody subscribed: fine
end
function icon_data() return icon end
ble-hello/layout.json
{
"widgets": [
{ "type": "bitmap", "w": 32, "h": 32, "align": "center", "y": -62,
"data": "{{ icon_data() }}", "color": "gold" },
{ "type": "label", "font": "medium", "align": "center", "w": 200,
"text": "{{ state.message }}" },
{ "type": "label", "font": "small", "align": "center", "y": 50, "color": "grey",
"text": "Taps: {{ state.taps }}" },
{ "type": "label", "font": "small", "align": "center", "y": 76,
"text": "{{ state.linked and 'Phone connected' or 'Waiting for a phone' }}",
"color": "{{ state.linked and 'green' or 'grey' }}" }
]
}
To try it:
- Zip the folder's contents and install it with Install from file (Sideloading). Tap Restart when the Kamoji app asks.
- Open BLE Hello on Kamoji, then disconnect the Kamoji app.
- In nRF Connect or LightBlue, connect to Kamoji Hello (or
KMJ-XXXX). - Write some text to
7d1e0002-…: it appears on Kamoji. - Write 128 bytes to
7d1e0003-…as hex: 4 bytes a row, 32 rows, the leftmost pixel in the highest bit. A square outline isFFFFFFFF, then8000000130 times, thenFFFFFFFF. In Python:bytes([0xFF] * 4 + [0x80, 0, 0, 1] * 30 + [0xFF] * 4).hex(). - Turn on notifications for
7d1e0004-…and tap the top of Kamoji. - Switch Kamoji to another mode, write a new message, and come back: the mini
app opens with it, because
messageis retained.
For bigger, real-world mini apps built on Bluetooth services, see Bluetooth mini apps in the examples.