import sys
import logging
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QLineEdit
from PyQt5.QtCore import Qt
import modbus_tk.defines as cst
from modbus_tk import modbus_tcp

# 配置日志以十六进制形式显示报文
logging.basicConfig()
log = logging.getLogger('modbus_tk')
log.setLevel(logging.DEBUG)


class ModbusControlWindow(QWidget):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Modbus Control Window")
        self.setGeometry(100, 140, 400, 200)

        self.label_ip = QLabel("IP Address:", self)
        self.label_ip.move(20, 20)
        self.text_ip = QLineEdit("192.168.1.181", self)
        self.text_ip.setGeometry(120, 20, 200, 20)

        self.label_device_id = QLabel("Device ID:", self)
        self.label_device_id.move(20, 60)
        self.text_device_id = QLineEdit("1", self)
        self.text_device_id.setGeometry(120, 60, 200, 20)

        self.btn_addr646 = QPushButton("向上", self)
        self.btn_addr646.move(20, 100)
        self.btn_addr646.clicked.connect(lambda: self.send_modbus_command(646))

        self.btn_addr647 = QPushButton("向下", self)
        self.btn_addr647.move(120, 100)
        self.btn_addr647.clicked.connect(lambda: self.send_modbus_command(647))

        self.btn_addr648 = QPushButton("确定", self)
        self.btn_addr648.move(220, 100)
        self.btn_addr648.clicked.connect(lambda: self.send_modbus_command(648))

        self.btn_addr649 = QPushButton("复位", self)
        self.btn_addr649.move(320, 100)
        self.btn_addr649.clicked.connect(lambda: self.send_modbus_command(649))

        self.bin_addr628 = QPushButton("短路试验", self)
        self.bin_addr628.move(20, 140)
        self.bin_addr628.clicked.connect(lambda: self.send_modbus_command(628))

        self.bin_addr629 = QPushButton("漏电试验", self)
        self.bin_addr629.move(120, 140)
        self.bin_addr629.clicked.connect(lambda: self.send_modbus_command(629))

        self.bin_addr641 = QPushButton("过压试验", self)
        self.bin_addr641.move(220, 140)
        self.bin_addr641.clicked.connect(lambda: self.send_modbus_command(641))

        self.bin_addr642 = QPushButton("电流断相试验", self)
        self.bin_addr642.move(320, 140)
        self.bin_addr642.clicked.connect(lambda: self.send_modbus_command(642))

        self.bin_addr636 = QPushButton("小车进", self)
        self.bin_addr636.move(20, 180)
        self.bin_addr636.clicked.connect(lambda: self.send_modbus_command(636))

        self.bin_addr637 = QPushButton("小车退", self)
        self.bin_addr637.move(120, 180)
        self.bin_addr637.clicked.connect(lambda: self.send_modbus_command(637))

    def send_modbus_command(self, addr):
        ip_address = self.text_ip.text()
        device_id = int(self.text_device_id.text())

        # 连接Modbus设备
        try:
            master = modbus_tcp.TcpMaster(host=ip_address, port=502)
            master.set_timeout(5.0)
        except Exception as exc:
            print(f"Failed to connect to Modbus device: {exc}")
            return

        # 发送Modbus功能码0x05
        try:
            master.execute(device_id, cst.WRITE_SINGLE_COIL, addr, output_value=1)
            print(f"Modbus command to address {addr} sent successfully.")
        except Exception as exc:
            print(f"Failed to send Modbus command to address {addr}: {exc}")
        finally:
            master.close()

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Up:
            self.send_modbus_command(646)
        elif event.key() == Qt.Key_Down:
            self.send_modbus_command(647)
        elif event.key() == Qt.Key_Return or event.key() == Qt.Key_Enter:
            self.send_modbus_command(648)
        elif event.key() == Qt.Key_Space:
            self.send_modbus_command(649)
        elif event.key() == Qt.Key_A:
            self.send_modbus_command(628)
        else:
            super().keyPressEvent(event)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = ModbusControlWindow()
    window.show()
    sys.exit(app.exec_())
    