python3串⼝读写pyserial # -*- coding: utf-8 -*-
# @Time    : 2021/3/3 14:20
# @Author  : juzi_juzi
# @Email  : juzi_juzi@163
# @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 = None
def com_open(self):
"""
串⼝的的打开;
:return: 返回串⼝的句柄;
"""
try:
self = serial.Serial(self.port, self.baudrate, timeout=self.timeout)
logging.debug('Open Serial: {}'.format(self.port))
except Exception as msg:
<('open port:{}, baudrate:{} error occur'.format(self.port, self.baudrate))
<(msg)
def com_close(self):
"""
串⼝的关闭;
:return:None;
"""
if self is not None and self.isOpen:
logging.info('Close Serial: {}'.format(self.port))
self.close()
def com_send_data(self, data):
"""
向打开的端⼝发送数据;
:param data: 发送的数据信息;
:return: 发送的数据内容的长度;
"""
if self is None:
self_open()
success_bytes = self.de('UTF-8'))
return success_bytes
def com_get_data(self, timeout=5):
"""
通过串⼝获取数据,默认等待时间为5s,
:param timeout: 读取数据的超时时间,默认值为5;
:return: 获取串⼝返回的数据;
"""
all_data = ''
if self is None:
self_open()
start_time = time.time()
while True:
end_time = time.time()
if end_time - start_time < timeout:
len_data = self.inWaiting()
if len_data != 0:
for i in range(1, len_data + 1):
data = ad(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):
"""
打开串⼝的⽅法;
python怎么读取串口数据:return:返回当前串⼝句柄;
"""
self_open()
def com_ap_close(self):
"""
关闭串⼝;
:return:None;
"""
self_close()
def com_ap_send_data(self, data, default_char='\r'):
"""
向串⼝发送指定字符串,默认发送完最后加回车;
:param data: 发送的命令;
:param default_char: 发送的命令后添加的默认回车字符;        :return:发送的字符长度;
"""
self_send_data(data + default_char)
def com_ap_get_data(self, timeout=2):
"""
从串⼝读取数据,默认在等待时间后读取的数据返回;
:param timeout:默认值为2s;
:return: 串⼝返回的数据;
"""
return self_get_data(timeout)

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。