【问题标题】:How to program a Bluetooth LE device using C on Linux x86?如何在 Linux x86 上使用 C 对蓝牙 LE 设备进行编程?
【发布时间】:2015-06-01 07:17:06
【问题描述】:

我有一个蓝牙设备,我可以在 Linux 上使用 gatttool 来控制它。我想开发自己的可以向其发送命令的 c 程序。

我以前做过蓝牙编程,比较简单,类似于网络编程,但这次是蓝牙低功耗设备,遵循here的原则,当我可以清楚地看到主机已关闭消息时使用 gatttool 连接/断开连接。

如何创建这个程序?我知道我应该使用 bluez 库,但我不确定从哪里开始使用低能耗设备。

int main(int argc, char **argv)
{
   struct sockaddr_rc addr = { 0 };
   int s, status;
   char dest[18] = "B4:99:4C:5C:EE:49";
   char buf[2048];
   pthread_t rthread;

   setbuf(stdout, NULL); 
   // allocate a socket
   s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
   // set the connection parameters (who to connect to)
   addr.rc_family = AF_BLUETOOTH;
   addr.rc_channel = (uint8_t) 1;
   str2ba( dest, &addr.rc_bdaddr );
   // connect to server
   status = connect(s, (struct sockaddr *)&addr, sizeof(addr));

   if( status < 0 ){
      perror("Error connecting to host\n");
      exit(1);
   }

   while(fgets(buf, sizeof(buf), stdin) != NULL){
      status = send(s, buf, sizeof(buf), 0);
      if(status < 0){
         printf("Error sending.\n");
     exit(1);
      }
   }

   close(s);

   return;

【问题讨论】:

    标签: c bluetooth bluetooth-lowenergy bluez intel-edison


    【解决方案1】:

    我也一直在尝试弄清楚如何做到这一点:您可能想查看 Github 上 sandeepmistry/noble:src/l2cap-ble.c 中的源代码。 (C 组件在此提交中被排除,因此您需要查看旧版本的源代码。)

    在构建它(需要libbluetooth-dev)并运行它之后,l2cap-ble 示例实质上创建了一个与 BLE 设备的简单的类似 TTY 的连接:

    $ gcc -o l2cap-ble l2cap-ble.c utility.c -lbluetooth
    $ ./l2cap-ble 12:34:56:78:9A:BC [public|random]
    

    源代码说明了一些需要穿插在标准套接字 I/O 代码中的 BLE 特定函数 (hci_*)。

    更新:我从以下代码开始编写了一个更充实、功能更全面的程序:https://github.com/dlenski/ttblue。您可以将此源代码用作如何使用 Bluez 与 BLE 小工具通信的示例。

    【讨论】:

    • 您的代码不再可用。可以发一下吗?
    • 这不是我的代码。但是,我基于它编写了一个更充实、功能更全面的程序。您可以将此作为如何使用 Bluez 与 BLE 小工具通信的示例:github.com/dlenski/ttblue
    【解决方案2】:

    您的程序适用于经典蓝牙,为了支持我的说法,我会说开启任何经典蓝牙设备,您的代码都可以正常工作

    要获得 lescan,我建议通过此链接。sudo ./st 将扫描附近的 ble divices

    https://github.com/carsonmcdonald/bluez-experiments

    【讨论】:

      【解决方案3】:

      github.com 上的另一个项目看起来很干净:https://github.com/edrosten/libblepp

      这里的讨论中提到过:https://mbientlab.com/community/discussion/2492/bluetooth-le-library-linux

      虽然它是 C++ 而不是 C。

      【讨论】:

        猜你喜欢
        • 2016-04-11
        • 1970-01-01
        • 1970-01-01
        • 2014-10-04
        • 1970-01-01
        • 1970-01-01
        • 2021-12-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多