我有以下串行端口的读写代码。但是当我频繁地运行它们时,比如说读写100次,总有一些时候读得到错误的字节数,它应该得到9个字节,但有时它只有8个字节。在
例如,通常当我发送[1,88,0,27,192]时,它应该返回9个字节,比如[1,88,4,0,0,3,35,182,49]。但是它总是在89次读写错误,它返回的值是[1,88,4,0,1,209,107,180],少1个字节。当我检测到这是1个字节丢失后,我再次写入和读取相同的发送消息,如[1,88,0,27,192],在这之后读取的数据总是丢失一个字节。但是,在其他语句之后,1字节丢失问题不会每次都出现。在
我遇到了另一个问题,比如,设备有时无法接收到我对特定命令的写入,具体地说,当我发送一个命令后,没有返回,因为我的串行设备没有接收到,所以它不能执行。所以我不得不关闭()和open()这样的端口,再发送几次命令,要使它返回aka excute命令,这样的重试花费了太多的时间,这让我再次等待。在
我的配置,FT232RL USB到串行芯片,9600波特率,8字节大小,超时1秒,停止位1,奇偶校验无。在
def SendData(self, portID, cmd):
"""
cmd is the pre-defined variables , they are the lists in front of this file.
After send data, there is a delay.
"""
global command_count
if (self.isOpen(portID)):
command_count += 1
lock = threading.RLock()
with lock:
try:
COMlogger.debug("SendData command count %d" % (command_count))
writereturn = self.serdict[portID].write(list2bytestr(cmd))
# wait for output buffer to drain, reference from the miniterm example
self.serdict[portID].flush()
self.lastcmd = cmd
COMlogger.debug("SendData sent out %s" % (str(cmd)))
COMlogger.debug("SendData write returns %d bytes." % writereturn)
except:
COMlogger.error("Sending data to %s with ID %d failed." % (self.portaddresslist[portID], portID))
return False
finally:
time.sleep(0.2)
return True
return False
def GetData(self, portID):
"""
It take times to let the device respond, so remember to wait a bit after sending data.
Before get data, there is a deley
"""
time.sleep(0.2)
global command_count
if (self.isOpen(portID)):
lock = threading.RLock()
with lock:
try:
# possibly time out here
#receivedmsg = self.serdict[portID].readline() # stop using readline since it wait for the \n or time out.
text = self.serdict[portID].read(1)
if text:
time.sleep(0.2)
n = self.serdict[portID].inWaiting()
if n:
text += self.serdict[portID].read(n)
receivedmsg = text
COMlogger.debug("GetData from ID %d returned %s" %(portID, str(bytestr2list(receivedmsg))))
return receivedmsg
except:
COMlogger.error( "Receiving data from %s with ID %d failed." % (self.portaddresslist[portID], portID))
return None
else:
COMlogger.error("Error in GetData, port %d is not open." % portID)
return None
目前没有回答
相关问题 更多 >
编程相关推荐