USB Switch Fixer

Software · Short case

USB Switch Fixer USB切换器修复

A keyboard-and-mouse switch kept failing and every sign said dead hardware. Shuo’s 18-minute control experiment proved the hardware healthy and pinned the fault on the PC.

  • Conceived, designed and built by Shuo Huang
  • Dead-hardware verdict overturned in 18 min
  • 5 explanations ruled out by live test
  • 7 defects caught in testing and fixed
  • First release 18 Aug 2026
  • PowerShell + Win32 DeviceIoControl

01System architecture

Repair the one port first. Touch the whole controller only behind a failsafe.

Two constraints shaped it. The fault takes away the keyboard a manual fix would need, so the repair has to run on its own. And the PC has a single USB controller that also carries the second monitor and every other USB device, so the gentle repair goes first and the drastic one is opt-in.

On the desk

USB sharing switch

One keyboard and mouse, two PCs, one push button. Its own hub chip enumerates perfectly every time.

Office PC

Root-hub port

Where the switch’s cable lands. Found by the peripherals behind it, never by port number.

Office PC

USB host controller

The PC’s only one. Every USB device depends on it, so resetting it is the last resort.

On demand

Snapshot tool

Full topology plus the port-level status Device Manager hides, saved for before-and-after diffing.

Starts at logon

Resident watcher

Polls every 3 s. Acts after 2 bad polls in a row, at most 12 repairs an hour, single instance.

Tier 2 · opt-in

Controller reset

Arms a one-shot failsafe task that re-enables USB after 90 s, then disables and re-enables the controller.

On disk

Repair log

Every detection, attempt and outcome, timestamped. The record that judged the tool.

Simplified: the snapshot tool reads every root-hub port as well as the switch’s own, and the watcher reads health from the Windows device tree as a whole.

Why tier 1 is a single port

A port power cycle is the software twin of pulling one cable and pushing it back in. The second monitor and the spare keyboard never notice.

Why tier 2 arms a failsafe first

Disabling the only USB controller removes every input device. A one-shot scheduled task, armed before the reset and run by Windows rather than by the script, re-enables it after 90 seconds even if the script crashes or is stopped mid-reset, so the PC cannot be left stranded.

What the log decided

The watcher’s own record showed where automation stops on this PC: a restart is still the durable cure.1 The page says so because the log does.

02The story

Every sign said dead hardware. An 18-minute experiment proved the PC was at fault.

Shuo shares one keyboard and mouse between two office PCs through a push-button switch. After enough switching, one PC stopped recognizing them until it was restarted. On his own initiative he traced the failure one test at a time, overturned the obvious verdict that the switch was dying with a single controlled experiment, and built a background watcher that attempts the repair with nobody at the keyboard.

  1. 01

    The problem

    Press the button and the keyboard and mouse jump to the other PC. After some number of presses, Windows on one PC reported a malfunctioning USB device, and that PC would not take the keyboard back until a full restart. It happened often enough that Shuo kept a spare keyboard and mouse plugged in.

    The awkward part: the tool you would use to fix it is the keyboard you have just lost. Any repair has to run by itself.

  2. 02

    What he built

    First, a diagnosis, run like an experiment. One explanation at a time, each tested against the live fault and written down even when it failed: stale drivers, stale device entries, power saving, a weak power supply.2 To see past what Device Manager shows, he read the status of every USB port directly from Windows.

    Then, a repair. A background watcher checks the USB devices every three seconds. When the keyboard and mouse fail to register, it does in software what a person would do by hand: unplug that one cable and plug it back in, without disturbing anything else on the PC. A stronger second step resets the PC’s whole USB controller, guarded by a timer that switches USB back on if anything goes wrong.

  3. 03

    What changed

    The verdict changed. Two days after the first release the fault came back and nothing cleared it, a physical replug included. Everything now read as failing hardware, and the working conclusion was to replace the switch.

    Shuo refused to accept that without a control: record the full state, restart, record it again. If the same hardware works after a restart, the hardware is not dead. Eighteen minutes later the answer was in. Nothing had been touched, and all 23 USB devices were healthy.3 The fault lives in the PC’s USB state, not in the switch.

    He then held his own tool to the same standard. Its log shows the software replug works mechanically but does not hold against the built-up fault, and that this PC’s controller refuses the reset step, so a restart remains the durable cure.1 He kept the evidence and reported it as it stands.

    No verdict without a control, and no result reported better than the log: it is the same method behind his Live vs Backtest audit of a live trading engine.

