Search code examples
bashserial-portwindows-subsystem-for-linux

Find active serial ports in Windows Subsystem for Linux (WSL)


How can i find which serial-port is the active one in Windows Subsystem for Linux? I know about the added support in WSL for using the /dev/ttyS, but which of these ports are active?

The issue I'm trying to solve is I have a device which keep switching comport, because of the internal chip that reconnects it self on a new port. I want to create a bash script that finds the active serial-ports.

Regular linux commands like: dmesg | grep tty does not work.


Solution

  • I created a solution combining both Powershell and WSL.

    1.Create a Powershell script, comports.ps1:

    $DeadComport = 3
    $COMportList = [System.IO.Ports.SerialPort]::getportnames() 
    
    if ($COMportList.Count -cgt 2) {
        Write-Output "Too many com-ports connnected! " 
        Write-Host -NoNewline "Com-ports found:" $COMportList.Count
       
    }else{
         ForEach ($COMport in $COMportList) { 
            $temp = new-object System.IO.Ports.SerialPort $COMport 
            $portNr = $temp.PortName.SubString(3)
            if ($portNr -eq $DeadComport){
                continue   
            }
            Write-Output $portNr
            $temp.Dispose() 
        }
    }
    

    - You can debug this code in PowerShell ISE and adjust it to meet your preference.


    2.Create a bash script in WSL, comscript.sh:

    Preferably in the home/your-username/bin folder, that makes the bash-script globally executable.

    #!/bin/bash
    
    echo "Active com-port"
    powershell.exe -File "c:\your-folder\comports.ps1" 
    

    Now you can just call comscript.sh and it will output the active comport, if more then one device is found it will throw an error message.

    Be aware that I'm filtering out com-port 3, since it's always there and active on my computer.