66 lines
1.8 KiB
Python
66 lines
1.8 KiB
Python
|
|
import time
|
|||
|
|
import json
|
|||
|
|
from datetime import datetime
|
|||
|
|
|
|||
|
|
recvData = bytearray() #接收的数据存放此数组
|
|||
|
|
startTime = time.time()
|
|||
|
|
|
|||
|
|
# 将bytearray以字为单位转换成16进制字符串,方便显示
|
|||
|
|
def wordData2HexStr(data):
|
|||
|
|
ret = ' '.join(data[i:i+2].hex() for i in range(0, len(data), 2))
|
|||
|
|
return ret.upper()
|
|||
|
|
|
|||
|
|
# 获取当前时间字符串
|
|||
|
|
def nowStr():
|
|||
|
|
now = datetime.now()
|
|||
|
|
ret = now.strftime('%H:%M:%S.') + f"{now.microsecond // 1000:03d}"
|
|||
|
|
return ret
|
|||
|
|
|
|||
|
|
# 启动函数,命令开始会调用此函数
|
|||
|
|
def start():
|
|||
|
|
global tsdb
|
|||
|
|
log_i('----------------- ' + cmdInfo['name'] + ' ----------------')
|
|||
|
|
|
|||
|
|
startTime = time.time() #记录启动时间
|
|||
|
|
|
|||
|
|
recvData = bytearray() #清空接收数组
|
|||
|
|
|
|||
|
|
attr = cmdInfo['attr']
|
|||
|
|
|
|||
|
|
url = attr['url']
|
|||
|
|
rsp_params = attr['rsp_params']
|
|||
|
|
rsp_headers = attr['rsp_headers']
|
|||
|
|
rsp_bodys = attr['rsp_bodys']
|
|||
|
|
type = attr['type']
|
|||
|
|
|
|||
|
|
cmd = {
|
|||
|
|
'url': url,
|
|||
|
|
'type': type,
|
|||
|
|
'rsp_params': rsp_params,
|
|||
|
|
'rsp_headers': rsp_headers,
|
|||
|
|
'rsp_bodys': rsp_bodys
|
|||
|
|
}
|
|||
|
|
cmdStr = json.dumps(cmd)
|
|||
|
|
send(bytearray(cmdStr, encoding='utf-8'))
|
|||
|
|
|
|||
|
|
log_d(f"[{nowStr()}]TX:{cmdStr}")
|
|||
|
|
|
|||
|
|
return True
|
|||
|
|
|
|||
|
|
# 接收数据处理函数,当收到数据会调用此函数
|
|||
|
|
def recvDataHandler(data):
|
|||
|
|
global recvData
|
|||
|
|
global tsdb,_G
|
|||
|
|
recvData = recvData + bytearray(data)
|
|||
|
|
tmpData = bytes(recvData).decode('utf-8')
|
|||
|
|
|
|||
|
|
# 此函数会被重复调用,间隔10毫秒,直到finish()
|
|||
|
|
def loop():
|
|||
|
|
global recvData
|
|||
|
|
if time.time() > startTime + int(cmdInfo['attr']['rsp_timeout']) / 1000.0:
|
|||
|
|
if len(recvData) > 0:
|
|||
|
|
log_w(f"[{nowStr()}]RX timeout:{wordData2HexStr(recvData)}")
|
|||
|
|
else:
|
|||
|
|
log_w(f"[{nowStr()}]RX timeout")
|
|||
|
|
log_e(f"[{devInfo['name']}]{cmdInfo['name']} fail.")
|
|||
|
|
finish()
|