I am trying to do simple serial link program for school project and I have small problem. I created class to maintain serial communication, but when I unplug and plug back serial port, it doesnt change state of serial connection (self.ser have still same object like when it was initalized). I want it to recconnect and continue to work. Can you please help me and tell mi what I am doing wrong? I am new to python. Thank you very much!
import serial
import uuid
class SerialWrapper:
def __init__(self):
self.ser = serial.Serial("COM3", 9600)
def handleconnect(self):
try:
if self.ser is None:
self.ser = serial.Serial("COM3", 9600)
self.ser.close()
self.ser.open()
print("Reconnecting...")
except:
if not (self.ser is None):
self.ser.close()
self.ser = None
print("Disconnecting")
else:
print("No Connection")
def serialwrite(self, data):
self.handleconnect()
try:
datalength = self.ser.write(data.encode())
print("Writing data...")
return datalength
except:
print("Error in writing data")
def serialread(self, datalength):
self.handleconnect()
try:
data = self.ser.read(datalength).decode()
print("Reading data...")
return data
except:
print("Error in reading data")
def main():
ser = SerialWrapper()
while 1:
value = uuid.uuid4().hex
length = ser.serialwrite(value)
print(ser.serialread(length))
main()