1
This commit is contained in:
126
bin/192.168.8.125.py
Normal file
126
bin/192.168.8.125.py
Normal file
@@ -0,0 +1,126 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: UTF-8 -*-
|
||||
|
||||
import socket
|
||||
import os
|
||||
import time
|
||||
import logging
|
||||
import sys
|
||||
# reload(sys) 和 sys.setdefaultencoding('utf-8') 在 Python 3 中不再需要
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
#======修改以下参数======
|
||||
TmsServerIp='192.168.8.9' #TMS服务器IP,用于绑定服务,等待外部指令
|
||||
TmsPor='10129' #TMS服务器端口,用于绑定服务,等待外部指令
|
||||
upc_dev_ip="192.168.8.125" #自动化控制设备IP
|
||||
upc_dev_port="502" #自动化控制设备端口
|
||||
# 注意:Senderfile 指向的 sender.py 脚本也需要是 Python 3 版本!
|
||||
Senderfile='/opt/upc_resent/bin/sender.py' #发送程序位置
|
||||
Logfile='/opt/upc_resent/log/192.168.8.125.log' #日志文件位置
|
||||
pythonpath="/usr/bin/python3" # Python 3 执行文件的位置,可在操作系统中使用which python3命令获取
|
||||
#========================
|
||||
|
||||
BUFSIZE = 1024
|
||||
|
||||
# 配置日志,只执行一次
|
||||
logging.basicConfig(filename=Logfile,filemode="a", level=logging.DEBUG)
|
||||
ISOTIMEFORMAT='%Y-%m-%d %X'
|
||||
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
try:
|
||||
sock.bind((TmsServerIp, int(TmsPor))) #启动TMS本地服务,等待外部设备发送指令
|
||||
sock.listen(500)
|
||||
except OSError as e: # 在 Python 3 中使用 OSError 替代 socket.error
|
||||
logstr="!!!!!ERROR!!!!!"+time.strftime( ISOTIMEFORMAT, time.localtime( time.time() ) )+" 无法绑定端口 %s:%s - %s" % (TmsServerIp, TmsPor, e)
|
||||
logging.error(logstr)
|
||||
print(logstr) # Python 3 print 函数
|
||||
sys.exit(1) # 绑定失败则退出
|
||||
|
||||
logging.info("服务启动,监听 %s:%s" % (TmsServerIp, TmsPor))
|
||||
|
||||
while True:
|
||||
connection,address = sock.accept()
|
||||
try:
|
||||
connection.settimeout(5) #GDC系统长连接
|
||||
# 接收到的数据是 bytes,需要解码成 str 进行比较
|
||||
buf_bytes = connection.recv(BUFSIZE)
|
||||
buf = buf_bytes.decode('utf-8').strip() # 解码成 str 并移除空白符
|
||||
|
||||
operation = "nodata" # 默认值,如果没有匹配的命令
|
||||
|
||||
datetime_str=time.strftime( ISOTIMEFORMAT, time.localtime( time.time() ) )
|
||||
logstr="==="+datetime_str+"收到客户端"+ address[0]+":"+str(address[1])+"发送的指令: '" +str(buf)+"'"
|
||||
logging.info(logstr)
|
||||
|
||||
# 根据接收到的外部命令,映射到单个内部操作指令
|
||||
if buf == 'open':
|
||||
operation = 'openall4'
|
||||
elif buf == 'close':
|
||||
operation = 'closeall4'
|
||||
elif buf == 'open1':
|
||||
operation = 'open1'
|
||||
elif buf == 'close1':
|
||||
operation = 'close1'
|
||||
elif buf == 'open2':
|
||||
operation = 'open2'
|
||||
elif buf == 'close2':
|
||||
operation = 'close2'
|
||||
elif buf == 'open3':
|
||||
operation = 'open3'
|
||||
elif buf == 'close3':
|
||||
operation = 'close3'
|
||||
elif buf == 'open4':
|
||||
operation = 'open4'
|
||||
elif buf == 'close4':
|
||||
operation = 'close4'
|
||||
elif buf == 'open5': # 新增 5-8 路的命令映射
|
||||
operation = 'open5'
|
||||
elif buf == 'close5':
|
||||
operation = 'close5'
|
||||
elif buf == 'open6':
|
||||
operation = 'open6'
|
||||
elif buf == 'close6':
|
||||
operation = 'close6'
|
||||
elif buf == 'open7':
|
||||
operation = 'open7'
|
||||
elif buf == 'close7':
|
||||
operation = 'close7'
|
||||
elif buf == 'open8':
|
||||
operation = 'open8'
|
||||
elif buf == 'close8':
|
||||
operation = 'close8'
|
||||
elif buf == 'guanggao-guan': # 外部命令 'guanggao-guan' 映射到 'closeall4' (全关)
|
||||
operation = 'closeall4'
|
||||
# else: operation 保持为 "nodata"
|
||||
|
||||
if operation == "nodata":
|
||||
logstr="==="+datetime_str+" 未知指令: '" +str(buf)+"'"
|
||||
logging.warning(logstr)
|
||||
print(logstr) # Python 3 print 函数
|
||||
# 给客户端一个反馈,需要编码成 bytes
|
||||
connection.send(('Unknown command: %s' % buf).encode('utf-8'))
|
||||
else:
|
||||
logstr="==="+datetime_str+" 映射到内部指令: '" +str(operation)+"'"
|
||||
logging.info(logstr)
|
||||
# 直接执行一次外部脚本
|
||||
os_command=str(pythonpath)+" " +Senderfile+ " " + str(upc_dev_ip)+" "+str(upc_dev_port)+" "+str(operation)+" "+str(Logfile)
|
||||
logging.info("执行外部命令: %s" % os_command)
|
||||
os.system(os_command) # 执行发送指令的脚本
|
||||
# 成功处理后给客户端反馈,需要编码成 bytes
|
||||
connection.send(('Command %s processed as %s' % (buf, operation)).encode('utf-8'))
|
||||
except socket.timeout:
|
||||
datetime_str=time.strftime( ISOTIMEFORMAT, time.localtime( time.time() ) )
|
||||
logstr="==="+datetime_str+" 客户端连接超时: "+ address[0]+":"+str(address[1])+"==="
|
||||
logging.warning(logstr)
|
||||
print('time out') # Python 3 print 函数
|
||||
except Exception as e: # 捕获其他可能的异常
|
||||
datetime_str=time.strftime( ISOTIMEFORMAT, time.localtime( time.time() ) )
|
||||
logstr="==="+datetime_str+" 处理客户端 "+ address[0]+":"+str(address[1])+" 请求时发生错误: "+str(e)+"==="
|
||||
logging.error(logstr, exc_info=True) # 记录异常详情
|
||||
print("Error processing request:", e) # Python 3 print 函数
|
||||
# 给客户端一个错误反馈,需要编码成 bytes
|
||||
connection.send(('Error processing command: %s' % str(e)).encode('utf-8'))
|
||||
finally:
|
||||
connection.close() # 确保每次连接都被关闭
|
||||
|
||||
126
bin/192.168.8.73.py
Normal file
126
bin/192.168.8.73.py
Normal file
@@ -0,0 +1,126 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: UTF-8 -*-
|
||||
|
||||
import socket
|
||||
import os
|
||||
import time
|
||||
import logging
|
||||
import sys
|
||||
# reload(sys) 和 sys.setdefaultencoding('utf-8') 在 Python 3 中不再需要
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
#======修改以下参数======
|
||||
TmsServerIp='192.168.8.9' #TMS服务器IP,用于绑定服务,等待外部指令
|
||||
TmsPor='10079' #TMS服务器端口,用于绑定服务,等待外部指令
|
||||
upc_dev_ip="192.168.8.73" #自动化控制设备IP
|
||||
upc_dev_port="502" #自动化控制设备端口
|
||||
# 注意:Senderfile 指向的 sender.py 脚本也需要是 Python 3 版本!
|
||||
Senderfile='/opt/upc_resent/bin/sender.py' #发送程序位置
|
||||
Logfile='/opt/upc_resent/log/192.168.8.73.log' #日志文件位置
|
||||
pythonpath="/usr/bin/python3" # Python 3 执行文件的位置,可在操作系统中使用which python3命令获取
|
||||
#========================
|
||||
|
||||
BUFSIZE = 1024
|
||||
|
||||
# 配置日志,只执行一次
|
||||
logging.basicConfig(filename=Logfile,filemode="a", level=logging.DEBUG)
|
||||
ISOTIMEFORMAT='%Y-%m-%d %X'
|
||||
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
try:
|
||||
sock.bind((TmsServerIp, int(TmsPor))) #启动TMS本地服务,等待外部设备发送指令
|
||||
sock.listen(500)
|
||||
except OSError as e: # 在 Python 3 中使用 OSError 替代 socket.error
|
||||
logstr="!!!!!ERROR!!!!!"+time.strftime( ISOTIMEFORMAT, time.localtime( time.time() ) )+" 无法绑定端口 %s:%s - %s" % (TmsServerIp, TmsPor, e)
|
||||
logging.error(logstr)
|
||||
print(logstr) # Python 3 print 函数
|
||||
sys.exit(1) # 绑定失败则退出
|
||||
|
||||
logging.info("服务启动,监听 %s:%s" % (TmsServerIp, TmsPor))
|
||||
|
||||
while True:
|
||||
connection,address = sock.accept()
|
||||
try:
|
||||
connection.settimeout(5) #GDC系统长连接
|
||||
# 接收到的数据是 bytes,需要解码成 str 进行比较
|
||||
buf_bytes = connection.recv(BUFSIZE)
|
||||
buf = buf_bytes.decode('utf-8').strip() # 解码成 str 并移除空白符
|
||||
|
||||
operation = "nodata" # 默认值,如果没有匹配的命令
|
||||
|
||||
datetime_str=time.strftime( ISOTIMEFORMAT, time.localtime( time.time() ) )
|
||||
logstr="==="+datetime_str+"收到客户端"+ address[0]+":"+str(address[1])+"发送的指令: '" +str(buf)+"'"
|
||||
logging.info(logstr)
|
||||
|
||||
# 根据接收到的外部命令,映射到单个内部操作指令
|
||||
if buf == 'open':
|
||||
operation = 'openall4'
|
||||
elif buf == 'close':
|
||||
operation = 'closeall4'
|
||||
elif buf == 'open1':
|
||||
operation = 'open1'
|
||||
elif buf == 'close1':
|
||||
operation = 'close1'
|
||||
elif buf == 'open2':
|
||||
operation = 'open2'
|
||||
elif buf == 'close2':
|
||||
operation = 'close2'
|
||||
elif buf == 'open3':
|
||||
operation = 'open3'
|
||||
elif buf == 'close3':
|
||||
operation = 'close3'
|
||||
elif buf == 'open4':
|
||||
operation = 'open4'
|
||||
elif buf == 'close4':
|
||||
operation = 'close4'
|
||||
elif buf == 'open5': # 新增 5-8 路的命令映射
|
||||
operation = 'open5'
|
||||
elif buf == 'close5':
|
||||
operation = 'close5'
|
||||
elif buf == 'open6':
|
||||
operation = 'open6'
|
||||
elif buf == 'close6':
|
||||
operation = 'close6'
|
||||
elif buf == 'open7':
|
||||
operation = 'open7'
|
||||
elif buf == 'close7':
|
||||
operation = 'close7'
|
||||
elif buf == 'open8':
|
||||
operation = 'open8'
|
||||
elif buf == 'close8':
|
||||
operation = 'close8'
|
||||
elif buf == 'guanggao-guan': # 外部命令 'guanggao-guan' 映射到 'closeall4' (全关)
|
||||
operation = 'closeall4'
|
||||
# else: operation 保持为 "nodata"
|
||||
|
||||
if operation == "nodata":
|
||||
logstr="==="+datetime_str+" 未知指令: '" +str(buf)+"'"
|
||||
logging.warning(logstr)
|
||||
print(logstr) # Python 3 print 函数
|
||||
# 给客户端一个反馈,需要编码成 bytes
|
||||
connection.send(('Unknown command: %s' % buf).encode('utf-8'))
|
||||
else:
|
||||
logstr="==="+datetime_str+" 映射到内部指令: '" +str(operation)+"'"
|
||||
logging.info(logstr)
|
||||
# 直接执行一次外部脚本
|
||||
os_command=str(pythonpath)+" " +Senderfile+ " " + str(upc_dev_ip)+" "+str(upc_dev_port)+" "+str(operation)+" "+str(Logfile)
|
||||
logging.info("执行外部命令: %s" % os_command)
|
||||
os.system(os_command) # 执行发送指令的脚本
|
||||
# 成功处理后给客户端反馈,需要编码成 bytes
|
||||
connection.send(('Command %s processed as %s' % (buf, operation)).encode('utf-8'))
|
||||
except socket.timeout:
|
||||
datetime_str=time.strftime( ISOTIMEFORMAT, time.localtime( time.time() ) )
|
||||
logstr="==="+datetime_str+" 客户端连接超时: "+ address[0]+":"+str(address[1])+"==="
|
||||
logging.warning(logstr)
|
||||
print('time out') # Python 3 print 函数
|
||||
except Exception as e: # 捕获其他可能的异常
|
||||
datetime_str=time.strftime( ISOTIMEFORMAT, time.localtime( time.time() ) )
|
||||
logstr="==="+datetime_str+" 处理客户端 "+ address[0]+":"+str(address[1])+" 请求时发生错误: "+str(e)+"==="
|
||||
logging.error(logstr, exc_info=True) # 记录异常详情
|
||||
print("Error processing request:", e) # Python 3 print 函数
|
||||
# 给客户端一个错误反馈,需要编码成 bytes
|
||||
connection.send(('Error processing command: %s' % str(e)).encode('utf-8'))
|
||||
finally:
|
||||
connection.close() # 确保每次连接都被关闭
|
||||
|
||||
124
bin/dev1.py
Executable file
124
bin/dev1.py
Executable file
@@ -0,0 +1,124 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: UTF-8 -*-
|
||||
# Auto-generated from template. DO NOT EDIT DIRECTLY!
|
||||
# Device: 设备73-TCP (dev1)
|
||||
|
||||
import socket
|
||||
import os
|
||||
import time
|
||||
import logging
|
||||
import sys
|
||||
|
||||
# ====== 配置参数(从配置文件读取)======
|
||||
TMS_SERVER_IP = '192.168.8.9'
|
||||
TMS_PORT = 10079
|
||||
UPC_DEV_IP = '192.168.8.73'
|
||||
UPC_DEV_PORT = '502'
|
||||
SENDER_FILE = '/home/smart/pythonPJ/upc_resent/bin/sender_tcp.py'
|
||||
LOG_FILE = '/home/smart/pythonPJ/upc_resent/log/dev1.log'
|
||||
PYTHON_PATH = '/usr/bin/python3'
|
||||
DEVICE_ID = 'dev1'
|
||||
# =========================
|
||||
|
||||
BUFSIZE = 1024
|
||||
|
||||
# 配置日志
|
||||
logging.basicConfig(filename=LOG_FILE, filemode="a", level=logging.DEBUG)
|
||||
ISOTIMEFORMAT = '%Y-%m-%d %X'
|
||||
|
||||
# 命令映射表
|
||||
COMMAND_MAPPINGS = {
|
||||
"open": "openall4",
|
||||
"close": "closeall4",
|
||||
"guanggao-guan": "closeall4",
|
||||
"open1": "open1",
|
||||
"close1": "close1",
|
||||
"open2": "open2",
|
||||
"close2": "close2",
|
||||
"open3": "open3",
|
||||
"close3": "close3",
|
||||
"open4": "open4",
|
||||
"close4": "close4",
|
||||
"open5": "open5",
|
||||
"close5": "close5",
|
||||
"open6": "open6",
|
||||
"close6": "close6",
|
||||
"open7": "open7",
|
||||
"close7": "close7",
|
||||
"open8": "open8",
|
||||
"close8": "close8",
|
||||
}
|
||||
|
||||
|
||||
def process_command(buf):
|
||||
"""处理接收到的命令,返回对应的操作指令"""
|
||||
buf = buf.strip()
|
||||
if buf in COMMAND_MAPPINGS:
|
||||
return COMMAND_MAPPINGS[buf]
|
||||
return "nodata"
|
||||
|
||||
|
||||
def main():
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
try:
|
||||
sock.bind((TMS_SERVER_IP, int(TMS_PORT)))
|
||||
sock.listen(500)
|
||||
except OSError as e:
|
||||
logstr = "!!!!!ERROR!!!!!" + time.strftime(ISOTIMEFORMAT, time.localtime(time.time())) + \
|
||||
" 无法绑定端口 %s:%s - %s" % (TMS_SERVER_IP, TMS_PORT, e)
|
||||
logging.error(logstr)
|
||||
print(logstr)
|
||||
sys.exit(1)
|
||||
|
||||
logging.info("服务启动,监听 %s:%s" % (TMS_SERVER_IP, TMS_PORT))
|
||||
print(f"[{DEVICE_ID}] 服务启动,监听 {TMS_SERVER_IP}:{TMS_PORT}")
|
||||
|
||||
while True:
|
||||
connection, address = sock.accept()
|
||||
try:
|
||||
connection.settimeout(5)
|
||||
buf_bytes = connection.recv(BUFSIZE)
|
||||
buf = buf_bytes.decode('utf-8').strip()
|
||||
|
||||
datetime_str = time.strftime(ISOTIMEFORMAT, time.localtime(time.time()))
|
||||
logstr = "===" + datetime_str + " 收到客户端 " + address[0] + ":" + str(address[1]) + \
|
||||
" 发送的指令: '" + str(buf) + "'"
|
||||
logging.info(logstr)
|
||||
print(logstr)
|
||||
|
||||
operation = process_command(buf)
|
||||
|
||||
if operation == "nodata":
|
||||
logstr = "===" + datetime_str + " 未知指令: '" + str(buf) + "'"
|
||||
logging.warning(logstr)
|
||||
print(logstr)
|
||||
connection.send(('Unknown command: %s' % buf).encode('utf-8'))
|
||||
else:
|
||||
logstr = "===" + datetime_str + " 映射到内部指令: '" + str(operation) + "'"
|
||||
logging.info(logstr)
|
||||
print(logstr)
|
||||
|
||||
os_command = str(PYTHON_PATH) + " " + SENDER_FILE + " " + \
|
||||
str(UPC_DEV_IP) + " " + str(UPC_DEV_PORT) + " " + \
|
||||
str(operation) + " " + str(LOG_FILE)
|
||||
logging.info("执行外部命令: %s" % os_command)
|
||||
os.system(os_command)
|
||||
connection.send(('Command %s processed as %s' % (buf, operation)).encode('utf-8'))
|
||||
except socket.timeout:
|
||||
datetime_str = time.strftime(ISOTIMEFORMAT, time.localtime(time.time()))
|
||||
logstr = "===" + datetime_str + " 客户端连接超时: " + address[0] + ":" + str(address[1]) + "==="
|
||||
logging.warning(logstr)
|
||||
print('time out')
|
||||
except Exception as e:
|
||||
datetime_str = time.strftime(ISOTIMEFORMAT, time.localtime(time.time()))
|
||||
logstr = "===" + datetime_str + " 处理客户端 " + address[0] + ":" + str(address[1]) + \
|
||||
" 请求时发生错误: " + str(e) + "==="
|
||||
logging.error(logstr, exc_info=True)
|
||||
print("Error processing request:", e)
|
||||
connection.send(('Error processing command: %s' % str(e)).encode('utf-8'))
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
124
bin/dev2.py
Executable file
124
bin/dev2.py
Executable file
@@ -0,0 +1,124 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: UTF-8 -*-
|
||||
# Auto-generated from template. DO NOT EDIT DIRECTLY!
|
||||
# Device: 设备125-TCP (dev2)
|
||||
|
||||
import socket
|
||||
import os
|
||||
import time
|
||||
import logging
|
||||
import sys
|
||||
|
||||
# ====== 配置参数(从配置文件读取)======
|
||||
TMS_SERVER_IP = '192.168.8.9'
|
||||
TMS_PORT = 10129
|
||||
UPC_DEV_IP = '192.168.8.125'
|
||||
UPC_DEV_PORT = '502'
|
||||
SENDER_FILE = '/home/smart/pythonPJ/upc_resent/bin/sender_tcp.py'
|
||||
LOG_FILE = '/home/smart/pythonPJ/upc_resent/log/dev2.log'
|
||||
PYTHON_PATH = '/usr/bin/python3'
|
||||
DEVICE_ID = 'dev2'
|
||||
# =========================
|
||||
|
||||
BUFSIZE = 1024
|
||||
|
||||
# 配置日志
|
||||
logging.basicConfig(filename=LOG_FILE, filemode="a", level=logging.DEBUG)
|
||||
ISOTIMEFORMAT = '%Y-%m-%d %X'
|
||||
|
||||
# 命令映射表
|
||||
COMMAND_MAPPINGS = {
|
||||
"open": "openall4",
|
||||
"close": "closeall4",
|
||||
"guanggao-guan": "closeall4",
|
||||
"open1": "open1",
|
||||
"close1": "close1",
|
||||
"open2": "open2",
|
||||
"close2": "close2",
|
||||
"open3": "open3",
|
||||
"close3": "close3",
|
||||
"open4": "open4",
|
||||
"close4": "close4",
|
||||
"open5": "open5",
|
||||
"close5": "close5",
|
||||
"open6": "open6",
|
||||
"close6": "close6",
|
||||
"open7": "open7",
|
||||
"close7": "close7",
|
||||
"open8": "open8",
|
||||
"close8": "close8",
|
||||
}
|
||||
|
||||
|
||||
def process_command(buf):
|
||||
"""处理接收到的命令,返回对应的操作指令"""
|
||||
buf = buf.strip()
|
||||
if buf in COMMAND_MAPPINGS:
|
||||
return COMMAND_MAPPINGS[buf]
|
||||
return "nodata"
|
||||
|
||||
|
||||
def main():
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
try:
|
||||
sock.bind((TMS_SERVER_IP, int(TMS_PORT)))
|
||||
sock.listen(500)
|
||||
except OSError as e:
|
||||
logstr = "!!!!!ERROR!!!!!" + time.strftime(ISOTIMEFORMAT, time.localtime(time.time())) + \
|
||||
" 无法绑定端口 %s:%s - %s" % (TMS_SERVER_IP, TMS_PORT, e)
|
||||
logging.error(logstr)
|
||||
print(logstr)
|
||||
sys.exit(1)
|
||||
|
||||
logging.info("服务启动,监听 %s:%s" % (TMS_SERVER_IP, TMS_PORT))
|
||||
print(f"[{DEVICE_ID}] 服务启动,监听 {TMS_SERVER_IP}:{TMS_PORT}")
|
||||
|
||||
while True:
|
||||
connection, address = sock.accept()
|
||||
try:
|
||||
connection.settimeout(5)
|
||||
buf_bytes = connection.recv(BUFSIZE)
|
||||
buf = buf_bytes.decode('utf-8').strip()
|
||||
|
||||
datetime_str = time.strftime(ISOTIMEFORMAT, time.localtime(time.time()))
|
||||
logstr = "===" + datetime_str + " 收到客户端 " + address[0] + ":" + str(address[1]) + \
|
||||
" 发送的指令: '" + str(buf) + "'"
|
||||
logging.info(logstr)
|
||||
print(logstr)
|
||||
|
||||
operation = process_command(buf)
|
||||
|
||||
if operation == "nodata":
|
||||
logstr = "===" + datetime_str + " 未知指令: '" + str(buf) + "'"
|
||||
logging.warning(logstr)
|
||||
print(logstr)
|
||||
connection.send(('Unknown command: %s' % buf).encode('utf-8'))
|
||||
else:
|
||||
logstr = "===" + datetime_str + " 映射到内部指令: '" + str(operation) + "'"
|
||||
logging.info(logstr)
|
||||
print(logstr)
|
||||
|
||||
os_command = str(PYTHON_PATH) + " " + SENDER_FILE + " " + \
|
||||
str(UPC_DEV_IP) + " " + str(UPC_DEV_PORT) + " " + \
|
||||
str(operation) + " " + str(LOG_FILE)
|
||||
logging.info("执行外部命令: %s" % os_command)
|
||||
os.system(os_command)
|
||||
connection.send(('Command %s processed as %s' % (buf, operation)).encode('utf-8'))
|
||||
except socket.timeout:
|
||||
datetime_str = time.strftime(ISOTIMEFORMAT, time.localtime(time.time()))
|
||||
logstr = "===" + datetime_str + " 客户端连接超时: " + address[0] + ":" + str(address[1]) + "==="
|
||||
logging.warning(logstr)
|
||||
print('time out')
|
||||
except Exception as e:
|
||||
datetime_str = time.strftime(ISOTIMEFORMAT, time.localtime(time.time()))
|
||||
logstr = "===" + datetime_str + " 处理客户端 " + address[0] + ":" + str(address[1]) + \
|
||||
" 请求时发生错误: " + str(e) + "==="
|
||||
logging.error(logstr, exc_info=True)
|
||||
print("Error processing request:", e)
|
||||
connection.send(('Error processing command: %s' % str(e)).encode('utf-8'))
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
118
bin/dev3.py
Executable file
118
bin/dev3.py
Executable file
@@ -0,0 +1,118 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: UTF-8 -*-
|
||||
# Auto-generated from template. DO NOT EDIT DIRECTLY!
|
||||
# Device: 设备UDP示例 (dev3) - UDP Protocol
|
||||
|
||||
import socket
|
||||
import os
|
||||
import time
|
||||
import logging
|
||||
import sys
|
||||
|
||||
# ====== 配置参数(从配置文件读取)======
|
||||
TMS_SERVER_IP = '192.168.8.9'
|
||||
TMS_PORT = 10080
|
||||
UPC_DEV_IP = '192.168.8.200'
|
||||
UPC_DEV_PORT = 502
|
||||
SENDER_FILE = '/home/smart/pythonPJ/upc_resent/bin/sender_udp.py'
|
||||
LOG_FILE = '/home/smart/pythonPJ/upc_resent/log/dev3.log'
|
||||
PYTHON_PATH = '/usr/bin/python3'
|
||||
DEVICE_ID = 'dev3'
|
||||
# =========================
|
||||
|
||||
BUFSIZE = 1024
|
||||
|
||||
# 配置日志
|
||||
logging.basicConfig(filename=LOG_FILE, filemode="a", level=logging.DEBUG)
|
||||
ISOTIMEFORMAT = '%Y-%m-%d %X'
|
||||
|
||||
# 命令映射表
|
||||
COMMAND_MAPPINGS = {
|
||||
"open": "openall4",
|
||||
"close": "closeall4",
|
||||
"guanggao-guan": "closeall4",
|
||||
"open1": "open1",
|
||||
"close1": "close1",
|
||||
"open2": "open2",
|
||||
"close2": "close2",
|
||||
"open3": "open3",
|
||||
"close3": "close3",
|
||||
"open4": "open4",
|
||||
"close4": "close4",
|
||||
"open5": "open5",
|
||||
"close5": "close5",
|
||||
"open6": "open6",
|
||||
"close6": "close6",
|
||||
"open7": "open7",
|
||||
"close7": "close7",
|
||||
"open8": "open8",
|
||||
"close8": "close8",
|
||||
}
|
||||
|
||||
|
||||
def process_command(buf):
|
||||
"""处理接收到的命令,返回对应的操作指令"""
|
||||
buf = buf.strip()
|
||||
if buf in COMMAND_MAPPINGS:
|
||||
return COMMAND_MAPPINGS[buf]
|
||||
return "nodata"
|
||||
|
||||
|
||||
def main():
|
||||
# 创建 UDP socket
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
try:
|
||||
sock.bind((TMS_SERVER_IP, int(TMS_PORT)))
|
||||
except OSError as e:
|
||||
logstr = "!!!!!ERROR!!!!!" + time.strftime(ISOTIMEFORMAT, time.localtime(time.time())) + \
|
||||
" 无法绑定UDP端口 %s:%s - %s" % (TMS_SERVER_IP, TMS_PORT, e)
|
||||
logging.error(logstr)
|
||||
print(logstr)
|
||||
sys.exit(1)
|
||||
|
||||
logging.info("UDP服务启动,监听 %s:%s" % (TMS_SERVER_IP, TMS_PORT))
|
||||
print(f"[{DEVICE_ID}] UDP服务启动,监听 {TMS_SERVER_IP}:{TMS_PORT}")
|
||||
|
||||
while True:
|
||||
try:
|
||||
# UDP 使用 recvfrom 接收数据,同时获取客户端地址
|
||||
buf_bytes, client_addr = sock.recvfrom(BUFSIZE)
|
||||
buf = buf_bytes.decode('utf-8').strip()
|
||||
|
||||
datetime_str = time.strftime(ISOTIMEFORMAT, time.localtime(time.time()))
|
||||
logstr = "===" + datetime_str + " 收到UDP客户端 " + client_addr[0] + ":" + str(client_addr[1]) + \
|
||||
" 发送的指令: '" + str(buf) + "'"
|
||||
logging.info(logstr)
|
||||
print(logstr)
|
||||
|
||||
operation = process_command(buf)
|
||||
|
||||
if operation == "nodata":
|
||||
logstr = "===" + datetime_str + " 未知指令: '" + str(buf) + "'"
|
||||
logging.warning(logstr)
|
||||
print(logstr)
|
||||
# 发送UDP响应
|
||||
sock.sendto(('Unknown command: %s' % buf).encode('utf-8'), client_addr)
|
||||
else:
|
||||
logstr = "===" + datetime_str + " 映射到内部指令: '" + str(operation) + "'"
|
||||
logging.info(logstr)
|
||||
print(logstr)
|
||||
|
||||
# 执行发送指令的脚本
|
||||
os_command = str(PYTHON_PATH) + " " + SENDER_FILE + " " + \
|
||||
str(UPC_DEV_IP) + " " + str(UPC_DEV_PORT) + " " + \
|
||||
str(operation) + " " + str(LOG_FILE)
|
||||
logging.info("执行外部命令: %s" % os_command)
|
||||
os.system(os_command)
|
||||
|
||||
# 发送UDP响应
|
||||
sock.sendto(('Command %s processed as %s' % (buf, operation)).encode('utf-8'), client_addr)
|
||||
except Exception as e:
|
||||
datetime_str = time.strftime(ISOTIMEFORMAT, time.localtime(time.time()))
|
||||
logstr = "===" + datetime_str + " 处理UDP请求时发生错误: " + str(e) + "==="
|
||||
logging.error(logstr, exc_info=True)
|
||||
print("Error processing UDP request:", e)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
140
bin/sender.py
Executable file
140
bin/sender.py
Executable file
@@ -0,0 +1,140 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: UTF-8 -*-
|
||||
# Auto-generated from template. DO NOT EDIT DIRECTLY!
|
||||
|
||||
import sys
|
||||
import socket
|
||||
import time
|
||||
import logging
|
||||
import telnetlib
|
||||
|
||||
|
||||
def tcp_command_send(upc_addr, upc_command, data):
|
||||
"""负责发送数据和接收一次响应"""
|
||||
timeout = 2
|
||||
socket.setdefaulttimeout(timeout)
|
||||
try:
|
||||
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
logging.debug(f"尝试连接到 {upc_addr[0]}:{upc_addr[1]}...")
|
||||
client.connect(upc_addr)
|
||||
logging.debug(f"成功连接到 {upc_addr[0]}:{upc_addr[1]}。")
|
||||
|
||||
logging.info(f"正在发送命令 '{upc_command}' 到 {upc_addr}: {data!r} (原始字节)")
|
||||
client.send(data)
|
||||
logging.debug(f"数据发送完成。")
|
||||
|
||||
recv_buffer_size = 1024
|
||||
response_bytes = b''
|
||||
try:
|
||||
logging.debug(f"尝试从 {upc_addr} 接收响应数据...")
|
||||
response_bytes = client.recv(recv_buffer_size)
|
||||
if response_bytes:
|
||||
logging.info(f"从 {upc_addr} 收到原始响应字节: {response_bytes!r}")
|
||||
try:
|
||||
response_str = response_bytes.decode('utf-8', errors='ignore')
|
||||
logging.info(f"从 {upc_addr} 收到解码响应字符串: '{response_str}'")
|
||||
except Exception as decode_e:
|
||||
logging.warning(f"解码从 {upc_addr} 收到的响应时发生错误: {decode_e}")
|
||||
else:
|
||||
logging.info(f"从 {upc_addr} 未收到响应数据 (连接可能已关闭或设备未发送)。")
|
||||
except socket.timeout:
|
||||
logging.warning(f"从 {upc_addr} 接收响应超时。")
|
||||
except OSError as recv_e:
|
||||
logging.error(f"从 {upc_addr} 接收响应时发生网络错误: {recv_e}")
|
||||
|
||||
client.close()
|
||||
logging.debug(f"连接关闭。")
|
||||
return True
|
||||
except OSError as e:
|
||||
logging.error(f"命令 '{upc_command}' 发送至 {upc_addr} 失败: {e}")
|
||||
return False
|
||||
|
||||
|
||||
# 指令定义表(从配置文件读取)
|
||||
COMMAND_DEFINITIONS = {
|
||||
"open1": "000100000008010F006400010001",
|
||||
"close1": "000100000008010F006400010000",
|
||||
"open2": "000100000008010F006500010001",
|
||||
"close2": "000100000008010F006500010000",
|
||||
"open3": "000100000008010F006600010001",
|
||||
"close3": "000100000008010F006600010000",
|
||||
"open4": "000100000008010F006700010001",
|
||||
"close4": "000100000008010F006700010000",
|
||||
"openall4": "000100000008010F00640004000F",
|
||||
"closeall4": "000100000008010F006400040000",
|
||||
"open5": "000100000008010F006800010001",
|
||||
"close5": "000100000008010F006800010000",
|
||||
"open6": "000100000008010F006900010001",
|
||||
"close6": "000100000008010F006900010000",
|
||||
"open7": "000100000008010F006A00010001",
|
||||
"close7": "000100000008010F006A00010000",
|
||||
"open8": "000100000008010F006B00010001",
|
||||
"close8": "000100000008010F006B00010000",
|
||||
"getstat": "fe010000000429C6",
|
||||
"getstat01": "fe010100000429C6",
|
||||
}
|
||||
|
||||
|
||||
def upc_send_command(upc_addr, upc_command, log_file):
|
||||
"""将命令发送给终端设备"""
|
||||
data = None
|
||||
|
||||
# 查找指令定义
|
||||
if upc_command in COMMAND_DEFINITIONS:
|
||||
hex_str = COMMAND_DEFINITIONS[upc_command]
|
||||
data = bytes.fromhex(hex_str)
|
||||
|
||||
if data is None:
|
||||
datetime_str = time.strftime(ISOTIMEFORMAT, time.localtime(time.time()))
|
||||
logstr = f"{datetime_str} 未知命令: {upc_command},没有对应的数据可发送。"
|
||||
logging.warning(logstr)
|
||||
print(logstr)
|
||||
else:
|
||||
i = 1
|
||||
while i <= 3: # 尝试发送3次
|
||||
if tcp_command_send(upc_addr, upc_command, data):
|
||||
datetime_str = time.strftime(ISOTIMEFORMAT, time.localtime(time.time()))
|
||||
logstr = f"{datetime_str} {upc_command}命令第{i}次发送成功"
|
||||
logging.info(logstr)
|
||||
return
|
||||
else:
|
||||
datetime_str = time.strftime(ISOTIMEFORMAT, time.localtime(time.time()))
|
||||
logstr = f"{datetime_str} {upc_command}命令第{i}次发送失败,3秒后进行第{i+1}次尝试"
|
||||
logging.warning(logstr)
|
||||
time.sleep(3)
|
||||
i = i + 1
|
||||
|
||||
datetime_str = time.strftime(ISOTIMEFORMAT, time.localtime(time.time()))
|
||||
logstr = f"{datetime_str} {upc_command}命令在3次尝试后发送均失败!"
|
||||
logging.error(logstr)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
ISOTIMEFORMAT = '%Y-%m-%d %X'
|
||||
|
||||
UPC_DEV_IP = sys.argv[1]
|
||||
UPC_DEV_PORT = sys.argv[2]
|
||||
upc_command = sys.argv[3]
|
||||
LOG_FILE = sys.argv[4]
|
||||
|
||||
logging.basicConfig(filename=LOG_FILE, filemode="a", level=logging.DEBUG)
|
||||
UPC_ADDR = (UPC_DEV_IP, int(UPC_DEV_PORT))
|
||||
|
||||
# 验证端口是否能Telnet通
|
||||
try:
|
||||
logging.debug(f"尝试通过 Telnet 检查端口 {UPC_ADDR[0]}:{UPC_ADDR[1]} 可访问性...")
|
||||
tn = telnetlib.Telnet(UPC_DEV_IP, UPC_DEV_PORT)
|
||||
tn.close()
|
||||
logging.debug(f"端口 {UPC_ADDR[0]}:{UPC_ADDR[1]} Telnet 检查通过。")
|
||||
except OSError as e:
|
||||
datetime_str = time.strftime(ISOTIMEFORMAT, time.localtime(time.time()))
|
||||
logstr = f"!!!!!ERROR!!!!!{datetime_str} {UPC_ADDR} 端口无法访问,请检查设备或网络连接: {e}!!!!!"
|
||||
logging.error(logstr)
|
||||
print(logstr)
|
||||
except Exception as e:
|
||||
datetime_str = time.strftime(ISOTIMEFORMAT, time.localtime(time.time()))
|
||||
logstr = f"!!!!!ERROR!!!!!{datetime_str} {UPC_ADDR} Telnet检查时发生未知错误: {e}!!!!!"
|
||||
logging.error(logstr, exc_info=True)
|
||||
print(logstr)
|
||||
else:
|
||||
upc_send_command(UPC_ADDR, upc_command, LOG_FILE)
|
||||
140
bin/sender_tcp.py
Executable file
140
bin/sender_tcp.py
Executable file
@@ -0,0 +1,140 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: UTF-8 -*-
|
||||
# Auto-generated from template. DO NOT EDIT DIRECTLY!
|
||||
|
||||
import sys
|
||||
import socket
|
||||
import time
|
||||
import logging
|
||||
import telnetlib
|
||||
|
||||
|
||||
def tcp_command_send(upc_addr, upc_command, data):
|
||||
"""负责发送数据和接收一次响应"""
|
||||
timeout = 2
|
||||
socket.setdefaulttimeout(timeout)
|
||||
try:
|
||||
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
logging.debug(f"尝试连接到 {upc_addr[0]}:{upc_addr[1]}...")
|
||||
client.connect(upc_addr)
|
||||
logging.debug(f"成功连接到 {upc_addr[0]}:{upc_addr[1]}。")
|
||||
|
||||
logging.info(f"正在发送命令 '{upc_command}' 到 {upc_addr}: {data!r} (原始字节)")
|
||||
client.send(data)
|
||||
logging.debug(f"数据发送完成。")
|
||||
|
||||
recv_buffer_size = 1024
|
||||
response_bytes = b''
|
||||
try:
|
||||
logging.debug(f"尝试从 {upc_addr} 接收响应数据...")
|
||||
response_bytes = client.recv(recv_buffer_size)
|
||||
if response_bytes:
|
||||
logging.info(f"从 {upc_addr} 收到原始响应字节: {response_bytes!r}")
|
||||
try:
|
||||
response_str = response_bytes.decode('utf-8', errors='ignore')
|
||||
logging.info(f"从 {upc_addr} 收到解码响应字符串: '{response_str}'")
|
||||
except Exception as decode_e:
|
||||
logging.warning(f"解码从 {upc_addr} 收到的响应时发生错误: {decode_e}")
|
||||
else:
|
||||
logging.info(f"从 {upc_addr} 未收到响应数据 (连接可能已关闭或设备未发送)。")
|
||||
except socket.timeout:
|
||||
logging.warning(f"从 {upc_addr} 接收响应超时。")
|
||||
except OSError as recv_e:
|
||||
logging.error(f"从 {upc_addr} 接收响应时发生网络错误: {recv_e}")
|
||||
|
||||
client.close()
|
||||
logging.debug(f"连接关闭。")
|
||||
return True
|
||||
except OSError as e:
|
||||
logging.error(f"命令 '{upc_command}' 发送至 {upc_addr} 失败: {e}")
|
||||
return False
|
||||
|
||||
|
||||
# 指令定义表(从配置文件读取)
|
||||
COMMAND_DEFINITIONS = {
|
||||
"open1": "000100000008010F006400010001",
|
||||
"close1": "000100000008010F006400010000",
|
||||
"open2": "000100000008010F006500010001",
|
||||
"close2": "000100000008010F006500010000",
|
||||
"open3": "000100000008010F006600010001",
|
||||
"close3": "000100000008010F006600010000",
|
||||
"open4": "000100000008010F006700010001",
|
||||
"close4": "000100000008010F006700010000",
|
||||
"openall4": "000100000008010F00640004000F",
|
||||
"closeall4": "000100000008010F006400040000",
|
||||
"open5": "000100000008010F006800010001",
|
||||
"close5": "000100000008010F006800010000",
|
||||
"open6": "000100000008010F006900010001",
|
||||
"close6": "000100000008010F006900010000",
|
||||
"open7": "000100000008010F006A00010001",
|
||||
"close7": "000100000008010F006A00010000",
|
||||
"open8": "000100000008010F006B00010001",
|
||||
"close8": "000100000008010F006B00010000",
|
||||
"getstat": "fe010000000429C6",
|
||||
"getstat01": "fe010100000429C6",
|
||||
}
|
||||
|
||||
|
||||
def upc_send_command(upc_addr, upc_command, log_file):
|
||||
"""将命令发送给终端设备"""
|
||||
data = None
|
||||
|
||||
# 查找指令定义
|
||||
if upc_command in COMMAND_DEFINITIONS:
|
||||
hex_str = COMMAND_DEFINITIONS[upc_command]
|
||||
data = bytes.fromhex(hex_str)
|
||||
|
||||
if data is None:
|
||||
datetime_str = time.strftime(ISOTIMEFORMAT, time.localtime(time.time()))
|
||||
logstr = f"{datetime_str} 未知命令: {upc_command},没有对应的数据可发送。"
|
||||
logging.warning(logstr)
|
||||
print(logstr)
|
||||
else:
|
||||
i = 1
|
||||
while i <= 3: # 尝试发送3次
|
||||
if tcp_command_send(upc_addr, upc_command, data):
|
||||
datetime_str = time.strftime(ISOTIMEFORMAT, time.localtime(time.time()))
|
||||
logstr = f"{datetime_str} {upc_command}命令第{i}次发送成功"
|
||||
logging.info(logstr)
|
||||
return
|
||||
else:
|
||||
datetime_str = time.strftime(ISOTIMEFORMAT, time.localtime(time.time()))
|
||||
logstr = f"{datetime_str} {upc_command}命令第{i}次发送失败,3秒后进行第{i+1}次尝试"
|
||||
logging.warning(logstr)
|
||||
time.sleep(3)
|
||||
i = i + 1
|
||||
|
||||
datetime_str = time.strftime(ISOTIMEFORMAT, time.localtime(time.time()))
|
||||
logstr = f"{datetime_str} {upc_command}命令在3次尝试后发送均失败!"
|
||||
logging.error(logstr)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
ISOTIMEFORMAT = '%Y-%m-%d %X'
|
||||
|
||||
UPC_DEV_IP = sys.argv[1]
|
||||
UPC_DEV_PORT = sys.argv[2]
|
||||
upc_command = sys.argv[3]
|
||||
LOG_FILE = sys.argv[4]
|
||||
|
||||
logging.basicConfig(filename=LOG_FILE, filemode="a", level=logging.DEBUG)
|
||||
UPC_ADDR = (UPC_DEV_IP, int(UPC_DEV_PORT))
|
||||
|
||||
# 验证端口是否能Telnet通
|
||||
try:
|
||||
logging.debug(f"尝试通过 Telnet 检查端口 {UPC_ADDR[0]}:{UPC_ADDR[1]} 可访问性...")
|
||||
tn = telnetlib.Telnet(UPC_DEV_IP, UPC_DEV_PORT)
|
||||
tn.close()
|
||||
logging.debug(f"端口 {UPC_ADDR[0]}:{UPC_ADDR[1]} Telnet 检查通过。")
|
||||
except OSError as e:
|
||||
datetime_str = time.strftime(ISOTIMEFORMAT, time.localtime(time.time()))
|
||||
logstr = f"!!!!!ERROR!!!!!{datetime_str} {UPC_ADDR} 端口无法访问,请检查设备或网络连接: {e}!!!!!"
|
||||
logging.error(logstr)
|
||||
print(logstr)
|
||||
except Exception as e:
|
||||
datetime_str = time.strftime(ISOTIMEFORMAT, time.localtime(time.time()))
|
||||
logstr = f"!!!!!ERROR!!!!!{datetime_str} {UPC_ADDR} Telnet检查时发生未知错误: {e}!!!!!"
|
||||
logging.error(logstr, exc_info=True)
|
||||
print(logstr)
|
||||
else:
|
||||
upc_send_command(UPC_ADDR, upc_command, LOG_FILE)
|
||||
128
bin/sender_udp.py
Executable file
128
bin/sender_udp.py
Executable file
@@ -0,0 +1,128 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: UTF-8 -*-
|
||||
# Auto-generated from template. DO NOT EDIT DIRECTLY!
|
||||
|
||||
import sys
|
||||
import socket
|
||||
import time
|
||||
import logging
|
||||
|
||||
|
||||
def udp_command_send(upc_addr, upc_command, data, timeout=2):
|
||||
"""通过UDP发送数据并接收响应"""
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
sock.settimeout(timeout)
|
||||
|
||||
try:
|
||||
logging.debug(f"尝试发送UDP数据到 {upc_addr[0]}:{upc_addr[1]}...")
|
||||
|
||||
logging.info(f"正在发送UDP命令 '{upc_command}' 到 {upc_addr}: {data!r} (原始字节)")
|
||||
sock.sendto(data, upc_addr)
|
||||
logging.debug(f"UDP数据发送完成。")
|
||||
|
||||
# 尝试接收响应
|
||||
recv_buffer_size = 1024
|
||||
try:
|
||||
logging.debug(f"等待从 {upc_addr} 接收UDP响应...")
|
||||
response_bytes, addr = sock.recvfrom(recv_buffer_size)
|
||||
if response_bytes:
|
||||
logging.info(f"从 {addr} 收到UDP原始响应字节: {response_bytes!r}")
|
||||
try:
|
||||
response_str = response_bytes.decode('utf-8', errors='ignore')
|
||||
logging.info(f"从 {addr} 收到UDP解码响应字符串: '{response_str}'")
|
||||
except Exception as decode_e:
|
||||
logging.warning(f"解码UDP响应时发生错误: {decode_e}")
|
||||
else:
|
||||
logging.info(f"未收到UDP响应数据。")
|
||||
except socket.timeout:
|
||||
logging.warning(f"接收UDP响应超时(设备可能不返回响应,这通常是正常的)。")
|
||||
except OSError as recv_e:
|
||||
logging.error(f"接收UDP响应时发生网络错误: {recv_e}")
|
||||
|
||||
sock.close()
|
||||
logging.debug(f"UDP socket关闭。")
|
||||
return True
|
||||
except OSError as e:
|
||||
logging.error(f"UDP命令 '{upc_command}' 发送至 {upc_addr} 失败: {e}")
|
||||
return False
|
||||
finally:
|
||||
try:
|
||||
sock.close()
|
||||
except:
|
||||
pass
|
||||
|
||||
|
||||
# 指令定义表(从配置文件读取)
|
||||
COMMAND_DEFINITIONS = {
|
||||
"open1": "000100000008010F006400010001",
|
||||
"close1": "000100000008010F006400010000",
|
||||
"open2": "000100000008010F006500010001",
|
||||
"close2": "000100000008010F006500010000",
|
||||
"open3": "000100000008010F006600010001",
|
||||
"close3": "000100000008010F006600010000",
|
||||
"open4": "000100000008010F006700010001",
|
||||
"close4": "000100000008010F006700010000",
|
||||
"openall4": "000100000008010F00640004000F",
|
||||
"closeall4": "000100000008010F006400040000",
|
||||
"open5": "000100000008010F006800010001",
|
||||
"close5": "000100000008010F006800010000",
|
||||
"open6": "000100000008010F006900010001",
|
||||
"close6": "000100000008010F006900010000",
|
||||
"open7": "000100000008010F006A00010001",
|
||||
"close7": "000100000008010F006A00010000",
|
||||
"open8": "000100000008010F006B00010001",
|
||||
"close8": "000100000008010F006B00010000",
|
||||
"getstat": "fe010000000429C6",
|
||||
"getstat01": "fe010100000429C6",
|
||||
}
|
||||
|
||||
|
||||
def upc_send_command(upc_addr, upc_command, log_file):
|
||||
"""将命令发送给终端设备"""
|
||||
data = None
|
||||
|
||||
# 查找指令定义
|
||||
if upc_command in COMMAND_DEFINITIONS:
|
||||
hex_str = COMMAND_DEFINITIONS[upc_command]
|
||||
data = bytes.fromhex(hex_str)
|
||||
|
||||
if data is None:
|
||||
datetime_str = time.strftime(ISOTIMEFORMAT, time.localtime(time.time()))
|
||||
logstr = f"{datetime_str} 未知命令: {upc_command},没有对应的数据可发送。"
|
||||
logging.warning(logstr)
|
||||
print(logstr)
|
||||
else:
|
||||
i = 1
|
||||
while i <= 3: # 尝试发送3次
|
||||
if udp_command_send(upc_addr, upc_command, data):
|
||||
datetime_str = time.strftime(ISOTIMEFORMAT, time.localtime(time.time()))
|
||||
logstr = f"{datetime_str} {upc_command}命令第{i}次发送成功"
|
||||
logging.info(logstr)
|
||||
return
|
||||
else:
|
||||
datetime_str = time.strftime(ISOTIMEFORMAT, time.localtime(time.time()))
|
||||
logstr = f"{datetime_str} {upc_command}命令第{i}次发送失败,3秒后进行第{i+1}次尝试"
|
||||
logging.warning(logstr)
|
||||
time.sleep(3)
|
||||
i = i + 1
|
||||
|
||||
datetime_str = time.strftime(ISOTIMEFORMAT, time.localtime(time.time()))
|
||||
logstr = f"{datetime_str} {upc_command}命令在3次尝试后发送均失败!"
|
||||
logging.error(logstr)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
ISOTIMEFORMAT = '%Y-%m-%d %X'
|
||||
|
||||
UPC_DEV_IP = sys.argv[1]
|
||||
UPC_DEV_PORT = int(sys.argv[2])
|
||||
upc_command = sys.argv[3]
|
||||
LOG_FILE = sys.argv[4]
|
||||
|
||||
logging.basicConfig(filename=LOG_FILE, filemode="a", level=logging.DEBUG)
|
||||
UPC_ADDR = (UPC_DEV_IP, UPC_DEV_PORT)
|
||||
|
||||
# UDP 是无连接的,无需像TCP那样预先检查端口连通性
|
||||
# 直接发送数据
|
||||
logging.info(f"UDP模式:准备发送命令到 {UPC_ADDR}")
|
||||
upc_send_command(UPC_ADDR, upc_command, LOG_FILE)
|
||||
Reference in New Issue
Block a user