一.通讯协议格式:
二.通讯协议原始日志
[2024-04-18 14:58:59.659 D] 99 99 0E 00 01 0A 04 00 01 00 00 00 1E FN FN
[2024-04-18 14:58:59.959 D] 99 99 0E 00 01 0C 03 03 01 00 BC FN FN
三.通讯协议原始指令日志Python脚本分析(仅解析指令的PC版和CMD部分)
#!/usr/bin/python3
class File:
#分析log路径
__path='PC_log.log'
__data=[]
#指令中【电路板】集合
__PC_dict = {'电路板':{'Board0': '00','Board1': '01','Board2': '02','Board3':'03'}
}
#指令中【CMD】集合
__CMD_dict={
'读取':{'状态查询':'0800','版本号':'0820'},
'写入':{'写入(直接)':'03','写入(间接)':'83'},
'动作指令': {'单电机动作': '0400', '组合动作':'0500'},
'复位指令': {'模块普通复位':'0303', '模块快速复位': '0302'}
}
def analysis_log(self):
'''
analysis_log():定义打开分析日志文件及获取分析结果
'''
try:
with open(File.__path, 'r', encoding='utf-8', errors='ignore') as f:
for line in f:
# 截取日期
Date_time=line.split('D')[0]+'D] '
#【协议头】
HD_order='9999'
#协议未
ED_order='FEFE'
#截取长度
LEN_order=line.replace(' ', '').split('9999')[-1][0:4]
#截取【PC版号】
PC_order = line.replace(' ', '').split('9999')[-1][4:6]
#截取【电机号】
MOTOR_order = line.replace(' ', '').split('9999')[-1][6:8]
#截取【CMD]
CMD_order = line.replace(' ', '').split('9999')[-1][8:12]
#截取【数据】
DATA_order = line.replace(' ', '').split('9999')[-1][12:-6]
#截取校验位
CRC_order=line.replace(' ', '').split('9999')[-1][-6:-4]
NEW_order=(Date_time+HD_order+LEN_order+' '+PC_order+' '+MOTOR_order+' '+CMD_order+' '+DATA_order+
' '+CRC_order+ED_order+'------'+File.pc_analyze(self,PC_order)[0]+' --- '+File.cmd_analyze(self,CMD_order)[0]+'指令')
File.__data.append(NEW_order)
return File.save_to_file(self,File.__data)
except Exception as ex:
print(ex)
def save_to_file(self,arr):
'''
save_to_file():定义日志解析后内容保存至文件中
'''
try:
with open('解析日志.txt', 'w') as file:
for row in arr:
line = ' '.join(str(element) for element in row)
file.write(line + '\n')
except Exception as ex:
print(ex)
def find_keys_by_value(self,order_dict,value):
'''
find_keys_by_value:定义根据字典值查找关键字
return:返回关键字
'''
keys_found = []
for key1 in order_dict:
if isinstance(order_dict[key1], dict):
for key2 in order_dict[key1]:
if order_dict[key1][key2] == value:
keys_found.append((key1+'->'+key2))
else:
if order_dict[key1] == value:
keys_found.append(key1)
return keys_found
def pc_analyze(self,value):
'''
pc_analyze():定义指令中pc查询
'''
try:
JH=File.find_keys_by_value(self,File.__PC_dict, value)
return JH
except Exception as ex:
print(ex)
def cmd_analyze(self,value):
'''
cmd_analyze():定义指令中CMD查询
'''
try:
CMD=File.find_keys_by_value(self,File.__CMD_dict, value)
return CMD
except Exception as ex:
print(ex)
f=File()
if __name__ == "__main__":
# arg1='[2024-04-18 14:58:59.659 D] 99 99 0E 00 01 0A 04 00 01 00 00 00 1E FN FN'
# arg2='[2024-04-18 14:58:59.959 D] 99 99 0E 00 01 0C 03 03 01 00 BC FN FN'
print('第86行:',f.analysis_log())
解析日志内容保存至文件中,文件内容如下: