import socket import time from datetime import datetime import os from openpyxl import Workbook import logging # DCA设备的配置信息 dca_ip_address = "192.168.17.15" dca_port = 5001 buffer_size = 1024 # 设置接收缓冲区的大小 # 获取当前日期并格式化为年月日的形式 Date = datetime.today().strftime('%Y-%m-%d') # 拼接桌面路径和年月日文件夹名 desktop_path = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop') folder_path = os.path.join(desktop_path, Date) # 创建文件夹 if not os.path.exists(folder_path): os.makedirs(folder_path) # 创建Excel工作簿 excel_file_name = f'TX眼图数据_{Date}.xlsx' excel_file_path = os.path.join(folder_path, excel_file_name) workbook = Workbook() sheet = workbook['Sheet'] #或者使用 workbook['Sheet1'] 来指定工作表名 # 定义表头 headers = [ "ID", "CH", "AP", "ER", "OMA", "EMM", "Crossing", "Jitter p-p", "Rise_Time", "Fall_time", "Eye_Width", "Eye_Height", "Zero_Level", "One_Level" ] # 初始化行号变量 row_num = 2 # 假设第一行是表头 # 获取默认工作表 #sheet = workbook.active #将表头写入工作表第一行 for col_index,header in enumerate(headers,start=1): cell = sheet.cell(row=1,column=col_index) cell.value = header # 保存Excel文件 workbook.save(excel_file_path) # 建立DCA设备网络连接 def connect_to_dca(): try: sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) print('尝试连接设备') sock.connect((dca_ip_address,dca_port)) print('成功连接设备') return sock #返回创建的socket对象实例 except Exception as e: print(f'无法连接设备:{e}') return None ######################################################################################################################## #设置日志记录 logging.basicConfig(filename='dca_log.log',level=logging.INFO,format='%(asctime)s-%(levelname)s-%(message)s') commands = [ b':FETCh:AMPLitude:AVEPower:DBM:CURRent:CHB?\n', b':FETCh:AMPLitude:EXTRatio:CURRent:CHB?\n', b':FETCh:AMPLitude:OMA:DBM:CURRent:CHB?\n', b':MEASure:MASK:MARGin:CHB?\n', b':FETCh:AMPLitude:CROSsing:CURRent:CHB?\n', b':FETCh:TIME:JITTer:PPeak:CURRent:CHB?\n', b':FETCh:TIME:TRISe:CURRent:CHB?\n', b':FETCh:TIME:FTIMe:CURRent:CHB?\n', b':FETCh:TIME:EYEWidth:CURRent:CHB?\n', b':FETCh:AMPLitude:EYEHeight:CURRent:CHB?\n', b':FETCh:AMPLitude:LEVel:ZERO:CURRent:CHB?\n', b':FETCh:AMPLitude:LEVel:ONE:CURRent:CHB?\n', ] # 创建socket对象 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def send_command_and_read_response(sock, command): try: print(f"发送命令:{command.decode().strip()}") sock.sendall(command) # 发送命令 time.sleep(1) full_response = b'' while True: part = sock.recv(1024) # 读取响应,可能需要多次接收 if not part: break # 如果没有数据接收,则认为响应结束 full_response += part print(f"接收到部分响应:{part.decode().strip()}") response = full_response.decode().strip() print(f'接收到完整响应:{response}') return response # 去除响应字符串两端的空白字符 except Exception as e: print(f'收发错误:{e}') return None # 定义write_to_excel函数 def write_to_excel(responses): # 创建Excel文件和工作表 wb = Workbook() ws = wb.active ws.title = "DCA Data" # 假设每个响应都是一行数据,这里简单地将它们写入不同的单元格 for i, response in enumerate(responses, start=1): ws.cell(row=i, column=1, value=response) print('正在保存文件') #保存文件 wb.save('excel_file_name') print('保存成功') responses = [] try: #连接到设备 sock.connect((dca_ip_address,dca_port)) for command in commands: logging.info(f'Sending command: {command.decode().strip()}') response = send_command_and_read_response(sock,command) #检查是否有响应 if response is None: logging.error(f'Failed to receive response for the command.') else: responses.append(response) # 假设每个命令的响应都是一行数据,包含多个用逗号分隔的值 time.sleep(1) write_to_excel(responses) except Exception as e: print(f"在读取响应时发生错误: {e}") logging.error(f"An error occurred while processing commands: {e}") finally: print('正在关闭socket连接') logging.info('Closing socket connection') #sock.close() # 关闭socket连接 print('已关闭socket连接') logging.info('Socket connection closed') print("无法连接到DCA设备。") logging.error("Unable to connect to DCA device.") #connect_to_dca.close()
代码只发送和接收第一条命令,打印如下,求解答:
发送命令::FETCh:AMPLitude:AVEPower:DBM:CURRent:CHB?
接收到部分响应:-39.78