1
我想寫一個基本的驅動程序來控制只與超級終端交互的設備。所有輸入都需要HT格式化數據,並且所有的回報都包含豐富的等號,換行符和空格,以便爲人類可視化獲得正確的格式。我非常確定回報會產生麻煩,因爲我會拋出異常,但我不知道我還能如何處理它。有誰知道更好的方法來做到這一點?控制只通過超級終端使用python進行交互的設備
設備手冊:http://us.startech.com/media/products/PCM815SHNA/Manuals/PCM815SHNA.pdf
import visa
import re
class iopower8(visa.SerialInstrument):
#initialization
def __init__(self,loc):
visa.SerialInstrument.__init__(self,loc)
self.term_chars = '\r' #set terminal characters
self.write('\r\r') #start faux 'Hyperterminal'
def on(self, bank, out):
self.ask("on " + str(bank) + " " + str(out))
for i in range (1,3):#read buffer into void to prevent issues
try:
self.read_raw()
except(visa_exceptions.VisaIOError):
self.buffer_clear()
break
return self.status(bank, out)
def off(self, bank, out):
self.ask("of " + str(bank) + " " + str(out))
for i in range (1,3):#read buffer into void to prevent issues
try:
self.read_raw()
except(visa_exceptions.VisaIOError):
self.buffer_clear()
break
return self.status(bank, out)
def status(self, bank, port): #enter bank and port # you want to check
self.ask("st " + str(bank))
result = 'Error' #send error message regardless
for i in range (1,13):#all 12 lines need to be read out of the buffer to prevent issues later
try:
stuff = self.read()#read the line to a holding srting, and dump in void if wriong line to clear buffer
if stuff.strip() == ('='*44):
break
except(visa_exceptions.VisaIOError):
break
for i in range(1,9):
try:
stuff = self.read()#read the line to a holding string, and dump in void if wriong line to clear buffer.
if i == port: #this offset will get you to the line with the relevant port's status
result = re.match('(.*?)(ON|OFF)', stuff) #regex to the find the on/off status
#convert to boolean
if result.group(2) == 'ON':
result = True
elif result.group(2) =='OFF':
result = False
else:
result = 'ERROR'
except(visa_exceptions.VisaIOError):
self.buffer_clear()
break
return result
def buffer_clear(self): #in case of buffer jamming
while True:
try:
self.read_raw()
except(visa_exceptions.VisaIOError):
break
def all_on(self, bank):
self.ask("on " + str(bank) + " 0")
for i in range (1,3):#read buffer into void to prevent issues
try:
hold = self.read_raw()
except(visa_exceptions.VisaIOError):
self.buffer_clear()
break
def all_off(self, bank):
self.ask("of " + str(bank) + " 0")
for i in range (1,3):#read buffer into void to prevent issues
try:
self.read_raw()
except(visa_exceptions.VisaIOError):
self.buffer_clear()
break
超級終端含義RS232? http://www.varesano.net/blog/fabio/serial%20rs232%20connections%20python – Novikov 2011-02-02 19:06:23
問題是格式。該設備是硬編碼,總是假定它正在與超級終端進行交互,所以輸出中存在大量垃圾,而且緩衝區中的多餘數據顯然沒有做足夠好的過濾工作,因爲它會週期性地拋出例外。據我所知,超級終端標準沒有很好的記錄。 – Elliot 2011-02-02 19:12:11