5

plausible explanations ruled out, each by its own test on the live fault2

18min

from proposing the control experiment to overturning the dead-hardware verdict3

55 → 4

USB address of the same switch, before and after the restart4

0 / 23

USB devices faulty one minute after the restart, with no hardware touched3

03Evidence

The fault lived in the PC, not in the switch

Windows gives each USB device an address when it sets the device up, and the number climbs each time a device has to be set up again. Shuo saved the full USB picture just before and one minute after a restart on August 20, and the same snapshot was taken again when the fault came back on September 4: same PC, same switch, same keyboard and mouse.

USB address of three hubs, in the three saved snapshots

A restart, with no hardware touched, reset the addresses from the 40s and 50s to single digits; seven hours into a fresh day on September 4 they were back up, and so was the fault.

Show the dataHide the data
Data: USB address of three hubs, in the three saved snapshots
HubBefore the restartAfter the restartSep 4, fault back
Switch’s hub55448
Hub B46657
Hub C45259
Measured with the snapshot tool on Shuo’s office development PC. Saved snapshots: August 20, 2026 at 18:38 (PC up 1,753 minutes) and 18:52 (up 1 minute, after the restart); September 4, 2026 at 14:01 (up 423 minutes). Hub B and Hub C are two other hubs on the PC’s one USB controller; devices that were not set up again, such as the second monitor’s adapter, kept low addresses throughout.4

04Functions

Everything it does, in the order a user meets it.

A

Watch

A resident watcher starts in the background at logon and checks every USB device every three seconds, because the fault removes the keyboard a manual fix would need.

  • Acts only after two bad checks in a row, because a normal switch takes a few seconds to settle
  • At most 12 repairs an hour, then a five-minute pause
  • Finds the switch by the keyboard and mouse it carries, so moving the cable to another port changes nothing

B

Repair one port

The software equivalent of unplugging one cable and plugging it back in.

  • Power-cycles only the switch’s port: 0 devices on it 3 seconds later, 3 healthy devices at 12 seconds5
  • The second monitor and the spare keyboard stay connected
  • One-click and forced runs for manual use

C

Escalate, safely

A second tier is built to restart the PC’s entire USB controller, and never without a way back.1

  • A one-shot failsafe task is armed first to switch USB back on after 90 seconds, then canceled when the reset step ends
  • Off by default; automatic only after three failed port cycles, at most twice an hour
  • A manual reset requires typing YES

D

Capture the evidence

One click saves the full USB picture to a text file, so two moments can be compared line by line. This is the tool that made the control experiment readable.

  • Port-level connection status that Device Manager does not show
  • Device addresses, speeds, problem codes, power settings and 24 hours of USB events
  • The before-and-after pair that settled the hardware question

05Under the hood

For the technical reader: the model, the math and the code.

Under the hoodEnumeration traces, raw hub IOCTLs, the control experiment and pseudo-code for the technical reader

The engineering interest is the method: locate the failure in the USB enumeration sequence, eliminate causes with one live test each, read port state through raw hub IOCTLs, settle the hardware question with a control experiment, and then judge the repair tool by its own log. The tool is PowerShell 5.1 with a small C# P/Invoke layer (DeviceIoControl, CfgMgr32) and no bundled runtime. It ran on Shuo’s office development PC, not on a trading machine.

Where enumeration breaks

A newly attached USB device is given an address (SET_ADDRESS) and then asked for its device descriptor. The failing nodes stopped at precisely those two steps: Set Address Failed, and on one cycle Device Descriptor Request Failed. A 150-second device-tree logger across four deliberate switch cycles showed the switch’s internal hub returning healthy every time (back after 5.6, 10.6, 9.3 and 17.7 seconds) while both peripherals behind it failed every time. The hub was sound; the devices behind it were not getting through enumeration.

