我正在尝试创建一个每1秒递增一个变量的线程计时器。该变量位于回调函数中,并在串行接收函数中查询,以便在规定时间内未收到数据时设置超时。回调函数以及接收函数都将变量声明为全局变量,并将变量声明为在定时器类之外声明。每当触发回调时,都会显示分配错误。不确定我做错了什么来修复此错误。
# python27 Serial Interface Prototype - MH 20170711
__author__ = 'MHammersley'
from serial import *
import threading
gRdTimeout = 0
t = None
class Cmd_Resp(object):
# opens a usb-to-serial com port session at the specified baud rate
def __init__(self, serial_port, baud, delimiter = '/n'):
#ensure non-blocking
self.serial_port = serial_port
self.baud = baud
self.delimiter = delimiter
self.port = Serial(serial_port, baud, timeout = 0, writeTimeout=0)
global t
self.t = threading.Timer(1.0, self.UpdateTimer).start()
# this function updates the timer variable in 1 second increments
def UpdateTimer(self):
global gRdTimeout
gRdTimeOut += 1
print('Count: ', gRdTimeout)
def start(self):
global t
self.t.start() # start the timer
# write only command, no read response
def send(self, cmd):
#Write command to com port
self.port.write(cmd+self.delimiter)
# read only until the expected response string is received
def receive(self, exp_resp, timeout):
#Read device response from com port.
global gRdTimeout, t
gRdTimeOut = 0 # set the timeout count to 0
serBuffer = "" # empty the buffer
tflag = True
self.t.start() # start the timer
loop = True
while (loop != False):
c = self.port.read()
if c == '\n':
serBuffer += "\n" # add the newline to the buffer
else:
serBuffer += c # add to the buffer
if exp_resp in serBuffer:
loop = False
if gRdTimeout >= timeout:
break
self.t.cancel() # stop the timer
return serBuffer
# sends a command to the uut and reads until the expected response is received
def request(self, cmd, exp_resp):
self.send(cmd)
self.exp_resp = exp_resp
return self.receive(exp_resp)
答案 0 :(得分:1)
def UpdateTimer(self):
global gRdTimeout # lowercase O
gRdTimeOut += 1 # capital O
print('Count: ', gRdTimeout)
那就是说,你应该真的避免使用像这样的全局变量。特别是因为你已经把它封装成一个类的麻烦了。根据{{1}}致电receive
时设置超时最长值,然后在每次检查时查看datetime.datetime.now() + datetime.timedelta(seconds=timeout)
是否早于或晚于截止值。
datetime.datetime.now()