环境:windows & linux & Zebra打印机gt820
windows:
之前安装了Zebra打印机官方驱动,所以先卸载掉驱动。再安装Zadig,用Zadig工具来安装WinUSB驱动。
zadig下载:Zadig - USB driver installation made easy
记住这两个数据:vendorId:0A5F productId :00C1 。这是打印机的供应商ID,和产品ID,程序中要用到。
Linux:ubuntu22.04 x86_64已经内置usbfs,直接下载libusb库:libusb - Browse /libusb-1.0/libusb-1.0.27 at SourceForge.net
解压后安装
./configure --prefix=/home/a/libusb-1.0.27/build
make -j 4
sudo make install
linux查看vendorid productId命令:lsusb
将头文件和库加到项目中。
测试代码:
void testPrintZplDirectUsb()
{
libusb_context* ctx = NULL;
libusb_device** devs;
libusb_device_handle* dev_handle = NULL;
ssize_t cnt;
//int i;
// 初始化libusb库
if (libusb_init(&ctx) < 0) {
printf("初始化失败\n");
return;
}
// 枚举设备
cnt = libusb_get_device_list(ctx, &devs);
if (cnt < 0) {
printf("枚举设备失败\n");
return ;
}
printf("%d个设备找到\n", cnt);
libusb_device* dev;
int i = 0, j = 0;
uint8_t path[8];
while ((dev = devs[i++]) != NULL) {
struct libusb_device_descriptor desc;
int r = libusb_get_device_descriptor(dev, &desc);
if (r < 0) {
fprintf(stderr, "failed to get device descriptor");
continue;
}
printf("%04x:%04x (bus %d, device %d)",
desc.idVendor, desc.idProduct,
libusb_get_bus_number(dev), libusb_get_device_address(dev));
r = libusb_get_port_numbers(dev, path, sizeof(path));
if (r > 0) {
printf(" path: %d", path[0]);
for (j = 1; j < r; j++)
printf(".%d", path[j]);
}
printf("\n");
if (desc.idVendor == 0x0a5f && desc.idProduct == 0x00c1)
{
获取handle方式一:
//dev_handle = libusb_open_device_with_vid_pid(ctx, desc.idVendor, desc.idProduct);
//if (dev_handle != NULL) {
// int ok = libusb_claim_interface(dev_handle, 0);
// unsigned char data[] = "^XA^FO200,20^BY3^BCN,100,Y,N,N^FDDAe123456^FS^XZ";
// int dataSize = sizeof(data)/*+1*/;
// int actrueLeng = 0;
// int transferedBytes = libusb_bulk_transfer(dev_handle, 0x01, data, dataSize, &actrueLeng, 0);
//
// //int transferedBytes = libusb_bulk_transfer(dev_handle, 0x01, data, dataSize, &actrueLeng, 1000);
// if (transferedBytes < 0)
// printf("写入数据失败\n");
// else
// printf("写入%d字节数据成功\n", actrueLeng);
// libusb_close(dev_handle);
//}
//获取handle方式二:推荐
int udev = libusb_open(dev, &dev_handle);
if (LIBUSB_SUCCESS == udev && dev_handle)
{
//show device name
char buffer[256] = { 0 };
//libusb_get_string_descriptor(dev_handle, desc.iProduct, 1, (unsigned char*)buffer, sizeof(buffer));
int iRetTemp = libusb_get_string_descriptor_ascii(dev_handle, desc.iProduct, (unsigned char*)buffer, sizeof(buffer));
if (iRetTemp > 0)
{
printf("device name:%s\n", buffer);
}
char* sb = "^XA^FO10,20^BY3^BCN,100,Y,N,N^FDDAe123456^FS^XZ";
//char* sb = "^XA^FX Third section with bar code.^BY5,2,200^FO50,50^BC^FD12345678^FS^XZ";
int ok = libusb_claim_interface(dev_handle, 0);
printf("%d\n", ok);
int actrueLeng = 0;
ok = libusb_bulk_transfer(dev_handle, 0x01, (unsigned char*)sb, 50, &actrueLeng, 1000);
printf("%d\n", ok);
libusb_close(dev_handle);
}
}
}
libusb_free_device_list(devs, 1);
libusb_exit(/*NULL*/ctx);
}