Device Manager cannot show what a port itself reports, so the port state was read with IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX (0x220448), port by port on the root hub and on the switch’s own hub. The marshaled struct needs Pack=1, because usbioctl.h declares it under pshpack1; with default packing the fields land in the wrong bytes. The query showed the switched-away port as NoDeviceConnected and the failing one as DeviceFailedEnumeration, with no over-current or insufficient-power flag anywhere. That absence is what ruled out a power fault.

Pseudo-code
# One port's status, read straight from its hub: the values Device Manager never shows.
# The structure must be packed to 1 byte, as usbioctl.h declares it (pshpack1);
# with default alignment, every field after is_hub would be read one byte late.
struct PortInfo, packed to 1 byte:
    port_index         uint32       # in: which port to ask about
    device_descriptor  18 bytes     # vendor, product, device class, ...
    current_config     uint8
    speed              uint8
    is_hub             uint8
    device_address     uint16       # rises with every enumeration
    open_pipes         uint32
    connection_status  uint32       # NoDeviceConnected, DeviceFailedEnumeration,
                                    # DeviceCausedOvercurrent, DeviceNotEnoughPower, ...

for port in ports_of(hub):
    info = PortInfo(port_index=port)
    DeviceIoControl(hub, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX, info, info)
    record(port, info.connection_status, info.device_address, info.speed)
Pseudo-code. How the snapshot tool reads one port’s status, simplified. connection_status and device_address are the two fields the diagnosis rests on.

Six hypotheses, each put to a live test

Each row was run against the live fault. A failed fix was kept as a result, not discarded.

Diagnosis timeline, Aug 18 and Aug 20, 2026. Restart, not shut down: with Windows Fast Startup on, a shutdown hibernates the kernel and does not re-initialize the USB stack.
HypothesisTestResult
Stale driver stateDisable and re-enable the switch’s hubRejected: faulty nodes returned with identical IDs
Stale device nodesCM_Query_And_Remove_SubTree, then rescanRejected: clean removal, nodes regenerated within seconds
USB selective suspendDisabled on the power plan and on all 10 hubsRejected: fault reproduced anyway
Weak or faulted port powerPort-level status flags, before and afterRejected: no over-current or power flag at any point
The switch is failing hardwareControlled restart: snapshot, restart, snapshotRejected: same hardware, 0 of 23 nodes faulty3
State held in the PC’s USB stackSame restart testSupported: only a re-initialization has restored it durably4

The control experiment

On Aug 20 the port cycle failed on 7 of 8 completed attempts, and a physical replug, unplugging the peripherals and powering off the other PC failed too. A sample-by-sample trace showed the hub never losing power during the cycle. The inference to dying hardware was reasonable and untested. The restart test costs one reboot and has a clean reading: if identical hardware enumerates after the PC’s USB stack is re-initialized, the hardware is exonerated.

It did. The snapshots also show the USB device addresses, which rise with each enumeration, far higher before the restart than after. That measures heavy re-enumeration churn on the controller and points at controller-side state; it does not by itself identify the mechanism.4

The Sep 4 record sharpens the claim instead of flattering it. With addresses already at 48 to 59, the fault cleared twice without any re-initialization and relapsed both times. So the supported statement is the narrow one: enumeration becomes unreliable as state builds up, and only a restart has restored it durably. A stronger story, that the port can no longer enumerate at all, is contradicted by the log and is not claimed.

From the three saved snapshots. Same PC, same switch, same peripherals. The Sep 4 row shows the same signature building within one working day of a fresh boot.
SnapshotUptimeSwitch hub addressOther hubsFaulty nodes
Aug 20, before restart1,753 min5546 / 451
Aug 20, after restart1 min46 / 20 of 23
Sep 4, fault recurring423 min4857 / 592

Tier 1: cycling one port

IOCTL_USB_HUB_CYCLE_PORT is CTL_CODE(FILE_DEVICE_USB, 273, METHOD_BUFFERED, FILE_ANY_ACCESS), that is 0x220444. Sent to the parent hub with an 8-byte buffer holding the port index, it makes the hub driver simulate a disconnect and reconnect on that one port. Microsoft documents the call as unsupported on Windows Vista and 7 and supported again from Windows 8, so it was tested before being relied on: it works on this PC’s Windows 10, and the error path decodes ERROR_NOT_SUPPORTED for a system where it does not.

