Registers a callback to be executed when another Bluetooth device attempts to connect to the imp
Device
Only available on the imp004m and imp006 (impOS 42)
Name | Type | Description |
---|---|---|
callback | Function |
A function triggered when a connection attempt is made
|
Nothing
This method allows other Bluetooth devices to connect to a compatible imp, and registers a function that will be called when a device attempts to connect. When it is called, it also updates the type of the advertisement broadcast by the imp to ADV_IND (see bluetooth.startadvertise()).
To prevent any remote devices connecting to the imp, pass null
into bluetooth.onconnect(). This is the default state.
The function passed into the parameter callback takes one parameter of its own: a btconnection object. This provides a set of methods with which to manage the connection between the imp and the remote device:
When close() is called on the btconnection object, the connection can no longer be used. This will also occur if the btconnection object goes out of scope. In neither case will any function registered with onclose() be called.
This simple snippet simply logs connections from remote devices as they are attempted, and signals if they were closed by the remote device
bt.onconnect(function (conn) {
server.log("Connection attempt made from " + conn.address());
// Register the remote closure notifier function
conn.onclose(function () {
server.log("Connection closed by " + conn.address());
});
// Does the connection meet the required level of security?
if (conn.security() < 4) {
// No, it doesn't so close the connection immediately
// Note this will NOT trigger the onclose() callback
conn.close();
return;
}
// Is the device attempting to connect a known one?
if (!macOnAllowedList(conn.address()) {
// Unknown device - close the connection
// Note this will NOT trigger the onclose() callback
conn.close();
}
});
function macOnAllowedList(mac) {
// Assume a global variable ‘permittedMACs` is an array of MAC addresses
for (aMAC in permittedMACs) {
if (aMAC == mac) return true;
}
return false;
}