ble_scan.lua 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. --[[
  2. @module ble_ibeacon
  3. @summary Air8000演示ibeacon功能模块
  4. @version 1.0
  5. @date 2025.07.01
  6. @author wangshihao
  7. @usage
  8. 本文件为Air8000核心板演示scan功能的代码示例,核心业务逻辑为:
  9. 观察者模式(scan)的基本流程(概要描述)
  10. 1. 初始化蓝牙框架
  11. 2. 创建BLE对象
  12. local ble_device = bluetooth_device:ble(ble_event_cb)
  13. 3.设置扫描模式
  14. ble_device:scan_create() -- 使用默认参数, addr_mode=0, scan_interval=100, scan_window=100
  15. 4. 开始扫描
  16. ble_device:scan_start()
  17. 5. 在回调函数中处理扫描事件, 如接收设备信息等
  18. 6. 按需停止扫描
  19. ble_device:scan_stop()
  20. ]]
  21. local function ble_callback(ble_device, ble_event, ble_param)
  22. if ble_event == ble.EVENT_SCAN_INIT then
  23. log.info("ble", "scan init")
  24. elseif ble_event == ble.EVENT_SCAN_REPORT then
  25. log.info("ble", "scan report", ble_param.rssi, ble_param.adv_addr:toHex(), ble_param.data:toHex())
  26. -- 解析广播数据, 日志很多, 按需使用
  27. -- local adv_data = ble_device:adv_decode(ble_param.data)
  28. -- if adv_data then
  29. -- for k, v in pairs(adv_data) do
  30. -- log.info("ble", "adv data", v.len, v.tp, v.data:toHex())
  31. -- end
  32. -- end
  33. -- if ble_param.data:byte(1) == 0x1A then
  34. -- log.info("ble", "ibeacon数据", ble_param.rssi, ble_param.adv_addr:toHex(), ble_param.data:toHex())
  35. -- end
  36. elseif ble_event == ble.EVENT_SCAN_STOP then
  37. log.info("ble", "scan stop")
  38. end
  39. end
  40. local bt_scan = false -- 是否扫描蓝牙
  41. function ble_scan()
  42. sys.wait(500)
  43. log.info("开始初始化蓝牙核心")
  44. bluetooth_device = bluetooth.init()
  45. sys.wait(100)
  46. log.info("初始化BLE功能")
  47. ble_device = bluetooth_device:ble(ble_callback)
  48. if ble_device == nil then
  49. log.error("当前固件不支持完整的BLE")
  50. return
  51. end
  52. sys.wait(100)
  53. -- 扫描模式
  54. sys.wait(1000)
  55. ble_device:scan_create() -- 使用默认参数, addr_mode=0, scan_interval=100, scan_window=100
  56. -- ble_device:scan_create(0, 10, 10) -- 使用自定义参数
  57. sys.wait(100)
  58. log.info("开始扫描")
  59. ble_device:scan_start()
  60. -- sys.wait(15000)
  61. -- log.info("停止扫描")
  62. -- ble_device:scan_stop()
  63. end
  64. sys.taskInit(ble_scan)