I am using Python 2.6 to communicate with a device on a serial port. I want to make sure the device is still active every 10 seconds. The best way I've found to do this is to start a thread that pings the device every so often (other methods, to be designed later, will send configuration commands out the serial port, thus the global). Below is my code inspired from here.
When I enter "quit", the ConnectionThread
seemingly only loses the 10 second timer and continuously spams the PING message. What is causing this, and how do I just end the entire thread?
import serial
import threading
ser = 0
class ConnectionThread(threading.Thread):
def __init__(self, event, **kwargs):
threading.Thread.__init__(self)
self.stopped = event
for key, value in kwargs.items():
setattr(self, key, value)
def run(self):
while not self.stopped.wait(10):
ser.write("{0},{1}\r".format(self.name,"PING"))
def main():
global ser
commport = input("Enter COM port:")
try:
ser = serial.Serial(
port = 'COM{0}'.format(commport),
baudrate = 9600
)
except:
print "Unable to open com port!"
stopFlag = threading.Event()
thread = ConnectionThread(stopFlag)
thread.start()
while True:
n = raw_input("Enter input:")
if n == "quit":
stopFlag.set()
break
if __name__ == "__main__":
main()