Skip to content

Instantly share code, notes, and snippets.

@KennFatt
Created May 28, 2020 04:53
Show Gist options
  • Save KennFatt/68227b6856a622584a83a0d24ec2b519 to your computer and use it in GitHub Desktop.
Save KennFatt/68227b6856a622584a83a0d24ec2b519 to your computer and use it in GitHub Desktop.
libusb 1.0 implementation with C language. It is used to write the instruction to change Mouse Logitech G102/G203 RGB color.
#include <libusb-1.0/libusb.h>
#include <stdio.h>
#include <stdlib.h>
#define VID 0x046d
#define PRID 0xc084
/**
* Sending solid RGB color bytes to Logitech G102 / G203.
* LIBRARY: -lusb-1.0
*
* NOTE: Bytes has been transferred but the LED could not recognize it.
* @author KennFatt https://kennan.xyz/
*/
int main(int argc, char **argv) {
libusb_context *ctx = NULL;
libusb_device *dev = NULL;
libusb_device_handle *dh = NULL;
int wIndex = 0x00;
int err = libusb_init(&ctx);
if (err != 0) {
printf("Error when initialize libusb: %d\n", err);
return EXIT_FAILURE;
}
dh = libusb_open_device_with_vid_pid(ctx, VID, PRID);
if (dh == NULL) {
printf("Could not open device with VendorId: %d, ProductId: %d\n", VID,
PRID);
return EXIT_FAILURE;
}
// attach device
dev = libusb_get_device(dh);
if (dev == NULL) {
printf("Could not find device with given device handler!\n");
return EXIT_FAILURE;
}
wIndex = 0x01;
if (libusb_kernel_driver_active(dh, wIndex)) {
printf("Kernel driver active!\n");
int det_status = libusb_detach_kernel_driver(dh, wIndex);
if (det_status != 0) {
printf("Could not detach the kernel driver: %d\n", det_status);
return EXIT_FAILURE;
}
int claim_status = libusb_claim_interface(dh, wIndex);
if (claim_status != 0) {
printf("Could not claim the device! %d\n", claim_status);
return EXIT_FAILURE;
}
}
// parse bytes
const char *raw_bytes = "11ff0e3b0001ff00ff0000000000";
const char *offset = raw_bytes;
unsigned char payload[14];
for (unsigned i = 0; i < 14; ++i, offset += 2) {
char buff[5] = {0x30, 0x78, offset[0], offset[1], 0};
payload[i] = strtol(buff, NULL, 0);
}
int status = libusb_control_transfer(dh, 0x21, 0x09, 0x0211, wIndex,
payload, 0x0e, 1000);
printf("Status: %d\n", status);
// Detach
if (wIndex != 0x00) {
int rel_status = libusb_release_interface(dh, wIndex);
if (rel_status != 0) {
printf("Could not release interface: %d\n", rel_status);
return EXIT_FAILURE;
}
int att_status = libusb_attach_kernel_driver(dh, wIndex);
if (att_status != 0) {
printf("Could not attach kernel driver: %d\n", att_status);
return EXIT_FAILURE;
}
}
libusb_exit(ctx);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment