require "timeout" class Rs232c def initialize(adrs=0, baud=9600, bit=8, parity="odd", stopbit=1, delim="\x0d\x0a") devname="/dev/ttyUSB%d"%adrs @port=open(devname,"r+") odd=(parity=~/o/i) str="%d cs%d %sparenb %sparodd %scstopb"%[baud,bit,(parity)?"":"-",(odd)?"":"-",(stopbit==2)?"":"-"] system("stty raw -echo -crtscts "+str+" <%s"%devname) # system("stty raw -echo -crtscts 9600 cs8 -parenb -parodd cstopb <%s"%devname) # 9600, 8bit, parity, even, stop1 @delim=delim # @delim="\x0d" each_init end def finish @port.close end def each_init() # initialization for each instrument end def talk(str) begin strs=str+@delim timeout(1){ @port.write(strs) @port.flush } rescue TimeoutError puts "write timeout error at #{Time::now} on ttyUSB with '#{str}'" end end def echo(str) begin strs=str+@delim timeout(1){ strs.split(//).each{|s| @port.write(s) @port.flush @port.read(1) } } rescue TimeoutError puts "write timeout error at #{Time::now} on ttyUSB with '#{str}'" end end def listen(n=256) begin timeout(2){ # @port.readpartial(256) @port.gets(@delim) } rescue TimeoutError puts "read timeout error at #{Time::now} on ttyUSB" return 0 end end def idn() talk(sprintf("*IDN?")) listen() end end #class