Serial

Python 2023. 4. 19. 15:36
import serial
import threading
import time
import parkingControl as Main
class Serial:
    def __init__(self, port, baudrate):
        self.port = port
        self.baudrate = baudrate
        self.serial_port = None
        self.thread_recv = None
        self.is_recv = False
   
    def connect(self):
        try:
            self.serial_port = serial.Serial(self.port, self.baudrate, timeout=0)
            self.is_recv = True
            self.thread_recv = threading.Thread(target=self.recv)
            self.thread_recv.daemon = False
            self.thread_recv.start()
            print("Connected!!")
        except Exception as e:
            print(f"Error connecting to serial port: {e}")
   
    def recv(self):
        while self.is_recv:
            data = self.serial_port.readline().decode().strip()
            if data:
                Main.on_receive_serial(data)

    def disconnect(self):
        self.is_recv = False
        if self.thread_recv:
            self.thread_recv.join()
        if self.serial_port:
            self.serial_port.close()
        print(f"diconnect {self.port}")

    def send(self, data):
        self.serial_port.write(data.encode())

if __name__ == "__main__":
    s = Serial("COM7", 115200)
    s.connect()
    while True:
        s.send("Hello, world!")
        time.sleep(10)

'Python' 카테고리의 다른 글

uft-8  (0) 2022.10.31
aes256 암호화 복호화  (0) 2021.01.27
: