列出可用的串口

List available serial ports

我正在寻找一种方法来列出可用的串行端口(不管 ruby 串行端口 gem)。现在,我尝试了下面的 ruby gems:

我知道如何在 Python、.NET /mono C# 中做到这一点,Java 但我无法在 ruby 中获取此信息,知道吗?

仅限windows

require 'rubyserial'

def seach_ports
  ports = []
  1.upto 64 do |index|
    begin
      serial = Serial.new  portname = 'COM' + index.to_s
      ports << portname if serial
      serial.close
    rescue  Exception => e
      ports << portname if e.to_s.include? "ACCESS_DENIED"
    end
  end
  return ports 
end

p ports = seach_ports

或端口状态

require 'rubyserial'

def seach_ports
  ports = {}
  1.upto 64 do |index|
    begin
      serial = Serial.new  portname = 'COM' + index.to_s
      ports[portname] = 'is available' if serial
      serial.close
    rescue  Exception => e
      ports[portname] = 'access denied' if e.to_s.include? "ACCESS_DENIED"
    end
  end
  return ports 
end

p seach_ports