The target is never a hard-coded port, because the switch moved from one root port to another when its cable was replugged. It is resolved in priority order: the parent hub of a faulty node; else the hub carrying the remembered keyboard and mouse hardware IDs; else the hub with at least two input devices behind it. Each candidate is resolved to the port it occupies on its parent hub and rejected unless Windows lists it as a hub.

Pseudo-code
def find_switch_port(devices):
    # Never a hard-coded port: the switch moved when its cable was replugged.
    candidates = (parents_of_faulty_nodes(devices)               # 1. the fault itself
                  + hubs_carrying(remembered_peripheral_ids)     # 2. the keyboard and mouse
                  + [hub_with_most_input_devices(at_least=2)])   # 3. best guess
    for hub in candidates:
        if hub is not None and listed_as_hub(hub):   # never cycle the mouse instead of the switch
            return parent_of(hub), port_on_parent(hub)
    return None

def cycle_port(parent_hub, port):
    # The software unplug and replug of one cable; nothing else on the PC drops.
    handle = open_device(interface_path(parent_hub, USB_HUB_INTERFACE))
    request = [port, 0]                 # 8 bytes: port index, status returned
    ok = DeviceIoControl(handle, IOCTL_USB_HUB_CYCLE_PORT, request, request)
    if not ok:
        log(describe(last_win32_error()))   # e.g. not supported, nothing on that port
    close(handle)
    return ok
Pseudo-code. Tier 1, simplified: find the switch by what is plugged into it, then cycle that one port.

Control logic and safety rails

The watcher is a debounced, rate-limited control loop. With bt the run of consecutive bad polls, ct the run of failed port cycles, A1h and R1h the port cycles and controller resets in the trailing hour, and e the opt-in flag:

cycle the port at poll t⟺bt≥2∧A1h<12reset the controller at poll t⟺bt≥2∧ct≥3∧e=1∧R1h<2
Polls are 3 s apart; each cycle is followed by a 12 s settle before the re-check. At the hourly cap the watcher backs off for five minutes and re-checks.
Pseudo-code
def reset_controller(controller):       # tier 2: opt-in, at most twice an hour
    # Arm the way back before taking anything away: a one-shot scheduled task,
    # run by Windows rather than by this script, that re-enables the
    # controller 90 s from now.
    failsafe = schedule_once(after=seconds(90), task=re_enable, target=controller)
    log("failsafe armed")
    disable(controller)                 # every USB device drops, keyboard included
    enable(controller)                  # with retries
    cancel(failsafe)                    # reset step over: disarm the rescue
    log("failsafe disarmed")
    # If the script dies between disable and enable, the armed task still
    # restores USB at 90 s: a crash mid-reset cannot strand the PC.
Pseudo-code. Tier 2, simplified: the way back is armed before the controller is touched. Error handling is left out.

Field record: what the tool’s own log shows

The log, read line by line, is the result. Tier 1 reproduces a replug but did not hold against the accumulated fault, and this PC’s controller driver refused the tier 2 disable call. The failsafe armed and disarmed correctly on both attempts. The conclusion the data supports: enumeration becomes unreliable as state builds up, and only a re-initialization of the USB stack has restored it durably.1

Source: the tool’s own log, 305 lines, Aug 18 to Sep 6, 2026.
DateEventOutcome
Aug 18Forced port cycle on a healthy portMechanism confirmed: 0 nodes at 3 s, 3 healthy at 12 s
Aug 20Live fault, watcher cycles7 of 8 cycles leave 2 faulty nodes; one transient clear
Aug 20Controlled restart0 of 23 nodes faulty
Sep 4Live fault 5 h 14 min after boot24 consecutive failed cycles across two rate-limit windows
Sep 4Manual port cycleFaults 2 → 0, back to 2 within about 40 s
Sep 4Controller reset, run by hand twiceDriver refused: “Not supported”; failsafe armed and disarmed

Why not something simpler?

The questions a reviewer would ask, answered from the record.

