Python编程.Bluetooth HID Mouse and Keyboard(二)

根据Bluetooth HID协议,蓝牙设备在0x11和0x13这两个PSM上监听并接收从蓝牙主机发来的L2CAP连接请求。所以,从Socket连接的角度来看,蓝牙设备其实是L2CAP连接的Host端,而蓝牙主机则是L2CAP连接的Client端,这跟它们在Bluetooth HID协议中的角色正相反。

接下来我就要用Python来实践蓝牙设备端的Socket工作流。

当然,根据上一篇文章的介绍,我首先要用C语言实现一些友好的接口,让Python程序通过ctypes能够很容易地使用。

struct bthidd_t {
	int serv_ctrl;
	int serv_intr;
	int sock_ctrl;
	int sock_intr;
	int b_shutdown;
};
struct bthidd_t * bthidd_init(void);
void bthidd_exit(struct bthidd_t *p_hidd);
void bthidd_shutdown(struct bthidd_t *p_hidd, int shutdown);
int bthidd_accept(struct bthidd_t *p_hidd);
int bthidd_ctrl_send(struct bthidd_t *p_hidd, char *data, int len);
int bthidd_intr_send(struct bthidd_t *p_hidd, char *data, int len);

由于Mouse和Keyboard设备只需要通过HID Interrupt通道向主机发送HID Report,因此暂时只设计了send接口。以下是这些接口的实现。

#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/l2cap.h>

#define	PSMHIDCTL	  0x11
#define	PSMHIDINT  0x13

struct bthidd_t {
	int serv_ctrl;
	int serv_intr;
	int sock_ctrl;
	int sock_intr;
	int b_shutdown;
};

// Wrapper for bind, caring for all the surrounding variables
static int bth_bind(int sockfd, unsigned short port) {
	struct sockaddr_l2 l2a;
	int i;
	memset(&l2a, 0, sizeof(l2a));
	l2a.l2_family = AF_BLUETOOTH;
	bacpy(&l2a.l2_bdaddr, BDADDR_ANY);
	l2a.l2_psm = htobs(port);
	i = bind(sockfd, (struct sockaddr *)&l2a, sizeof(l2a));
	if (0 > i) {
		fprintf(stderr, "Bind error (PSM %d): %s.\n", port, strerror(errno));
	}
	return i;
}

struct bthidd_t * bthidd_init(void) {
	struct bthidd_t * p_hidd;
	int ret;

	p_hidd = malloc(sizeof(struct bthidd_t));
	if (!p_hidd) { goto _err; }
	memset(p_hidd, 0, sizeof(struct bthidd_t));

	// Open, bind and listen socket for HID-Control.
	p_hidd->serv_ctrl = socket(AF_BLU
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值