Просмотр исходного кода

update: 完善nimble库的Peripheral模式的demo,俗称从机,被连接被扫描的设备

Wendal Chen 3 лет назад
Родитель
Сommit
f5d151bea7

+ 47 - 61
components/nimble/src/luat_nimble_mode_peripheral.c

@@ -24,21 +24,21 @@
 #include "nimble/nimble_port.h"
 // #include "nimble/nimble_port_freertos.h"
 
-/* Heart-rate configuration */
-#define GATT_HRS_UUID                           0x180D
-#define GATT_HRS_MEASUREMENT_UUID               0x2A37
-#define GATT_HRS_BODY_SENSOR_LOC_UUID           0x2A38
-#define GATT_DEVICE_INFO_UUID                   0x180A
-#define GATT_MANUFACTURER_NAME_UUID             0x2A29
-#define GATT_MODEL_NUMBER_UUID                  0x2A24
-
-/** GATT server. */
-#define GATT_SVR_SVC_ALERT_UUID               0x1811
-#define GATT_SVR_CHR_SUP_NEW_ALERT_CAT_UUID   0x2A47
-#define GATT_SVR_CHR_NEW_ALERT                0x2A46
-#define GATT_SVR_CHR_SUP_UNR_ALERT_CAT_UUID   0x2A48
-#define GATT_SVR_CHR_UNR_ALERT_STAT_UUID      0x2A45
-#define GATT_SVR_CHR_ALERT_NOT_CTRL_PT        0x2A44
+// /* Heart-rate configuration */
+// #define GATT_HRS_UUID                           0x180D
+// #define GATT_HRS_MEASUREMENT_UUID               0x2A37
+// #define GATT_HRS_BODY_SENSOR_LOC_UUID           0x2A38
+// #define GATT_DEVICE_INFO_UUID                   0x180A
+// #define GATT_MANUFACTURER_NAME_UUID             0x2A29
+// #define GATT_MODEL_NUMBER_UUID                  0x2A24
+
+// /** GATT server. */
+// #define GATT_SVR_SVC_ALERT_UUID               0x1811
+// #define GATT_SVR_CHR_SUP_NEW_ALERT_CAT_UUID   0x2A47
+// #define GATT_SVR_CHR_NEW_ALERT                0x2A46
+// #define GATT_SVR_CHR_SUP_UNR_ALERT_CAT_UUID   0x2A48
+// #define GATT_SVR_CHR_UNR_ALERT_STAT_UUID      0x2A45
+// #define GATT_SVR_CHR_ALERT_NOT_CTRL_PT        0x2A44
 
 // extern uint16_t hrs_hrm_handle;
 
@@ -50,9 +50,9 @@ struct ble_gatt_register_ctxt;
 static void gatt_svr_register_cb(struct ble_gatt_register_ctxt *ctxt, void *arg);
 static int gatt_svr_init(void);
 
-static const char *manuf_name = "LuatOS";
-static const char *model_num = "BLE Demo";
-static uint16_t hrs_hrm_handle;
+// static const char *manuf_name = "LuatOS";
+// static const char *model_num = "BLE Demo";
+// static uint16_t hrs_hrm_handle;
 static uint16_t g_ble_attr_indicate_handle;
 static uint16_t g_ble_attr_write_handle;
 extern uint16_t g_ble_conn_handle;
@@ -81,13 +81,13 @@ typedef struct ble_write_msg {
     char buff[1];
 }ble_write_msg_t;
 
-static int
-gatt_svr_chr_access_heart_rate(uint16_t conn_handle, uint16_t attr_handle,
-                               struct ble_gatt_access_ctxt *ctxt, void *arg);
+// static int
+// gatt_svr_chr_access_heart_rate(uint16_t conn_handle, uint16_t attr_handle,
+//                                struct ble_gatt_access_ctxt *ctxt, void *arg);
 
