A method for Windows end to verify SN of Android device
By constructing a device information set, matching a manufacturer identifier whitelist, and a multi-level cleaning rule engine, combined with a timing competition fault tolerance mechanism, the environmental dependence and identification accuracy issues of serial number acquisition for Android devices in automated production testing were resolved, achieving stable identification under different USB configuration modes.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- BEIJING YINGZHI TECH CO LTD
- Filing Date
- 2026-01-31
- Publication Date
- 2026-06-02
AI Technical Summary
Existing methods for obtaining Android device serial numbers suffer from strong environmental dependence, poor accuracy, and instability during the automated production testing and firmware burning of Android mobile terminals. In particular, they cannot accurately obtain the device's motherboard serial number when the device is in recovery mode, boot mode, or when specific function drivers are not installed.
By calling the device installation application programming interface of the operating system kernel, a device information set is constructed, filtering parameters are configured to ignore the functional attributes of the device, a matching strategy based on the manufacturer's identifier whitelist is adopted, and a multi-level cleaning rule engine and a timing competition fault tolerance mechanism are combined to dynamically adjust the retry waiting time to ensure accurate acquisition of the device serial number in different USB configuration modes.
It enables serial number recognition of Android devices in different USB configuration modes without relying on a specific ADB driver, improving the detection stability and recognition accuracy of automated production lines, and eliminating false offline judgments caused by timing races and device enumeration delays.
Smart Images

