python控制网络继电器
网络继电器配置如下:
1. 搜索局域网网络设备
2. 参数配置&写入配置
这里网络继电器作为服务端。客户端通过socket建立链接并发送开关指令(socket对接即可。mqtt根据需求配置(高版本mqtt协议不支持)))
import socket def open_door(rely_host="", rely_port=12345, channel_id=0, timeout=5): try: client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.settimeout(0.5) client.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) client.connect((rely_host, rely_port)) print(f"控制继电器通道{channel_id}开端口发送吸合发送:AT+STACH{channel_id}=1,{timeout}\\r\\n") cmd = f"AT+STACH{channel_id}=1,{timeout}\r\n" client.send(cmd.encode()) print(client.recv(BUFF_SIZE).decode()) except Exception as e: print(e) return False else: client.close() print("Socket关闭") return True if __name__ == '__main__': """ 数据库逻辑微调 1. 继电器初始化配置 2. 继电器开启超时时间 3. MQTT仅支持低版本 rely_host: 继电器ip rely_port: 继电器端口,默认12345 channel_id: 继电器通道口,默认为0表示所有 timeout: 开门->闭合超时时间 """ HOST = "192.168.2.199" PORT = 12345 BUFF_SIZE = 1024
# 表示通道一开门。3秒后关闭 status = open_door(rely_host=HOST, rely_port=PORT, channel_id=1, timeout=3) if not status: print("开门失败") else: print("开门成功")
---
import socket def operating_network_relay(rely_host="", rely_port=12345, channel_id=0, timeout=5, operate_type=None): """ rely_host: 继电器ip rely_port: 继电器端口,默认12345 channel_id: 要开启的路数,默认为0表示所有 timeout: 开 -> 关超时时间 operate_type: 可选 open|close 为空表示超过超时时间自动关门 """ try: client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.settimeout(0.5) client.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) client.connect((rely_host, rely_port)) if operate_type == "open": print(f"控制继电器通道{channel_id}合:AT+STACH{channel_id}=1\\r\\n") cmd = f"AT+STACH{channel_id}=1\r\n" elif operate_type == "close": print(f"控制继电器通道{channel_id}开:AT+STACH{channel_id}=0\\r\\n") cmd = f"AT+STACH{channel_id}=0\r\n" else: print(f"控制继电器通道{channel_id}合{timeout}秒开:AT+STACH{channel_id}=1,{timeout}\\r\\n") cmd = f"AT+STACH{channel_id}=1,{timeout}\r\n" client.send(cmd.encode()) print("继电器返回: ", client.recv(BUFF_SIZE).decode()) except Exception as e: print(e) return False else: client.close() print("Socket关闭") return True if __name__ == '__main__': HOST = "192.168.2.199" PORT = 12345 BUFF_SIZE = 1024 status = operating_network_relay(rely_host=HOST, rely_port=PORT, channel_id=1, timeout=3) if not status: print("指令发送失败") else: print("指令发送成功")
本文来自博客园,作者:一石数字欠我15w!!!,转载请注明原文链接:https://www.cnblogs.com/52-qq/p/17243998.html