Use LIBUSB to detect USB devices on your MAC in QT

Source: Internet
Author: User
Tags 04x naming convention

The first problem with using QT to make a Kindle annotation management software on a MAC is to detect the status of USB devices connected to your Mac. If the development is in Cocoa, there will be a corresponding system API to use, but because I was in the QT platform development, so it is a bit more difficult. Just then, I found a library:libusb

LIBUSB Introduction

Libusb designed a series of external APIs called by the application, through which the API applications can manipulate the hardware, from the source code of LIBUSB can be seen, these APIs call the kernel of the underlying interface, and kernel driver used in the function of the implementation of the same function, Just libusb closer to the USB spec. This makes the use of libusb much easier than developing kernel drivers. (From: Baidu Encyclopedia)

0x00 Download Libusb

On the LIBUSB Project homepage (http://libusb.info) We can find the latest source code, download it, and unzip it. Here i download the libusb-1.0.20.tar.bz2, unzip it out.

0x01 installation Libusb
cd libusb-1.0.20/./configuremakemake install

At this point, the machine has been compiled and installed to complete the LIBUSB

0X02 running the sample program
cd examples/make

Then we see examples/ a few more executable programs in the directory:

    • Listdevs: List all current USB devices

    • hotplugtest: USB hot-swap test

    • dpfp_threaded: Operation u.are.u 4000b fingerprint capture device Demo

    • DPFP: Initialize u.are.u 4000b fingerprint capture device

    • Sam3u_benchmark: Demo to test the performance of the Atmel sam3u USB master Synchronous transmission

    • fxload: USB firmware operation

type] [-d vid:pid] [-p bus,addr] [-s loader] -i firmware  -i <path>       -- Firmware to upload  -s <path>       -- Second stage loader  -t <type>       type: an21, fx, fx2, fx2lp, fx3  -d <vid:pid>    -- Target device, as an USB VID:PID  -p <bus,addr>   -- Target device, as a libusb bus number and device address path  -v              -- Increase verbosity  -q              -- Decrease verbosity (silent mode)  -V              -- Print program version
    • xusb: USB test program
Usage:/users/jason/downloads/libusb-1.0. -/EXAMPLES/.LIBS/XUSB [-h] [- D] [-i] [-K] [-B file] [- LLang] [-j] [-X] [- S] [-P] [-W] [Vid:pid]-h:display usage- D: Enable debug Output-i: Print Topology and speed info-j: Test composite FTDI based JTAG device-k : Test Mass Storage device-b file:dump Mass Storage data to File' file '-p:test Sony PS3 Sixaxis Controller- S: Test Microsoft SideWinder Precision Pro (HID)-x:test Microsoft XBox Controller Type S- LLang:language to report Errorsinch(ISO639-1-w:force the use of device requests if querying Wcid Descriptorsif only the vid:pid is provided, XUSB attempt The most appropriate test for S to run

listdevsFor example, we execute the test procedure:

./listdevs

Execution Result:

05ac:8406203705ac:82820203.30a5c:45002027305ac:8005200)
link library

Libraries exist in a large number of Windows platforms, MAC platforms, and Linux platforms. In essence, a library is a binary form of executable code that can be loaded into memory by the operating system.
Because of the different platforms of Windows, Macs, and Linux (mainly compilers, assemblers, and connectors), the binary of the libraries is incompatible.

There are two types of libraries under Linux: static libraries and shared libraries (dynamic libraries). The difference between the two is that the code is loaded in a different time.

The code for the static library has been loaded into the executable program during compilation, so the volume is large.

The code for a shared library is loaded into memory when the executable is running, only a simple reference during compilation, so the code is small.

Create a static link library 0x00 write a static link library
    • Hello.h
#ifndef HELLO_H #define HELLO_H void hello(constchar#endif
    • hello.c
#include <stdio.h> void hello(constchar *name) {         printf("Hello %s!\n", name); }
    • Main.c
#include "hello.h" int main() {     hello("world");     return0; }
0x01 Creating the target code
gcc -c hello.c

The compile option in GCC means that the -c source file is converted to the target code using the GNU assembler, in which case only the C compiler (CCL) and assembler (as) are called, and the connector (LD) is not executed. So the target file of the output will not contain the contained information that is required to be loaded and executed as a program, but it can be connected to a program at a later time.

We execute the ls command to see that there is one more file in the directory hello.o , it is hello.c the target code of the compilation

0x02 Creating a static link library
ar rcs libhello.a hello.o

Create a static library with the AR command.

The naming convention for Static library filenames is prefixed with lib, followed by a static library name with a. a extension.

For example: We will create a static library named Hello, then the static library file name is LIBHELLO.A. You need to be aware of this when creating and using static libraries.

We execute the ls command, we can see that the directory is more than a static link librarylibhello.a

0x03 link Static link library

The static library is finished, how to use its internal function?

You only need to include a prototype declaration of these common functions in the source program that uses these common functions, and then specify the static library name when you generate the target file with the GCC command, and GCC will connect the public function to the destination file from the static library.

Notice that GCC adds the prefix lib to the static library name, and then appends the extension. A to the static library file name to find the static library files, so when we write a library that needs to be connected, we write only the names, such as the LIBHELLO.A Library, which writes only:-lhello

gcc -o main main.c -L. -lhello

Execute the program

./mainHello world!
Creating a dynamic link library 0x00 creating a dynamic-link library
gcc -dynamiclib -o hello.dylib hello.o