Figure CN122132279A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of computer peripheral communication and automated testing technology, specifically a method for plug-and-play verification of Android device serial numbers on a Windows device. Background Technology
[0002] In the automated production testing and firmware flashing stages of Android mobile terminals, accurately obtaining the device's motherboard serial number is a prerequisite for establishing device identity indexes and traceability data. Existing general solutions typically rely on the Android Debug Bridge (ADB) toolchain for communication. This approach is highly dependent on the environment, requiring the host machine to have a specific USB debugging driver installed and the target device to be in a normal boot state with the USB debugging protocol enabled. When devices on the production line are in recovery mode, boot mode, or in an unknown device state due to the lack of specific function drivers, ADB-based detection methods will fail, leading to production process interruptions.
[0003] Some alternative solutions attempt to directly call the underlying APIs of the Windows operating system to obtain device information, but in practical applications, they still face challenges in terms of identification accuracy and stability. First, the USB Product Identifier (PID) of an Android device dynamically changes under different USB configuration modes (such as charging only, media transfer, network sharing, etc.). Static matching logic based on a fixed PID struggles to adapt to this polymorphism, easily leading to missed detections. Second, when generating device instance paths, the Windows Plug and Play Manager appends an interface mask (such as MI_01) or topology connection suffix to the original serial number based on the number of interfaces on the composite device. If this path string is read directly without specific format cleaning, the obtained data will contain non-inherent redundant characters, resulting in inconsistencies with the original records in the manufacturing execution system. Furthermore, there is a non-deterministic time delay between the physical insertion of the device and the operating system completing enumeration and writing to the registry. Existing instantaneous polling mechanisms often fail to handle this timing competition, prematurely determining read failure and reducing the first-pass yield of automated production lines. Summary of the Invention
[0004] To address the shortcomings of existing technologies, this invention provides a method for plug-and-play verification of Android device serial numbers on Windows, which solves the problems of discontinuous control trajectory, static and unadjustable emotion mapping, lack of user feedback loop, weak adaptive capability, and insufficient fusion of multi-dimensional control information in existing technologies.
[0005] To achieve the above objectives, the present invention provides the following technical solution:
[0006] This invention provides a method for plug-and-play verification of Android device serial numbers on Windows, comprising the following steps: By calling the device installation application programming interface of the operating system kernel, a device information set containing all currently physically connected Universal Serial Bus devices is constructed; when constructing the device information set, filtering parameters are configured to ignore the functional class attributes of the devices, so that device nodes that have not installed the preset driver or are in boot mode can be included. Iterate through the device members in the device information set and obtain the device instance path string for each device member; based on the preset manufacturer identifier whitelist, perform an inclusion matching verification on the device instance path string. If the match is successful, determine that the current device is the target device to be tested. The device instance path string of the target device under test is parsed, the original instance identifier is extracted by locating the path separator, and the interface mask prefix and composite device topology suffix attached by the operating system driver stack are removed based on the multi-level cleaning rule engine, so as to restore the unique device serial number. If a valid device serial number is not obtained in a single traversal, the timing race fault tolerance mechanism is triggered. The waiting time is calculated based on the current number of retries, and the current execution thread is suspended. After the suspension ends, the device information set construction and subsequent steps are re-executed until the serial number is successfully obtained or the maximum retry threshold is reached.
[0007] Furthermore, when constructing the device information set, a globally unique identifier is specified to point to the Universal Serial Bus controller and hub classes; control flags are configured to instruct the system to only return devices that are currently physically connected, and to force the return of devices of all device interface classes, regardless of whether the device has been assigned a specific function driver. This setting ensures that the system can bypass the limitations of upper-layer function drivers and directly capture the existence of devices at the bus level.
[0008] Furthermore, in the device matching process, a generalized matching strategy based on feature substrings is adopted. A hardware identifier field containing the manufacturer identifier and product identifier is extracted from the device instance path string; the manufacturer identifier whitelist is traversed, and the manufacturer allocation code in the whitelist is combined with a preset prefix character to construct a feature substring; it is then checked whether the device instance path string contains the feature substring. If either feature substring is contained, a successful match is determined, and the current product identifier value of the device is ignored, thus ensuring compatibility with changes in device identity under different Universal Serial Bus configuration modes such as charging-only, media transmission protocol, or debug mode.
[0009] Furthermore, the multi-level cleaning rule engine first performs raw data extraction: treating the device instance path string as an ordered character sequence, performing a reverse search algorithm to locate the index position of the last occurrence of the backslash character representing the path level separation in the sequence; and extracting all characters from the next character after the index position to the end of the sequence as the uncleaned raw instance identifier.
[0010] Furthermore, the multi-level cleaning rule engine then performs interface mask prefix cleaning: it detects whether the first character of the original instance identifier matches the predefined interface association descriptor feature string; if it matches, it determines the truncation offset based on the length of the feature string and the length of the index bit, removes the first feature string and the subsequent numeric index, and retains the remaining character sequence as an intermediate variable; if it does not match, it directly uses the original instance identifier as an intermediate variable.
[0011] Furthermore, the multi-level cleaning rule engine finally performs composite device topology suffix cleaning: it detects whether there are delimiters representing topology connections in the intermediate variables after removing the interface mask prefix; if the delimiter exists, the intermediate variables are vectorized and segmented based on the delimiter to generate a segmentation vector containing multiple data segments; the data segment located at a preset index position in the segmentation vector is selected as the final device serial number, where the preset index position corresponds to the position of the inherent entropy value reported by the device firmware. Through the above layer-by-layer stripping, non-inherent character information automatically generated by the operating system based on the device topology is eliminated.
[0012] Furthermore, the timing contention fault-tolerance mechanism employs a truncated binary exponential backoff algorithm to dynamically adjust the polling frequency. The specific calculation logic is as follows: obtain a preset base time slice constant and a time limit; calculate a power value with base 2 and the current number of retries as the exponent; multiply the power value by the base time slice constant to obtain the exponentially increasing time; compare the exponentially increasing time with the time limit, and take the smaller of the two as the waiting time before the current retrieval. This mechanism effectively covers the non-deterministic latency required from the establishment of a physical connection to the complete readiness of the operating system registry entries by dynamically extending the waiting time.
[0013] Furthermore, this invention introduces a configuration persistence and hot-reloading mechanism. The vendor identifier whitelist is stored in an external structured configuration file. During system initialization, the configuration file is read, the records are traversed, and the activation status bits are checked. Only vendor identifiers with valid activation status bits are loaded into a hash set data structure in memory for subsequent matching steps to query in constant-time complexity.
[0014] Furthermore, the system registers a monitoring handle for the directory where the configuration file is located through the operating system file system interface to listen for file attribute change events; when a change signal is received, a debouncing timer is started, and the change is confirmed to be valid only if no signal is received again within a preset stable time window; after confirming that the change is valid, the process of rereading and parsing the configuration file is triggered.
[0015] Furthermore, when triggering the process of rereading and parsing the configuration file, a read-write lock mechanism is used to ensure thread safety: when performing the device enumeration and matching steps, a shared read lock is requested to allow concurrent reading of the vendor identifier whitelist in memory; when performing the configuration update step, an exclusive write lock is requested to block subsequent read requests and wait for the current read operation to complete; while holding the exclusive write lock, the hash set in memory is cleared and the newly parsed vendor identifier is filled in, and the exclusive write lock is released after the update is completed.
[0016] This invention provides a method for plug-and-play verification of Android device serial numbers on Windows. It has the following beneficial effects: 1. This invention, by configuring filtering parameters for the device's application programming interface (API), ignores the device's functional attributes, allowing device nodes in boot mode or without specific function drivers to remain visible. Combined with an inclusion matching strategy based on a manufacturer identifier whitelist, the system can establish communication without relying on specific ADB drivers, effectively addressing identification interruptions caused by product identifier changes during Android device charging, debugging, or mass storage mode switching.
[0017] 2. This invention employs a multi-level cleaning rule engine, extracting the original instance identifier through the location path separator and performing interface mask prefix removal and composite device topology suffix stripping operations. This mechanism can remove non-intrinsic character information automatically attached by the operating system driver stack from complex Windows device instance paths, accurately restoring the unique serial number reported by the device firmware, and avoiding verification errors caused by data format pollution at the operating system level.
[0018] 3. This invention utilizes a truncated binary exponential backoff algorithm to construct a time-series competition fault-tolerant mechanism, extending instantaneous single-point queries into adaptive time-window detection. By dynamically adjusting the retry waiting time, it effectively covers the non-deterministic latency between the establishment of the device's physical connection and the readiness of the operating system registry entry, eliminating false offline determinations caused by host load fluctuations or device enumeration delays, and improving the stability of the automated production line detection process. Attached Figure Description
[0019] Figure 1 This is a block diagram of the overall hardware architecture and functional modules of the system of the present invention; Figure 2 This is a flowchart illustrating the overall implementation of the serial number reading method of the present invention. Figure 3 This is a schematic diagram of the device state flow according to the present invention; Figure 4 This is a flowchart of the exponential backoff retry algorithm of the present invention.
[0020] Among them, 10 is the Android terminal; 20 is the Windows host; 201 is the device enumeration module; 202 is the identification filtering module; 203 is the data parsing module; 204 is the timing control module; 205 is the configuration monitoring module; 22 is the device identification application; 30 is the universal serial bus interface; and 40 is the configuration file. Detailed Implementation
[0021] The technical solutions in the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.
[0022] See attached document Figure 1 This invention provides a method for plug-and-play verification of Android device serial numbers on a Windows platform, which operates within an electronic device identification system. For example... Figure 1 As shown, the electronic device identification system includes an Android terminal 10, a Windows host 20, and a universal serial bus interface 30 connecting the Android terminal 10 and the Windows host 20.
[0023] Android terminal 10 is the target mobile device to be detected. Android terminal 10 is internally configured with non-volatile memory (such as NAND Flash or eFuse), in which a unique factory serial number is burned.
[0024] Android terminal 10 is configured with firmware that reads the serial number from the non-volatile memory during the device boot loading phase and writes the serial number into the index string field of the standard USB device descriptor, specifically the iSerialNumber field.
[0025] Android terminal 10 is powered on and has established a physical connection with Windows host 20 via Universal Serial Bus interface 30. The operating modes of Android terminal 10 include, but are not limited to, normal operating system startup mode, recovery mode, or boot loading mode. As long as Android terminal 10 completes USB physical layer power supply and basic enumeration handshake, it can be used as a detection target.
[0026] Windows host 20 is a computing device running Windows operating system 21. Windows operating system 21 includes a kernel-level plug-and-play manager and a generic USB driver stack.
[0027] When Android terminal 10 is connected, Windows operating system 21 automatically detects hardware changes, reads the device descriptor of Android terminal 10, and generates a corresponding device instance in the device tree of the system registry. This process is automatically completed by the underlying Windows operating system 21, without depending on whether Android terminal 10 has ADB debugging permissions enabled, or whether Windows host 20 has specific function drivers for Android terminal 10 installed.
[0028] A device identification application 22 runs on the Windows host 20. The device identification application 22 is used to execute the serial number reading method described in this invention. The device identification application 22 logically includes: a device enumeration module 201, an identifier filtering module 202, a data parsing module 203, and a timing control module 204.
[0029] The device enumeration module 201 is configured to call the system API provided by the Windows operating system 21 to obtain a list of handles to all online USB class devices in the current system.
[0030] Define the set of all connected and active devices in the current Windows host 20 as the universal set. The device enumeration module 201 constructs a target device information set based on filtering criteria. This device information set It's the complete series. A subset of that, containing only devices that conform to the Universal Serial Bus (USB) class definition.
[0031] The identifier filtering module 202 is communicatively connected to the device enumeration module 201. The identifier filtering module 202 is configured with a preset list of manufacturer identifiers. The identifier filtering module 202 is configured to traverse the device information set. For each device instance, extract its device instance path and compare the manufacturer identifier contained in the path with a preset list of manufacturer identifiers. Perform a match.
[0032] The data parsing module 203 is communicatively connected to the identifier filtering module 202. The data parsing module 203 is configured to receive the device instance path string of the target device filtered by the identifier filtering module 202. The data parsing module 203 internally stores a character cleaning algorithm used to perform multi-level segmentation and feature removal on the device instance path string to restore the original serial number consistent with that stored in the motherboard of the Android terminal 10.
[0033] The timing control module 204 is connected to both the device enumeration module 201 and the data parsing module 203. The timing control module 204 is configured to monitor the status of the reading process. When the timing control module 204 detects a device information set... When the output of the data parsing module 203 is empty, the device enumeration module 201 is controlled to re-initiate the enumeration operation according to the preset exponential backoff strategy in order to eliminate the timing race caused by the enumeration delay of the Windows operating system 21.
[0034] The modules mentioned above are physically implemented by executing instruction code in memory through the central processing unit of the Windows host 20, and the modules interact with each other through memory sharing or function calls.
[0035] See attached document Figure 2 The method described in this embodiment of the invention begins in the device connection detection phase. When the Android terminal 10 is physically connected to the Windows host 20 via the Universal Serial Bus interface 30, the operating system kernel of the Windows host 20 immediately initiates an enumeration process, allocates resources for the hardware, and establishes corresponding key values in the registry. During this period, the device identification application 22 starts and executes the serial number reading process.
[0036] First, the device identification application 22 performs the construction of the device information set. The device identification application 22 calls the setupDiGetClassDevs interface in the Windows SetupAPI function library. During the call, the globally unique identifier (GUID) of the Universal Serial Bus device class is passed as a filter parameter, and the flags are set to a combination of DIGCF_PRESENT and DTGCF_ALLCLASSES. This operation command returns the set of all physically connected and active USB devices in the system at the current moment, i.e., the aforementioned device information set. At this point, the returned data type is a device information set handle, which points to a memory block containing information about all eligible device interfaces.
[0037] Subsequently, the device traversal and identifier acquisition phase begins. Device identification application 22 initializes a loop structure, utilizing the SetupDiEnumDeviceInfo interface to retrieve device information. Perform index traversal. For the index value... For each corresponding device node, the system populates a device information data structure (SPDEVINFODATA). Then, the system calls the configuration manager API CM_Get_Device_ID on this structure to directly read the device instance path string from the system registry. The device instance path string It includes a bus type prefix (such as USB), hardware identifiers (including vendor IDVID and product IDPID), and instance identifier.
[0038] After obtaining the device instance path string Next, the process enters the vendor identifier-based filtering phase. The system loads a list of vendor identifiers pre-loaded into a configuration file or memory. The system for Perform a substring search operation and determine... Does it contain the form VID_ plus A character fragment of any element in the array. If the currently traversed device... If the matching conditions are not met, the system determines that the device is not the target Android terminal 10 and immediately jumps to the next index to continue traversing.
[0039] If the current device Once the manufacturer identification matching criteria are met, the process proceeds to the serial number extraction and cleaning stage. The system processes the serial number according to preset character parsing rules. Processing is underway. First, the system is located. The system extracts the last backslash character (eight) from the string and extracts the substring following that position as the raw serial number data. Next, the system checks if this raw serial number data contains a specific interface prefix (e.g., the string MI_) or a compound device connector (e.g., the character '&'). If these characteristic characters are present, the system performs a stripping operation to remove path modifiers added by the Windows driver stack, thereby restoring the clean device serial number. .
[0040] At the end of a single read operation, the system performs validity checks and timing retry logic. The system checks the extracted sequence number. Is it an empty string? If so... If the result is not empty, the system outputs it to the display interface or verification module and terminates the reading process. If the device information set has been traversed... After checking all devices, no non-empty data was found. or device information set Since it is a set of zero elements, the system will check the current retry counter variable. Has the preset maximum threshold been reached? .
[0041] If the current retry counter Less than the maximum threshold The system will perform a delayed wait operation. Waiting time. According to the current counter The value increases linearly or exponentially. After the wait is complete, the system resets the device information set handle, returns to the starting point of the operation to build the device information set, and restarts the full enumeration. This loop mechanism continues until the serial number is successfully read or the number of retries is exhausted. If the number of retries is exhausted and the reading is still unsuccessful, the system outputs a read failure signal.
[0042] The method described in this embodiment maintains a finite state machine at runtime, which manages the entire lifecycle from physical connection detection to final data output.
[0043] After system initialization, it first enters a standby polling state. In this state, the device identification application does not consume significant computing resources, but instead listens for device change events at preset time intervals (e.g., every 500 milliseconds) or based on the Windows message loop. The core task of this state is to detect changes in the electrical connections of the Universal Serial Bus ports in real time. Once the device information set returned by the SetupAPI interface contains at least one valid element, the logical control of the system immediately shifts from the standby polling state to the identifier matching state.
[0044] In the identifier matching state, the system operates in a high-frequency computation mode. In this state, the system performs rigorous feature comparison on each captured device handle. The system reads the hardware ID field from the device instance path and compares it one by one with the list of manufacturer identifiers loaded in memory. This state has two exit paths: First, when the traversal process finds that the manufacturer identifier of any device instance matches the preset list, the state machine immediately locks the target device instance and transitions to the data cleaning state; second, if no match is found after traversing all objects in the current device information set, it indicates that the currently inserted device may be a non-target device (such as a mouse or keyboard) or the target device has not yet completed its underlying enumeration, at which point the state machine transitions to the fault-tolerant judgment state.
[0045] In the data cleaning state, the system executes string processing logic for the locked target device instance. This state does not involve hardware interaction; it only operates on string data in memory. The system disassembles and reassembles the original instance path based on predefined delimiters (backslashes and '&' symbols) and feature prefixes (MI_). After the cleaning operation is completed, the system generates a sequence number result to be verified and then transitions the state to the validity verification state.
[0046] In the validity verification state, the system performs logical checks on the cleaned serial number. The system checks if the length of the serial number string is greater than zero and if it conforms to the expected character set specification (e.g., whether it contains only numbers and letters). If the verification passes, the reading is considered successful, the state machine transitions to the termination output state, at which point the system renders the final SN value on the user interface, releases the relevant handle resources, and ends the current process. If the verification fails (e.g., the extraction result is empty), the state machine transitions to the fault-tolerant judgment state.
[0047] The fault-tolerance state is the linchpin between connection failures and retries. Upon entering this state, the system reads the retry counter variable from the current context. The system will Compared with the preset maximum retry threshold Perform a numerical comparison. If The system calculates the current required backoff time. This will cause the current thread to enter a blocked or sleep mode, temporarily halting the state machine. Once the sleep period ends, the retry counter will automatically reset. The value increments automatically and rolls back to the standby polling state (or directly triggers a new round of enumeration), thus forming a closed-loop retry mechanism. If This indicates that no valid information can be read within the specified time window. The state machine transitions to an abnormal termination state, the system outputs an error code indicating timeout or device not detected, and resets all state variables, waiting for the user's next manual trigger or the device to be plugged in or unplugged.
[0048] See attached document Figure 1 and attached Figure 2 In this embodiment, the device enumeration module 201 constructs a panoramic view of devices at the current moment through interaction with the Windows operating system kernel. The core of this process lies in establishing a device information set containing all physically connected USB devices.
[0049] When the device enumeration module 201 performs enumeration operations, it loads the Windows SetupAPI component via a dynamic link library. The system calls the SetupDiGetClassDevs function in this component to request the kernel to return a device handle. To ensure that all types of USB devices (including but not limited to mass storage devices, ADB interface devices, composite devices, and unknown devices without installed drivers) can be captured, the system strictly specifies the class identifier and control flags when calling this function.
[0050] Specifically, the system sets the ClassGuid parameter to a pointer to GUID_DEVCLASS_USB. This GUID is a globally unique 128-bit integer (typically defined as {36FC9E60-C465-11CF-8056-444553540000}), which uniquely identifies Universal Serial Bus controllers and hub-type devices under the Windows registry path HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class. By specifying this GUID, the system instructs PnP Manager to only retrieve hardware objects mounted on the USB bus, thereby physically filtering out irrelevant hardware such as PCI, Bluetooth, or virtual devices.
[0051] Meanwhile, in order to achieve plug-and-play verification and exclude residual historical device information (i.e. ghost devices) in the registry, the system configures the Flags parameter to be the result of a bitwise OR operation between DIGCF_PRESENT and DIGCF_ALLCLASSES.
[0052] The DIGCF_PRESENT flag indicates that the system should only return devices that are currently physically connected and responding to system queries. If this flag is not set, all previously connected device records stored in the registry will be returned, which can lead to serious misjudgments.
[0053] More importantly, the use of the DIGCF_ALLCLASSES flag is crucial. In the standard Windows driver model, devices typically belong to a specific functional class (such as disk class or port class). However, for Android terminals 10 that have not yet installed a specific driver or are in Bootloader mode, their functional class may not yet be established or may be marked as Unknown. By setting DIGCF_ALLCLASSES, this invention forces the system to ignore the device's functional class attribute and directly enumerate based on the bus interface attribute. This technical feature ensures that even if the Android terminal 10 is in a driver-missing or yellow exclamation mark state, its underlying device nodes can still be successfully captured by the device enumeration module 201, thus forming the technical basis for driverless reading.
[0054] Upon successful function call, a handle of type HDEVINFO is returned. This handle points to a memory region maintained by the operating system kernel, which stores configuration information for all device members that meet the above conditions in the form of a linked list or array. This device information set not only contains the device instance ID but also implicitly includes indexes pointing to detailed attribute keys of the device in the registry, providing a direct entry point for subsequent attribute queries. If the function returns INVALID_HANDLE_VALUE, it indicates that the underlying system enumeration failed, and the system will capture the error code (e.g., via GetLastError) for diagnostic purposes.
[0055] After obtaining the device information set handle containing all currently online USB devices in the system, the identification and filtering module 202 enters the device instance identification phase. This phase is implemented through an iterative loop structure, with the system maintaining an index variable that increments from zero.
[0056] In each iteration, the system calls the `SetupDiEnumDeviceInfo` function. This function receives the device information set handle and the current index variable as input parameters and attempts to populate an output parameter, namely the device information data structure (SP_DEVINFO_DATA). Before the call, the `cbSize` member of this structure must be initialized to the size of the structure in bytes to ensure API version compatibility. If the function returns a success status, it indicates that the device corresponding to the current index exists, and the system then obtains the unique instance handle of that device.
[0057] Subsequently, the system uses the obtained instance handle to call the configuration manager function CM_Get_Device_ID to extract the device instance path. This function copies the device path string stored in the kernel to a buffer allocated by the application. The extracted device instance path... This is a string describing the device's location and identity within the bus topology. Its standard format is typically structured as: USB\VID_XXXX&PID_YYYY\InstanceID or USB\VID_XXXX&PID_YYYY&MI_ZZ\InstanceID. USB indicates the bus type, XXXX in VID_XXXX is a four-digit hexadecimal vendor identifier, YYYY in PID_YYYY is a four-digit hexadecimal product identifier, MI_ZZ is the interface number for the composite device, and InstanceID, following the last backslash, is the key field containing serial number information.
[0058] In obtaining Then, the system executes whitelist-based filtering logic. The identifier filtering module 202 loads a preset set of vendor identifiers. This collection contains the allocation codes that allow verification of target Android device manufacturers (e.g., OE8D for MediaTek, 05C6 for Qualcomm, 1782 for Spreadtrum, etc.).
[0059] The system for sets Iterate through the collection. For each element... The system constructs a feature substring. (e.g., VID_OE8D). The system detects the current device instance path. Does it contain this feature substring? The matching strategy here uses inclusion matching rather than exact matching, and does not restrict the specific value of the Product Identifier (PID).
[0060] The technical significance of this matching strategy lies in the fact that while the product identifier of an Android device dynamically changes under different USB configuration modes (such as charging-only mode, MTP mode, PTP mode, RNDIS mode, or MIDI mode), its vendor identifier (VID) remains constant. By locking only the VID_ prefix and vendor code, this invention can ignore the current USB function mode of the device, thereby achieving indiscriminate capture of target devices in all modes.
[0061] Once discovered during the traversal Includes any one The system immediately identifies the current device as the target device under test and terminates the test. The traversal, and the Marked as valid input, it is passed to the subsequent data parsing module 203. If the traversal is complete... After considering all elements, it is still not in If a match is found, the system determines that the device is not the target device (such as a mouse, keyboard, or Bluetooth adapter that comes with the PC) and jumps to the next device index in the main loop.
[0062] Data parsing module 203 receives the target device instance path string transmitted by identifier filtering module 202, denoted as... In the Windows operating system's driver model, this path string follows a specific hierarchical naming convention, and its logical structure is defined as a combination of a bus prefix, a hardware identifier, and an instance identifier. Specifically, Formatted as The format is as follows. The backslash character (ASCII code 0x5C) is used as a delimiter between different levels of information.
[0063] The technical goal of this stage is to... The instance identifier portion is precisely separated because, according to the Universal Serial Bus (USB) device class definition, the serial number information reported by the device firmware is only encapsulated in the instance identifier field. The hardware identifier field (containing VID and PID) is only used for device classification and is not unique.
[0064] The system first stores the string It is considered a sequence of characters. (Definition) It consists of N ordered characters: ,in Indicates the first position in the sequence The character at each position.
[0065] The system defines a delimiter constant. This constant corresponds to the path separator (i.e., the backslash character). The system executes a reverse search algorithm, traversing the character sequence to locate the delimiter. Last occurrence index position The mathematical model for this positioning process is expressed as follows: ; The above formula shows that, It is the maximum value in the set of character indices equal to the delimiter. This logic ensures that regardless of whether there are nested sub-levels in the hardware identifier field, the system can always locate the rightmost delimiter, thus correctly distinguishing between the hardware ID and the instance ID.
[0066] Based on the located index The system performs a substring extraction operation to extract the substring from... Use all characters from the beginning of the position to the end of the sequence to construct the original sequence number data. The extraction process is represented as follows: ; The result obtained from the above calculation This is an unwashed instance identifier. In some simple device configurations (such as single-interface devices without specific function drivers installed), this... This is equivalent to the serial number of the device's motherboard. However, in the case of composite devices or devices processed through a specific driver stack, It may contain interface prefixes or parent association information added by the operating system kernel, therefore This data needs to be passed as an intermediate variable to subsequent cleaning logic for further processing. The atomicity and independence of this extraction step ensure that the acquisition path of the original data remains stable and conforms to the Windows kernel naming standard, regardless of how the subsequent cleaning rules change.
[0067] After obtaining the raw data through the aforementioned steps Subsequently, the data parsing module 203 invokes the built-in multi-level cleaning rule engine. This engine is designed as a set of cascading filters to eliminate non-inherent character information automatically appended by the Windows Universal Serial Bus driver stack based on the device topology. Because Android devices may appear as hybrid devices or single mass storage devices under different USB configurations, the instance ID format generated by the Windows kernel varies. This rule engine normalizes heterogeneous input data into a unique device motherboard serial number through two stages: standardized interface mask cleaning and hybrid topology stripping.
[0068] First, the engine executes the interface mask cleaning logic. When an Android device is identified as a multi-interface composite device, the Windows Plug and Play Manager creates an independent device node for each functional interface and adds an interface association descriptor prefix to its instance ID, typically represented as the character sequence MI_ followed by a two-digit index. To restore the device-level unique identifier, the system defines a prefix feature constant. .
[0069] Let the input character sequence be... The length is System check Does the header match the feature constant? Define intermediate cleaning variables The generating function is: ; in: Indicate extraction Operations on the leading character substring; Represents the interface mask feature (corresponding to MI_); This represents the truncation offset, the value of which is equal to the characteristic constant. The length plus the index bit length (usually) ), used to completely remove MI_xx fragments.
[0070] This logic ensures that regardless of whether the current handle points to the device's ADB interface, MTP interface, or mass storage interface, the interface-specific number prefix is removed.
[0071] Subsequently, the engine executes the composite topology stripping logic.
[0072] In certain driver loading scenarios, especially when the device is enumerated by the parent bus driver, the instance ID may contain topology path information or hash values concatenated by connectors (e.g., 5&1234568&0&2). Such strings are not pure SNs, but contain a parent node prefix and a port number suffix.
[0073] System-defined topology delimiters This symbol corresponds to the character '&'. The system uses intermediate variables... Perform an existence check. If... Contains delimiter The system will perform vectorized segmentation. Define the segmentation vector. for: ; in The first delimiter is the first delimiter. Each data segment. According to the Windows kernel's naming conventions for USB child nodes, the serial number information, containing the device's inherent entropy value, is located at a specific index position in the segmentation vector. In this embodiment, the target index... Set to 1 (i.e., the second element of the vector).
[0074] Final output serial number The derivation logic is expressed as follows: ; Through the above two-stage cleaning, the system can accurately extract the iSerialNumber payload originally reported by the Android device bootloader from the complex driver path string, eliminating the format pollution of device identity at the operating system level.
[0075] See attached document Figure 3In this embodiment, the timing race analysis module aims to address the time lag between physical connection establishment and logical device visibility. When the Android terminal 10 connects to the Windows host 20, there is a non-deterministic time window between the electrical connection at the physical layer and the application layer's ability to retrieve device information via API. This phenomenon stems from the asynchronous parallel execution mechanism between the Windows operating system's plug-and-play subsystem and user-mode applications.
[0076] Specifically, the moment the device is plugged into the USB port is recorded as... The Windows host's USB host controller first detects a level change on the data line (D+ or D-) and triggers a hardware interrupt. Subsequently, the operating system kernel initiates an enumeration sequence, sending standard USB requests (such as the GET_DESCRIPTOR instruction) to the device to obtain its device descriptor. After receiving the device's response, the kernel loads the corresponding driver stack and creates the device node under the HKLMurrentControlSet branch of the system registry. We denote the moment when the device information in the registry is fully established and indexable as... .
[0077] At the same time, the device identification application 22, as an independent user process, is constantly... The SetupDiGetClassDevs interface is called to initiate a query. Since the execution of the application and the kernel's enumeration process do not have a mandatory synchronization lock mechanism, they are independent of each other on the timeline.
[0078] At this point, the timing race risk faced by the system can be described by the following time inequality: ; When the above inequality holds, even though the devices are physically connected (i.e. However, since the kernel has not yet completed the registry write operation, the device information set obtained by the application is limited. This will be an empty set, or the set will only contain historical cached data and not currently added devices. This phenomenon is called a false offline state.
[0079] Furthermore, during the boot phase (Bootloader mode) or mode switching phase (such as switching from charging-only to MTP mode), the USB controller of Android terminal 10 undergoes a reset operation. This operation causes the device to logically disconnect and reconnect within a very short time. Let the device reset duration be... If the application happens to be during a device reset interval... Initiating a query within the same function will also result in a read failure.
[0080] Therefore, a single, instantaneous API call cannot guarantee successful device capture under all hardware performance conditions. A time-based fault tolerance mechanism must be introduced to extend discrete, single-point queries to comprehensive coverage. Time window query to ensure Ultimately satisfied This mechanism eliminates random identification errors caused by fluctuations in host CPU load or device response latency, thus meeting timing requirements.
[0081] In this embodiment, the timing control module 204 dynamically adjusts the polling frequency of the USB device by executing a truncated binary exponential backoff algorithm. The core strategy of this algorithm is to non-linearly extend the waiting interval before the next attempt as the number of consecutive read failures increases. This mechanism aims to balance the dual needs of fast response to high-performance devices and low-frequency compatibility with low-speed devices, minimizing the occupation of host CPU resources while ensuring the detection rate.
[0082] The system first initializes the retry counter variable. Set it to zero, and set two key time parameters: the base time slice constant. (Typically set in milliseconds, e.g., 100ms) and the maximum allowed retry threshold. .
[0083] When the device enumeration module 201 or the data parsing module 203 reports a read failure (i.e., unable to obtain a valid serial number string), When this happens, the timing control module 204 does not immediately initiate the next call, but instead enters the backoff calculation process. The system calculates the backoff based on the current retry counter. Calculate the waiting time required for this thread to be suspended. .
[0084] Waiting time Number of retries The functional relationship is defined as follows: ; in: Represents the binary exponential growth factor, as... The factor increases linearly, and grows geometrically. A preset time limit (e.g., set to 2000ms) is used to prevent excessively long waiting times due to exponential explosion, ensuring that the system maintains a certain level of responsiveness even in extreme situations. The function is used to take the smaller value between the calculated exponential time and the upper limit value, and implement a truncation strategy.
[0085] After the calculation is completed, the timing control module 204 calls the operating system kernel's thread synchronization interface (such as Sleep or WaitForSingleObject in the Windows API) to suspend the currently executing thread. Milliseconds. During this period, the CPU releases execution rights, allowing the operating system to handle underlying driver loading and plug-and-play events, thereby accelerating the device readiness process.
[0086] After the thread is suspended, the system will increment the retry counter. Subsequently, the system... Perform boundary checks: If The system resets the device information set handle and sends a reset signal to the device enumeration module 201, triggering a new round of device scanning and parsing. If This indicates that the device operates within a predefined time window (i.e., all...). If initialization fails to complete or a physical disconnection occurs within the accumulated sum (), the timing control module 204 determines that the current session has timed out, returns a device unreachable status code to the main program, and terminates the current retry loop.
[0087] Through the above logic, the present invention extends the originally discrete and instantaneous read operation into a detection window with a variable time span and adaptive properties, effectively covering the nondeterministic latency required for an Android device to go from power-on reset to USB descriptor readiness.
[0088] See attached document Figure 4 This invention introduces a configuration persistence layer to decouple the executable binary code of the application from the characteristic data of the target hardware. This design allows the system to adapt to new Android device manufacturers or remove outdated device support without recompiling or modifying the core logic code, thereby significantly improving the maintainability and lifecycle of the technical solution.
[0089] The system maintains a separate configuration file on non-volatile storage media (such as hard disk drives or solid-state drives) on the Windows host 20. This configuration file is encoded in a hierarchical structured data format, preferably using Extensible Markup Language or JavaScript object representation. At the physical storage level, this file is deployed in the application's installation root directory or an application data isolation directory specified by the operating system to ensure compliance with read and write permissions.
[0090] From a logical data model perspective, this configuration file defines a complete set of configuration records, denoted as . . Each record item in This corresponds to a specific Android device manufacturer's licensing rules. To achieve fine-grained control, the record items... Defined as a multidimensional attribute tuple: ; in, This represents a hexadecimal string value (e.g., 0E8D or 2717) that corresponds to the manufacturer identifier of the record. It is the unique index key for the system to perform low-level hardware comparison and must meet the format specification of a four-digit hexadecimal character. This field represents a human-readable name description of the vendor. It does not participate in core logic operations but is used for system logging and rendering user interface prompts to enhance system interactivity. This represents the activation status bit of the entry, and its value range is a Boolean field. .when When, instruct the system to load the rule; when When this happens, the system is instructed to ignore the rule.
[0091] During the system initialization phase, the identifier filtering module 202 triggers the configuration loading subroutine. This subroutine first uses the operating system file system API... A read stream is created to the configuration file using a method similar to CreateFile in the Windows API. Subsequently, the system performs deserialization parsing, traversing... All records in the set.
[0092] To optimize runtime matching performance, the system constructs an efficient lookup data structure in volatile memory to map the aforementioned configurations. Specifically, the system constructs a set of in-memory whitelists. The logical process is described as follows: ; This formula indicates that only if a record exists in the configuration file And its active state bit When it is set to valid, its corresponding VID value Only then will it be extracted and injected into middle.
[0093] In terms of the choice of memory data structure, this embodiment uses a hash set for storage. Based on the characteristics of hash tables, in subsequent VID matching operations, it is determined whether an input device VID exists in the hash table. The time complexity is constant. This technical detail ensures that even if the configuration file is expanded with hundreds or thousands of vendor entries, the system's response latency at the moment of device insertion remains at the microsecond level, and performance will not degrade as the configuration scale increases.
[0094] Furthermore, this persistent storage mechanism integrates integrity verification logic. When saving the configuration file, the system calculates a cyclic redundancy check (CRC) code or a secure hash digest based on the byte stream of the file content and encapsulates the result in the file's metadata header. During the loading phase, the system recalculates the hash value of the read content in real time and compares it with the metadata. If the comparison fails, the system determines that the configuration file is corrupted or has been illegally tampered with, and automatically blocks the loading process and switches to the built-in default list of security modes. This constitutes a defensive technical barrier to prevent the risk of unauthorized device access due to malicious external modification of the VID list.
[0095] This invention, in its embodiments, dynamically updates configuration files during the operation of the device identification application through a file system monitoring mechanism, allowing new vendor whitelists to take effect in real time without terminating or restarting the main process. This mechanism is executed by a built-in configuration monitoring module, which runs as a background daemon thread, independent of the main UI thread and the USB enumeration thread.
[0096] During the initialization phase, the configuration monitoring module calls the file system change notification interface provided by the operating system (such as ReadDirectoryChangesW or FindFirstChangeNotification in the Windows API). The system registers a monitoring handle with the operating system kernel for the directory path where the configuration file is located. This handle is configured to listen only for specific types of file attribute change events, specifically filename changes and last write time changes.
[0097] When a user or remote management system modifies and saves a configuration file, the operating system kernel captures the write operation and sends a change signal to the configuration monitoring module. Given that file saving operations may trigger multiple consecutive low-level write interrupts within a very short time, this embodiment introduces debouncing logic to prevent unnecessary reloading of the system.
[0098] The system defines a stable time window. (For example, set to 500 milliseconds). Let... This is the timestamp of the received latest change signal. The monitoring module does not immediately update upon receiving the signal; instead, it starts a countdown timer. Updates only when the current system time... The system will only confirm the change as valid and trigger the reload process when the following conditions are met: ; This logic ensures that the file write operation has been completely terminated and the file handle has been released, thereby avoiding the risk of reading incomplete file data that is being written.
[0099] After confirming the changes are effective, the system performs a hot-swap operation on the memory data. (Due to the vendor identifier list...) It is a global resource that is shared and accessed by multiple threads (the enumeration thread needs to read the list for matching, while the monitoring thread needs to write to the list for updating). The system introduces read-write lock synchronization primitives to ensure data consistency and thread safety.
[0100] Define the list of vendors in memory as This object is associated with a read-write lock state variable. When the device enumeration module 201 needs to read the list for device filtering, it requests a shared read lock. At this time, multiple read threads are allowed to access the list simultaneously. However, write operations are prohibited.
[0101] When the configuration monitoring module prepares to update the list, it requests an exclusive write lock. At this time, the system will block all subsequent read requests and wait for all currently active read operations to complete.
[0102] Once the exclusive write lock is acquired, the system performs an atomic update operation: clearing the current hash set. ; Reread and parse the configuration file on the disk; Fill in the newly parsed valid vendor identifier to Release the exclusive write lock.
[0103] The entire update process is completed within milliseconds. Once the update is complete, subsequent device enumeration operations will immediately be based on the new update. The system is then evaluated. This hot-loading mechanism enables the system to adapt to rapid switching requirements in a production line environment, such as temporarily adding support for newly introduced models without interrupting the operation of the production line testing software.
Claims
1. A method for plug-and-play verification of Android device serial numbers on Windows, characterized in that, Includes the following steps: By calling the device installation application programming interface of the operating system kernel, a device information set containing all currently physically connected Universal Serial Bus devices is constructed. When constructing the device information set, filter parameters are used to ignore the functional class attributes of the device, so that device nodes that have not installed the preset driver or are in boot mode can be included. Iterate through the device members in the device information set and obtain the device instance path string for each device member; based on the preset manufacturer identifier whitelist, perform an inclusion matching verification on the device instance path string. If the match is successful, determine that the current device is the target device to be tested. The device instance path string of the target device under test is parsed, the original instance identifier is extracted by locating the path separator, and the interface mask prefix and composite device topology suffix attached by the operating system driver stack are removed based on the multi-level cleaning rule engine, so as to restore the unique device serial number. If a valid device serial number is not obtained in a single traversal, the timing race fault tolerance mechanism is triggered. The waiting time is calculated based on the current number of retries, and the current execution thread is suspended. After the suspension ends, the device information set construction and subsequent steps are re-executed until the serial number is successfully obtained or the maximum retry threshold is reached.
2. The method for plug-and-play Android device serial number verification on Windows as described in claim 1, characterized in that, The steps of constructing a device information set containing all currently physically connected Universal Serial Bus devices specifically include: Specify a globally unique identifier pointing to the Universal Serial Bus controller and hub class; Configure control flags to instruct the system to return only devices that are currently physically connected, and force the return of devices of all device interface classes, regardless of whether the device has been assigned a specific function driver; Call the function that retrieves device class information, and it returns a handle to a set of device information in the kernel memory region. This handle indexes all device members that meet the above conditions.
3. The method for plug-and-play Android device serial number verification on Windows as described in claim 1, characterized in that, The step of performing a matching verification on the device instance path string based on a pre-set manufacturer identifier whitelist specifically includes: Extract the hardware identifier field containing the manufacturer identifier and product identifier from the device instance path string; Traverse the manufacturer identifier whitelist and combine the manufacturer allocation code in the whitelist with the preset prefix characters to construct a feature substring; Detect whether the device instance path string contains the feature substring; If any characteristic substring is contained, the match is considered successful and the current product identifier value of the device is ignored to accommodate changes in the device's identity under different Universal Serial Bus configuration modes.
4. The method for plug-and-play Android device serial number verification on Windows as described in claim 1, characterized in that, The step of extracting the original instance identifier by locating the path separator specifically includes: The device instance path string is treated as an ordered sequence of characters. Execute the reverse search algorithm to locate the index position of the last occurrence of the backslash character representing the path hierarchy in the sequence; Extract all characters from the next character at the indexed position to the end of the sequence, and use them as the unwashed original instance identifier.
5. The method for plug-and-play Android device serial number verification on Windows as described in claim 1, characterized in that, The step of removing the interface mask prefix attached by the operating system driver stack specifically includes: Detect whether the first character of the original instance identifier matches the predefined interface association descriptor feature string; If a match is found, the truncation offset is determined based on the length of the feature string and the length of the index, the feature string at the beginning and the subsequent numeric index are removed, and the remaining character sequence is retained as an intermediate variable. If there is no match, the original instance identifier is used as an intermediate variable.
6. The method for plug-and-play Android device serial number verification on Windows according to claim 1, characterized in that, The step of removing the composite device topology suffix attached by the operating system driver stack specifically includes: Detect whether there is a delimiter representing topology connections in the intermediate variables after removing the interface mask prefix; If the delimiter exists, the intermediate variables are vectorized and segmented based on the delimiter to generate a segmentation vector containing multiple data segments; The data segment located at a preset index position in the segmentation vector is selected as the final device serial number, wherein the preset index position corresponds to the position of the inherent entropy value reported by the device firmware.
7. The method for plug-and-play Android device serial number verification on Windows as described in claim 1, characterized in that, The waiting time is calculated based on the current number of retries using a truncated binary exponential backoff algorithm. The specific calculation logic is as follows: Obtain the preset base time slice constant and time limit value; Calculate the power value with base 2 and the current number of retries as the exponent, and multiply the power value by the base time slice constant to obtain the exponential growth time; Compare the exponential growth time with the upper time limit, and take the smaller of the two as the waiting time before this retry; By dynamically extending the wait time, the nondeterministic latency required for a device to become ready from a physical connection to an operating system registry entry is mitigated.
8. The method for plug-and-play Android device serial number verification on Windows according to claim 1, characterized in that, The vendor identifier whitelist is stored in an external structured configuration file; it also includes a loading step performed during system initialization: Read the configuration file and iterate through the record items within it; Check the activation status bit in each record entry; Only vendor identifiers with valid activation status bits are extracted and loaded into a hash set data structure in memory for subsequent matching steps to query in constant time complexity.
9. A method for plug-and-play Android device serial number verification on a Windows side according to claim 8, characterized in that, It also includes a runtime configuration hot reloading step: Register a monitoring handle for the directory where the configuration file is located through the operating system file system interface to listen for file attribute change events; When a change signal is received, the anti-jitter timer is started. The change is confirmed to be valid only if no signal is received again within the preset stabilization time window. After confirming that the changes are effective, the process of rereading and parsing the configuration file is triggered.
10. A method for plug-and-play Android device serial number verification on a Windows side according to claim 9, characterized in that, When triggering the process of rereading and parsing the configuration file, the steps to ensure thread safety using a read-write lock mechanism specifically include: When performing the device enumeration and matching steps, a shared read lock is requested to allow concurrent reading of the vendor identifier whitelist in memory; When performing the configuration update step, an exclusive write lock is requested, blocking subsequent read requests and waiting for the current read operation to complete; While holding the exclusive write lock, clear the hash set in memory and fill it with the newly resolved vendor identifier. Release the exclusive write lock after the update is complete.