# -*- coding: utf-8 -*- # @Time : 2021/3/3 14:20 # @Author : juzi_juzi # @Email : juzi_juzi@163.com # @File : serialcom.py # @Software: PyCharm # import time import serial import logging class SerialUtils: def __init__(self, port, baudrate=115200, timeout=5): self.port = port self.baudrate = baudrate self.timeout = timeout self.com = None def com_open(self): """ 串口的的打開; :return: 返回串口的句柄; """ try: self.com = serial.Serial(self.port, self.baudrate, timeout=self.timeout) logging.debug('Open Serial: {}'.format(self.port)) except Exception as msg: logging.error('open port:{}, baudrate:{} error occur'.format(self.port, self.baudrate)) logging.error(msg) def com_close(self): """ 串口的關閉; :return:None; """ if self.com is not None and self.com.isOpen: logging.info('Close Serial: {}'.format(self.port)) self.com.close() def com_send_data(self, data): """ 向打開的端口發送數據; :param data: 發送的數據信息; :return: 發送的數據內容的長度; """ if self.com is None: self.com_open() success_bytes = self.com.write(data.encode('UTF-8')) return success_bytes def com_get_data(self, timeout=5): """ 通過串口獲取數據,默認等待時間為5s, :param timeout: 讀取數據的超時時間,默認值為5; :return: 獲取串口返回的數據; """ all_data = '' if self.com is None: self.com_open() start_time = time.time() while True: end_time = time.time() if end_time - start_time < timeout: len_data = self.com.inWaiting() if len_data != 0: for i in range(1, len_data + 1): data = self.com.read(1) data = data.decode('utf-8') all_data = all_data + data if i == len_data: break else: logging.debug('Received data is null') else: break logging.debug('Received data:{}'.format(all_data)) return all_data class ComAP(SerialUtils): def __init__(self, port, baudrate=115200, timeout=5): super().__init__(port, baudrate, timeout) def com_ap_open(self): """ 打開串口的方法; :return:返回當前串口句柄; """ self.com_open() def com_ap_close(self): """ 關閉串口; :return:None; """ self.com_close() def com_ap_send_data(self, data, default_char='\r'): """ 向串口發送指定字符串,默認發送完最后加回車; :param data: 發送的命令; :param default_char: 發送的命令后添加的默認回車字符; :return:發送的字符長度; """ self.com_send_data(data + default_char) def com_ap_get_data(self, timeout=2): """ 從串口讀取數據,默認在等待時間后讀取的數據返回; :param timeout:默認值為2s; :return: 串口返回的數據; """ return self.com_get_data(timeout)