TI-Nspire & BLE / Tiny BLE-Connection-Listener / SensorTag
The connection flow is as follows:
- The ble.addStateListener() function registers a listener-callback.
- The bleCentral.startScanning() function gets a scanner-callback to scan peripherals.
- The connect() function gets a connector-callback to connect a found peripheral.
.lua
-- Tiny BLE-Connection-Listener for TI-Nspire -- Tap the right half of the screen to start scanning. -- Tap the left half of the screen to stop scanning. require "bleCentral" require "color" local myPeripheral = nil local MESSAGES = {} function on.resize() W, H = platform.window:width(), platform.window:height() fontSize = W/20 lineSpace = H/11 leftMargin = W/50 refreshMenu() platform.window:invalidate() end function on.construction() ble.addStateListener(listenerCallback) end function on.paint(gc) gc:setFont("sansserif", "r", fontSize) for i, v in ipairs(MESSAGES) do gc:drawString(v, leftMargin, (i - 1) * lineSpace) end end ------------------------------ -- Define listener callback -- ------------------------------ function listenerCallback(state) MESSAGES[1] = "Listener Callback" MESSAGES[2] = " state: "..(state or "none") platform.window:invalidate() end ---------------------------- -- Start or Stop scanning -- ---------------------------- function peripheralOn() bleCentral.startScanning(scannerCallback) platform.window:invalidate() end function peripheralOff() bleCentral.stopScanning() if myPeripheral then myPeripheral:disconnect() MESSAGES[4] = " peri name: " ..(myPeripheral:getName() or "none") MESSAGES[5] = " peri state: "..(myPeripheral:getState() or "none") end platform.window:invalidate() end ----------------------------- -- Define scanner callback -- ----------------------------- function scannerCallback(peripheral, advertisementData, isConnectable, RSSI) if peripheral then peripheral:connect(connectorCallback) MESSAGES[3] = "Scanner Callback" MESSAGES[4] = " peri name: " ..(peripheral:getName() or "none") MESSAGES[5] = " peri state: "..(peripheral:getState() or "none") MESSAGES[6] = " RSSI: " ..(RSSI or "none").." dbm" end platform.window:invalidate() end ------------------------------- -- Define connector callback -- ------------------------------- function connectorCallback(peripheral, event) if peripheral then bleCentral.stopScanning() myPeripheral = peripheral end MESSAGES[7] = "Connector Callback" MESSAGES[8] = " peri name: " ..(peripheral:getName() or "none") MESSAGES[9] = " peri state: "..(peripheral:getState() or "none") MESSAGES[10] = " event: " ..(event or "none") platform.window:invalidate() end ------------------ -- Menu & Mouse -- ------------------ function refreshMenu() Menu = { {"Controls", {"Scan and Connect", function() peripheralOn() end}, {"Disconnect" , function() peripheralOff() end}, }, } toolpalette.register(Menu) end function on.mouseUp(x, _) if x > W/2 then peripheralOn() end if x < W/2 then peripheralOff() end end