Open item, recorded as open: other ways of restarting the controller were not tested after the driver refused the disable call.
AlternativeWhy it was not the design
Replace the switchThe control experiment: identical hardware enumerated cleanly after a restart, 0 of 23 nodes faulty.3
Reset the controller firstThe PC has a single USB host controller. A reset takes down every USB device at once, for about 10 seconds by design, the second monitor’s display adapter included. One port goes first; the controller is opt-in.
Hard-code the switch’s portThe switch moved to a different root port when its cable was replugged. The target is resolved from the keyboard and mouse hardware IDs on every repair.
Act on the first bad pollA healthy switch needs several seconds to re-enumerate: its hub took 5.6 to 17.7 seconds in the four-cycle trace. So the watcher waits for two consecutive bad polls, then allows a 12-second settle before the re-check.
Retry without limitA fault that will not clear would be cycled forever. The caps are 12 port cycles and 2 controller resets an hour, and a single-instance guard was added after two watchers were found cycling the same port against each other.
Disable the controller unguardedA crash between disable and enable would leave the PC with no USB input at all. A one-shot scheduled task, armed first, re-enables it after 90 seconds even if the script crashes or is stopped mid-reset.
A bundled runtimePowerShell 5.1 ships with Windows and the P/Invoke layer is small, so there is nothing to install. A deliberate departure from the bundled-runtime packaging of The Guardian.
Shut down instead of restartWith Windows Fast Startup on, a shutdown hibernates the kernel and leaves the USB stack as it was. Only Restart re-initializes it, so the control experiment specified Restart.
Read the address data as proof of mechanismAn address counts enumerations. It shows churn, not which controller resource is exhausted, and the Sep 4 log contradicts the strongest reading.4

Failure modes engineered out

Seven defects were found by testing against the PC’s own device tree, and fixed:

  • A hub-detection heuristic that picked the USB sound card’s hub instead of the switch
  • A parent walk from a composite-interface node that resolved the mouse as the hub, which would have cycled the mouse instead of the switch cable
  • .Count on a single unrolled CimInstance returning empty, so status reported the watcher as stopped while it ran
  • A duplicate watcher instance, closed with a single-instance guard
  • A root-hub resolution gap that made the switch invisible
  • A config save that dropped the escalation flag
  • An O(n²) property scan that hit a two-minute timeout, replaced by one device snapshot per poll

One more was found by the field log and is recorded as open: PowerShell 5.1 read the script without a byte-order mark as ANSI, so the one Chinese file name in the watcher’s escalation hint was written garbled.

Built with

  • PowerShell 5.1
  • C# P/Invoke
  • Win32 DeviceIoControl
  • USB hub IOCTLs
  • CfgMgr32
  • PnP device tree
  • Windows scheduled tasks
  • Windows internals
  • xHCI / USB enumeration
  • Debounce and rate limiting
  • Fail-safe automation
  • Timestamped event log
  • Root-cause analysis
  • Control experiments

06Releases

Shipped in versions, like a product.

  1. 1.0Live diagnosis, port power cycle, background logon watcher with debounce and rate limit, one-click wrappers.
  2. 1.1Restart control experiment and revised root cause. Controller-reset tier behind a 90-second failsafe, single-instance guard, root-hub resolution fix, snapshot tool.
  1. 1Field log through Sep 6, 2026, on one office development PC (not a trading machine). The port cycle did not durably clear the accumulated fault: 24 consecutive failed cycles on Sep 4, and one clear that relapsed within about 40 seconds. The controller driver on this PC refused the reset tier (“Not supported”), and automatic escalation was never enabled.
  2. 2Ruled out on Aug 18 and Aug 20, 2026: stale driver state, stale device nodes, USB selective suspend, a port power fault, and failing switch hardware. Each was tested against the live fault.
  3. 3Aug 20, 2026: the restart test was proposed at 18:36 and confirmed at 18:54. The state was captured before and after; one minute after boot, 0 of 23 USB device nodes were faulty, with no hardware or cabling changed in between.
  4. 4USB device address of the switch’s hub chip in the saved snapshots: 55 after 1,753 minutes of uptime, 4 one minute after the restart. An address rises with each enumeration, so the gap shows re-enumeration churn on the controller. The mechanism inside the controller was not measured and is not claimed; on Sep 4, 2026 the fault twice cleared briefly without a re-initialization while addresses stood at 48 to 59.
  5. 5Measured on Aug 18, 2026 in a forced cycle of a healthy port: the mechanism test, not a live repair.
Previous
Previous

Spread Liquidity Study

Next
Next

Futures Risk Monitor