We ls can see more of the directory under the command hello.dylib , which is the creation of the dynamic link library (. Dylib is under the MAC system, under Windows is. dll, Linux is. So)

0x00 Link Dynamic Link library
gcc -o main1 main.c -L. -lhello

Execute the program

./main1Hello world!
Use libusb0x00 in QT to add libusb dynamic link libraries to QT projects

We first create a new project in QT5 Testlibusb and then create a new directory under the project directory lib to hold the LIBUSB library file.

Copy the libusb corresponding library file to this directory, because I am using the platform is MAC OS X, the corresponding library file should be the .dylib extension, we found in the directory under the Libusb source folder /libusb/.libs/ libusb-1.0.0.dylib and then copied to the directory just created

and add the LIBUSB header file libusb.h to the project

0x01 Modify QT Project compilation options

Modify the files in the QT project by .pro Adding the following lines:

macx: LIBS += -L$$PWD/lib/ -lusb-1.0.0INCLUDEPATH += $$PWD/.DEPENDPATH += $$PWD/.
0x02 Writing LIBUSB test program
    • Getusbinfo.h
#ifndef Getusbinfo#define GETUSBINFO#include <QString>#include <QObject>#include <QList>#include <QThread>#include <libusb.h>structstuusbdevices{QString idproduct;    QString Idvendor;    QString Imanufacturer; QString Iserialnumber;};classgetusbinfo:qthread{ Public: Getusbinfo (Qobject *parent); ~getusbinfo ();intInitusbdevices (); QString getvidpid (Libusb_device **devs);voidShowallusbdevices (qlist<stuusbdevices> lst);voidSetrunstatus ();voidRun ();BOOLIsstop;};#endif //Getusbinfo 
    • Getusbinfo.cpp
#include "getusbinfo.h"#include <QThread>#include <QDebug>#include <QString>Getusbinfo::getusbinfo (Qobject *parent): Qthread (parent), Isstop (false) {}getusbinfo::~getusbinfo () {qdebug () <<"Getusbinfo::~getusbinfo"<<endl;}intGetusbinfo::initusbdevices () {Libusb_device **devs;intR    ssize_t CNT; R = Libusb_init (NULL);if(R <0)returnR CNT = Libusb_get_device_list (NULL, &devs);if(CNT <0)return(int) CNT;    Getvidpid (DEVS); Libusb_free_device_list (Devs,1); Libusb_exit (NULL);return 0;} QString getusbinfo::getvidpid (Libusb_device **devs) {Libusb_device *dev;inti =0; Qlist<stuusbdevices> Lstusb; while(dev = devs[i++])! = NULL) {structLibusb_device_descriptor desc;intr = Libusb_get_device_descriptor (Dev, &desc);if(R <0) {Qdebug () <<"failed to get device descriptor"<<stderr;return ""; }printf("%04x:%04x (bus%d, device%d) \ n", Desc.idvendor, Desc.idproduct, Libusb_get_bus_number (Dev), libusb_get_device_address (Dev));        Stuusbdevices Stu;        Stu.idproduct = Qstring::number (desc.idproduct);        Stu.idvendor = Qstring::number (Desc.idvendor);        Stu.imanufacturer = Qstring::number (desc.imanufacturer);        Stu.iserialnumber = Qstring::number (Desc.iserialnumber);    Lstusb.append (Stu); } showallusbdevices (LSTUSB);returnQString (lstusb[0].IDPRODUCT);}voidGetusbinfo::showallusbdevices (qlist<stuusbdevices> lst) { for(intI=0; I<lst.count (); i++) {qdebug () <<"vid:"<<lst.at (i) .idvendor<<"\ n"<<"pid:"<<lst.at (i) .idproduct<<"\ n"<<"Sernumber:"<<lst.at (i) .iserialnumber<<"\ n"<<"Manufacturer:"<<lst.at (i) .imanufacturer<<"\ n"; }}voidGetusbinfo::setrunstatus () {isstop =true;}voidGetusbinfo::run () {qdebug () <<"Getusbinfo::run ()"<<endl; while(!isstop)       {initusbdevices (); SleepTen); }}
    • Main.cpp
#include "mainwindow.h"#include <QApplication>#include "getusbinfo.h"#include <QLibrary>int main(intchar *argv[]){    QApplication a(argc, argv);    MainWindow w;    w.show();    QThread t;    GetUsbInfo info(&t);    info.initUsbDevices();    return a.exec();}
0X03 Execute LIBUSB Test program
starting/users/jason/project/qtdemos/ Build-testlibusb-desktop_qt_5_5_1_clang_64bit-debug/testlibusb.app/contents/macos/testlibusb...vid:  "1452"  pid:  "33798"  sernumber:  "5"  Manufacturer:  "3"  vid:  "1452"  PID:  "33423"  sernumber:  "0"  Manufacturer: " 1 " vid: " 2652 " pid: " 17664 " Sernumber:  "0"  Manufacturer:  "1"  vid:  "1452"  pid:  "32773"  sernumber:  "0"  Manufacturer:  "0"   

Finally we get a list of USB devices on the current MAC

This article's copyright belongs to the author Luo voyage All, uses Attribution-noncommercial 3.0 License. Any person may reproduce, share, but not be used without permission for commercial purposes; reprint please specify the source. Thanks for cooperating!

Use LIBUSB to detect USB devices on your MAC in QT

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.