The WADBS widget can get the port even if it is not displayed on the screen, but it is not suitable for non-root automation because it relies on Shizuku.
I was able to build an app that opens wireless debugging, so I think this can be automated even with non-root.