-static int
-gatt_svr_chr_access_device_info(uint16_t conn_handle, uint16_t attr_handle,
-                                struct ble_gatt_access_ctxt *ctxt, void *arg);
+// static int
+// gatt_svr_chr_access_device_info(uint16_t conn_handle, uint16_t attr_handle,
+//                                 struct ble_gatt_access_ctxt *ctxt, void *arg);
 
 static int
 gatt_svr_chr_access_func(uint16_t conn_handle, uint16_t attr_handle,
@@ -213,34 +213,34 @@ static void gatt_svr_register_cb(struct ble_gatt_register_ctxt *ctxt, void *arg)
     LLOGD("gatt_svr_register_cb op %d", ctxt->op);
     switch (ctxt->op) {
     case BLE_GATT_REGISTER_OP_SVC:
-        LLOGD("registered service %s with handle=%d\n",
+        LLOGD("registered service %s with handle=%d",
                     ble_uuid_to_str(ctxt->svc.svc_def->uuid, buf),
                     ctxt->svc.handle);
         break;
 
     case BLE_GATT_REGISTER_OP_CHR:
         LLOGD("registering characteristic %s with "
-                    "def_handle=%d val_handle=%d\n",
+                    "def_handle=%d val_handle=%d",
                     ble_uuid_to_str(ctxt->chr.chr_def->uuid, buf),
                     ctxt->chr.def_handle,
                     ctxt->chr.val_handle);
         break;
 
     case BLE_GATT_REGISTER_OP_DSC:
-        LLOGD("registering descriptor %s with handle=%d\n",
+        LLOGD("registering descriptor %s with handle=%d",
                     ble_uuid_to_str(ctxt->dsc.dsc_def->uuid, buf),
                     ctxt->dsc.handle);
         break;
 
     default:
-        assert(0);
+        // assert(0);
         break;
     }
 }
 
 static int l_ble_chr_write_cb(lua_State* L, void* ptr) {
     ble_write_msg_t* wmsg = (ble_write_msg_t*)ptr;
-    rtos_msg_t* msg = (rtos_msg_t*)lua_topointer(L, -1);
+    // rtos_msg_t* msg = (rtos_msg_t*)lua_topointer(L, -1);
     lua_getglobal(L, "sys_pub");
     if (lua_isfunction(L, -1)) {
         lua_pushstring(L, "BLE_GATT_WRITE_CHR");
@@ -256,7 +256,7 @@ static int
 gatt_svr_chr_access_func(uint16_t conn_handle, uint16_t attr_handle,
                                struct ble_gatt_access_ctxt *ctxt, void *arg)
 {
-    int i = 0;
+    // int i = 0;
     struct os_mbuf *om = ctxt->om;
     ble_write_msg_t* wmsg;
     rtos_msg_t msg = {0};
@@ -280,7 +280,7 @@ gatt_svr_chr_access_func(uint16_t conn_handle, uint16_t attr_handle,
         case BLE_GATT_ACCESS_OP_READ_CHR:
             return 0;
         default:
-            assert(0);
+            // assert(0);
             return BLE_ATT_ERR_UNLIKELY;
     }
 }
@@ -352,7 +352,7 @@ bleprph_print_conn_desc(struct ble_gap_conn_desc *desc)
     LLOGI(" peer_ota_addr_type=%d peer_ota_addr=" ADDR_FMT, desc->peer_ota_addr.type, ADDR_T(desc->peer_ota_addr.val));
     LLOGI(" peer_id_addr_type=%d peer_id_addr=" ADDR_FMT, desc->peer_id_addr.type, ADDR_T(desc->peer_id_addr.val));
     LLOGI(" conn_itvl=%d conn_latency=%d supervision_timeout=%d "
-                "encrypted=%d authenticated=%d bonded=%d\n",
+                "encrypted=%d authenticated=%d bonded=%d",
                 desc->conn_itvl, desc->conn_latency,
                 desc->supervision_timeout,
                 desc->sec_state.encrypted,
@@ -467,7 +467,7 @@ bleprph_advertise(void)
 
     rc = ble_gap_adv_set_fields(&fields);
     if (rc != 0) {
-        LLOGE("error setting advertisement data; rc=%d\n", rc);
+        LLOGE("error setting advertisement data; rc=%d", rc);
         return;
     }
 
@@ -478,7 +478,7 @@ bleprph_advertise(void)
     rc = ble_gap_adv_start(own_addr_type, NULL, BLE_HS_FOREVER,
                            &adv_params, bleprph_gap_event, NULL);
     if (rc != 0) {
-        LLOGE("error enabling advertisement; rc=%d\n", rc);
+        LLOGE("error enabling advertisement; rc=%d", rc);
         return;
     }
 }
@@ -521,7 +521,7 @@ bleprph_gap_event(struct ble_gap_event *event, void *arg)
         else {
             g_ble_state = BT_STATE_DISCONNECT;
         }
-        // LLOGI("\n");
+        // LLOGI("");
 
         if (event->connect.status != 0) {
             /* Connection failed; resume advertising. */
@@ -537,7 +537,7 @@ bleprph_gap_event(struct ble_gap_event *event, void *arg)
         g_ble_state = BT_STATE_DISCONNECT;
         LLOGI("disconnect; reason=%d ", event->disconnect.reason);
         bleprph_print_conn_desc(&event->disconnect.conn);
-        // LLOGI("\n");
+        // LLOGI("");
 
         /* Connection terminated; resume advertising. */
 #if CONFIG_EXAMPLE_EXTENDED_ADV
@@ -553,7 +553,7 @@ bleprph_gap_event(struct ble_gap_event *event, void *arg)
         rc = ble_gap_conn_find(event->conn_update.conn_handle, &desc);
         if (rc == 0)
             bleprph_print_conn_desc(&desc);
-        // LLOGI("\n");
+        // LLOGI("");
         return 0;
 
     case BLE_GAP_EVENT_ADV_COMPLETE:
@@ -570,12 +570,12 @@ bleprph_gap_event(struct ble_gap_event *event, void *arg)
         rc = ble_gap_conn_find(event->enc_change.conn_handle, &desc);
         if (rc == 0)
             bleprph_print_conn_desc(&desc);
-        // LLOGI("\n");
+        // LLOGI("");
         return 0;
 
     case BLE_GAP_EVENT_SUBSCRIBE:
         LLOGI("subscribe event; conn_handle=%d attr_handle=%d "
-                    "reason=%d prevn=%d curn=%d previ=%d curi=%d\n",
+                    "reason=%d prevn=%d curn=%d previ=%d curi=%d",
                     event->subscribe.conn_handle,
                     event->subscribe.attr_handle,
                     event->subscribe.reason,
@@ -586,7 +586,7 @@ bleprph_gap_event(struct ble_gap_event *event, void *arg)
         return 0;
 
     case BLE_GAP_EVENT_MTU:
-        LLOGI("mtu update event; conn_handle=%d cid=%d mtu=%d\n",
+        LLOGI("mtu update event; conn_handle=%d cid=%d mtu=%d",
                     event->mtu.conn_handle,
                     event->mtu.channel_id,
                     event->mtu.value);
@@ -600,7 +600,7 @@ bleprph_gap_event(struct ble_gap_event *event, void *arg)
 
         /* Delete the old bond. */
         rc = ble_gap_conn_find(event->repeat_pairing.conn_handle, &desc);
-        assert(rc == 0);
+        // assert(rc == 0);
         ble_store_util_delete_peer(&desc.peer_id_addr);
 
         /* Return BLE_GAP_REPEAT_PAIRING_RETRY to indicate that the host should
@@ -619,7 +619,7 @@ bleprph_gap_event(struct ble_gap_event *event, void *arg)
             pkey.passkey = 123456; // This is the passkey to be entered on peer
             // LLOGI("Enter passkey %d on the peer side", pkey.passkey);
             rc = ble_sm_inject_io(event->passkey.conn_handle, &pkey);
-            LLOGI("ble_sm_inject_io BLE_SM_IOACT_DISP result: %d\n", rc);
+            LLOGI("ble_sm_inject_io BLE_SM_IOACT_DISP result: %d", rc);
         } else if (event->passkey.params.action == BLE_SM_IOACT_NUMCMP) {
             LLOGI("Passkey on device's display: %d", event->passkey.params.numcmp);
             LLOGI("Accept or reject the passkey through console in this format -> key Y or key N");
@@ -632,7 +632,7 @@ bleprph_gap_event(struct ble_gap_event *event, void *arg)
             // }
             pkey.numcmp_accept = 1;
             rc = ble_sm_inject_io(event->passkey.conn_handle, &pkey);
-            LLOGI("ble_sm_inject_io BLE_SM_IOACT_NUMCMP result: %d\n", rc);
+            LLOGI("ble_sm_inject_io BLE_SM_IOACT_NUMCMP result: %d", rc);
         } else if (event->passkey.params.action == BLE_SM_IOACT_OOB) {
             static uint8_t tem_oob[16] = {0};
             pkey.action = event->passkey.params.action;
@@ -640,7 +640,7 @@ bleprph_gap_event(struct ble_gap_event *event, void *arg)
                 pkey.oob[i] = tem_oob[i];
             }
             rc = ble_sm_inject_io(event->passkey.conn_handle, &pkey);
-            LLOGI("ble_sm_inject_io BLE_SM_IOACT_OOB result: %d\n", rc);
+            LLOGI("ble_sm_inject_io BLE_SM_IOACT_OOB result: %d", rc);
         } else if (event->passkey.params.action == BLE_SM_IOACT_INPUT) {
             LLOGI("Passkey on device's display: %d", event->passkey.params.numcmp);
             LLOGI("Enter the passkey through console in this format-> key 123456");
@@ -653,7 +653,7 @@ bleprph_gap_event(struct ble_gap_event *event, void *arg)
             // }
             pkey.passkey = event->passkey.params.numcmp;
             rc = ble_sm_inject_io(event->passkey.conn_handle, &pkey);
-            LLOGI("ble_sm_inject_io BLE_SM_IOACT_INPUT result: %d\n", rc);
+            LLOGI("ble_sm_inject_io BLE_SM_IOACT_INPUT result: %d", rc);
         }
 #endif
         return 0;
@@ -687,7 +687,7 @@ bleprph_on_sync(void)
 #else
     rc = ble_hs_util_ensure_addr(0);
 #endif
-    assert(rc == 0);
+    // assert(rc == 0);
 
     /* Figure out address to use while advertising (no privacy for now) */
     rc = ble_hs_id_infer_auto(0, &own_addr_type);
@@ -709,7 +709,7 @@ bleprph_on_sync(void)
     }
     ble_gatts_start();
     //print_addr(addr_val);
-    // LLOGI("\n");
+    // LLOGI("");
     /* Begin advertising. */
 #if CONFIG_EXAMPLE_EXTENDED_ADV
     ext_bleprph_advertise();
@@ -727,25 +727,12 @@ int luat_nimble_init_peripheral(uint8_t uart_idx, char* name, int mode) {
     int rc = 0;
     nimble_port_init();
 
-    // if (name == NULL || strlen(name) == 0) {
-    //     if (selfname[0] == 0) {
-    //         memcpy(selfname, "LuatOS", strlen("LuatOS") + 1);
-    //     }
-    // }
-    // else {
-    //     memcpy(selfname, name, strlen(name) + 1);
-    // }
-    char buff[32] = {0};
-    // char mac[6] = {0};
     /* Set the default device name. */
     if (name != NULL && strlen(name)) {
         rc = ble_svc_gap_device_name_set((const char*)name);
         ble_use_custom_name = 1;
     }
 
-        
-
-
     /* Initialize the NimBLE host configuration. */
     ble_hs_cfg.reset_cb = bleprph_on_reset;
     ble_hs_cfg.sync_cb = bleprph_on_sync;
@@ -755,7 +742,6 @@ int luat_nimble_init_peripheral(uint8_t uart_idx, char* name, int mode) {
     ble_hs_cfg.sm_io_cap = BLE_SM_IO_CAP_NO_IO;
     ble_hs_cfg.sm_sc = 0;
 
-
     ble_svc_gap_init();
     ble_svc_gatt_init();
 

+ 0 - 58
demo/nimble/esp32c3/main.lua

@@ -1,58 +0,0 @@
-
--- LuaTools需要PROJECT和VERSION这两个信息
-PROJECT = "nimbledemo"
-VERSION = "1.0.0"
-
-log.info("main", PROJECT, VERSION)
-
--- 一定要添加sys.lua !!!!
-sys = require("sys")
-
--- --添加硬狗防止程序卡死
--- if wdt then
---     wdt.init(9000)--初始化watchdog设置为9s
---     sys.timerLoopStart(wdt.feed, 3000)--3s喂一次狗
--- end
-
--- 监听BLE主适配的状态变化
--- sys.subscribe("BLE_STATE_INC", function(state)
---     log.info("ble", "ble state changed", state)
---     if state == 1 then
---         nimble.server_init()
---     else
---         nimble.server_deinit()
---     end
--- end)
-
--- 监听GATT服务器的WRITE_CHR, 收到Write数据时会回调该函数
-sys.subscribe("BLE_GATT_WRITE_CHR", function(info, data)
-    -- info 是个table, 但当前没有数据
-    -- data 是BLE收到的数据
-    log.info("ble", "data got!!", data:toHex())
-end)
-
--- TODO 支持传数据(read)和推送数据(notify)
-
--- 配合微信小程序 "LuatOS蓝牙调试"
--- 1. 若开发板无天线, 将手机尽量靠近芯片也能搜到
--- 2. 该小程序是开源的, 每次write会自动分包
--- https://gitee.com/openLuat/luatos-miniapps
-
-sys.taskInit(function()
-    sys.wait(1000)
-    -- nimble.debug(6)
-    -- 默认模式是BLE server, 无pin码验证
-    nimble.init("LuatOS-" .. wlan.getMac()) -- 蓝牙名称可修改
-
-    -- 下面是周期性发送数据, nimble.send_msg可在任意代码中调用, 不依赖task
-    while 1 do
-        sys.wait(3000)
-        nimble.send_msg(1, 0, string.char(0x5A, 0xA5, 0x12, 0x34, 0x56))
-    end
-end)
-
-
--- 用户代码已结束---------------------------------------------
--- 结尾总是这一句
-sys.run()
--- sys.run()之后后面不要加任何语句!!!!!

+ 18 - 12
demo/nimble/Air103/main.lua → demo/nimble/peripheral/main.lua

@@ -1,8 +1,20 @@
 
 -- LuaTools需要PROJECT和VERSION这两个信息
-PROJECT = "nimbledemo"
+PROJECT = "bledemo"
 VERSION = "1.0.0"
 
+--[[
+BLE peripheral/外设/从机的demo, 等待被连接
+支持的模块:
+1. Air101/Air103, 开发板的BLE天线未引出, 需要靠近使用, 且功耗高
+2. ESP32系列, 包括ESP32C3/ESP32S3
+
+-- 配合微信小程序 "LuatOS蓝牙调试"
+-- 1. 若开发板无天线, 将手机尽量靠近芯片也能搜到
+-- 2. 该小程序是开源的, 每次write会自动分包
+-- https://gitee.com/openLuat/luatos-miniapps
+]]
+
 log.info("main", PROJECT, VERSION)
 
 -- 一定要添加sys.lua !!!!
@@ -24,24 +36,17 @@ sys.subscribe("BLE_STATE_INC", function(state)
     end
 end)
 
--- 监听GATT服务器的WRITE_CHR
+-- 监听GATT服务器的WRITE_CHR, 也就是收取数据的回调
 sys.subscribe("BLE_GATT_WRITE_CHR", function(info, data)
     -- info 是个table, 但当前没有数据
     log.info("ble", "data got!!", data:toHex())
 end)
 
--- TODO 支持传数据(read)和推送数据(notify)
-
--- 配合微信小程序 "LuatOS蓝牙调试"
--- 1. 若开发板无天线, 将手机尽量靠近芯片也能搜到
--- 2. 该小程序是开源的, 每次write会自动分包
--- https://gitee.com/openLuat/luatos-miniapps
-
 sys.taskInit(function()
     sys.wait(2000)
 
     -- BLE模式, 默认是SERVER/Peripheral,即外设模式, 等待被连接的设
-    -- nimble.mode(nimble.MODE_BLE_SERVER)
+    -- nimble.mode(nimble.MODE_BLE_SERVER) -- 默认就是它, 不用调用
 
     -- 设置SERVER/Peripheral模式下的UUID, 支持设置3个
     -- 地址支持 2/4/16字节, 需要二进制数据, 例如 string.fromHex("AABB") 返回的是2个字节数据,0xAABB
@@ -51,11 +56,12 @@ sys.taskInit(function()
         nimble.setUUID("indicate", string.fromHex("FF32")) -- 订阅本设备的数据的UUID,默认值 FFF2
     end
 
-    -- nimble.debug(6)
+    -- 可以自定义名称
     -- nimble.init("LuatOS-Wendal") -- 蓝牙名称可修改,也有默认值LOS-$mac地址
     nimble.init() -- 蓝牙名称可修改,也有默认值LOS-$mac地址
 
-    if nimble.send_msg then
+    -- 发送数据
+    if nimble.send_msg then -- 老固件没这个API,请升级固件
         while 1 do
             sys.wait(3000)
             nimble.send_msg(1, 0, string.char(0x5A, 0xA5, 0x12, 0x34, 0x56))