#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@文件    :com.py
@时间    :2022/11/14 17:28:23
@作者    :None
@版本    :1.0
@说明    :modbus 485驱动
'''

import serial.tools.list_ports
import serial
from serial.serialutil import SerialException
from utils.modbus import modbus_rtu


class ComMaster:
    def __init__(self):
        super(ComMaster, self).__init__()
        self.master = None

    def set_com(self, port, baudrate, bytesize, parity, stopbits):
        self.port = port
        self.baudrate = baudrate
        self.bytesize = bytesize
        self.parity = parity
        self.stopbits = stopbits

    def open_device(self):
        try:
            self.master = modbus_rtu.RtuMaster(serial.Serial(port=self.port, baudrate=self.baudrate, bytesize=self.bytesize, parity=self.parity, stopbits=self.stopbits, xonxoff=0))
            self.master.set_timeout(1)
            self.master.set_verbose(True)
            return True
        except SerialException:
            return False

    def send(self, slave, function_code, starting_address, byte_count):
        ret = self.master.execute(slave, function_code, starting_address, byte_count)
        print(list(ret))
        return ret
