Comunicação Linux USB e Bluetooth

12 de agosto de 2021 Off Por Marcelo Martins

Muitas vezes temos a necessidade de realizar comunicação direta com dispositivos USB e/ou Bluetooth.

A Lib hidapi, permite realizar a comunicação através destes dispositivos, em sistemas windows, linux e mac.

Estarei apresentando brevemente esta api, e detalhando um pouco de sua instalação.

GIT da api

https://github.com/signal11/hidapi

Documentação do fabricante

O Projeto do GIT pode ser visto em:

https://github.com/libusb/hidapi

o processo de instalação pode ser visto em:

https://github.com/libusb/hidapi#installing-hidapi

Instalação no Linux

A instalação para execução necessita apenas da lib.

apt install libhidapi

Porem se voce quer desenvolver, precisará instalar o pacote de desenvolvimento:

apt install libhidapi-dev

Pacotes acessórios

apt install libhidapi-libusb libhidapi-hidraw

O hidraw é usado para integração com o kernel do linux e suporta o desenvimento de usb e bluetooth.

Já o usb é usado diretamente na camada de aplicação. Caso se deseja construir apenas uma das opções, a outra pode ser não utilizada.

Exemplo de código

#ifdef WIN32
#include <windows.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include "hidapi.h"

#define MAX_STR 255

int main(int argc, char* argv[])
{
	int res;
	unsigned char buf[65];
	wchar_t wstr[MAX_STR];
	hid_device *handle;
	int i;

	// Initialize the hidapi library
	res = hid_init();

	// Open the device using the VID, PID,
	// and optionally the Serial number.
	handle = hid_open(0x4d8, 0x3f, NULL);

	// Read the Manufacturer String
	res = hid_get_manufacturer_string(handle, wstr, MAX_STR);
	wprintf(L"Manufacturer String: %s\n", wstr);

	// Read the Product String
	res = hid_get_product_string(handle, wstr, MAX_STR);
	wprintf(L"Product String: %s\n", wstr);

	// Read the Serial Number String
	res = hid_get_serial_number_string(handle, wstr, MAX_STR);
	wprintf(L"Serial Number String: (%d) %s\n", wstr[0], wstr);

	// Read Indexed String 1
	res = hid_get_indexed_string(handle, 1, wstr, MAX_STR);
	wprintf(L"Indexed String 1: %s\n", wstr);

	// Toggle LED (cmd 0x80). The first byte is the report number (0x0).
	buf[0] = 0x0;
	buf[1] = 0x80;
	res = hid_write(handle, buf, 65);

	// Request state (cmd 0x81). The first byte is the report number (0x0).
	buf[0] = 0x0;
	buf[1] = 0x81;
	res = hid_write(handle, buf, 65);

	// Read requested state
	res = hid_read(handle, buf, 65);

	// Print out the returned buffer.
	for (i = 0; i < 4; i++)
		printf("buf[%d]: %d\n", i, buf[i]);

	// Close the device
	hid_close(handle);

	// Finalize the hidapi library
	res = hid_exit();

	return 0;
}

No exemplo acima temos alguns fragmentos importantes.

hid_init

Esta função inicializa a biblioteca;

hid_open

A função hid_open, carrega o device, sempre pedindo o VID e o PID do dispositivo USB.

hid_close

A função close, descarrega a função, tendo ser chamada ao fim de sua execução.