読者です 読者をやめる 読者になる 読者になる

TI-Nspire & BLE / SimpleLink SensorTag をつなぐ

The following script, which is from http://compasstech.com.au/TNS_Authoring/Scripting/script_tut30.html, will try to establish a connection with BLE devices.


.lua

-- Source: http://compasstech.com.au/TNS_Authoring/Scripting/script_tut30.html
platform.apilevel = '2.5'
screen = platform.window
w = screen:width()
h = screen:height()
pcall(function () require 'bleCentral' end)
require "color"
local bleState       = ''
local bleStatus      = 'Stand by'
local peripheralName = ''
local myPeripheral   = nil

function on.resize()
   w = screen:width() or 841
   h = screen:height() or 567
   pcall(function() ble.addStateListener(listenerCallback) end)
   refreshMenu()
   screen:invalidate()
end
function on.paint(gc)
   w = screen:width() or 841
   h = screen:height() or 567
   if bleState:find("ON") then
      gc:setColorRGB(color.blue)
   else
      gc:setColorRGB(color.red)
   end
   --gc:setFont("sansserif", "b", 12)
   gc:setFont("sansserif", "b", w/15)
   gc:drawString(bleState      , 0.1*w, 0.1*h)
   gc:drawString(bleStatus     , 0.1*w, 0.2*h)
   gc:drawString(peripheralName, 0.1*w, 0.3*h)
end

--BLE STATE LISTENER -----------

function listenerCallback(state, scriptError)
   if     state == ble.ON          then bleState = 'BLE ON'
   elseif state == ble.OFF         then bleState = 'BLE OFF'
   elseif state == ble.RESETTING   then bleState = 'BLE RESET'
   elseif state == ble.UNSUPPORTED then bleState = 'UNSUPPORTED'
      if scriptError then print('Error message: BLE not supported') end
   end
   screen:invalidate()
end

-- BLE PERIPHERALS -----------------------

function peripheralOn()
   bleCentral.startScanning(callbackScan)
   bleStatus = 'Scanning' 
   screen:invalidate()
end
function peripheralOff()
   bleCentral.stopScanning()
   if myPeripheral then
      myPeripheral:disconnect()
   end
   bleStatus = 'Stand by' 
   screen:invalidate()
end
function callbackScan(peripheral)
   if peripheral ~= nil then
      peripheralName = peripheral:getName() 
   end
   peripheral:connect(callbackConnect) 
   screen:invalidate()
end
function callbackConnect(peripheral, event)
  if event == bleCentral.CONNECTED then 
      bleCentral.stopScanning()
      bleStatus = 'Connected'
      myPeripheral = peripheral
   elseif event == bleCentral.DISCONNECTED then 
      bleStatus = 'Disconnected'
      peripheralName = ''
   end
   screen:invalidate()
end

--Menu-----------------------------------

function refreshMenu()
   Menu = {
      {"Controls",
         {"Scan and Connect", function() peripheralOn()  end},
         {"Disconnect"      , function() peripheralOff() end},
         {"Reset"           , function() bleState = '' bleStatus = 'Stand by' on.resize() end},
      },
   }
   toolpalette.register(Menu)
end
広告を非表示にする