Commit 0fad8f99 authored by 方开's avatar 方开 🍔
Browse files

设置日志级别和增加测试日志

parent 57ccd177
......@@ -68,7 +68,7 @@ class GetCmds(object):
if subId in subData.keys():
return subData
else:
pass
return None
def getExterCmd(self):
exterCmd = specialCmdData.get("extertemphumi")
......
......@@ -8,25 +8,7 @@ measurePath = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "../../log/measure.log")
# 配置logging信息
def mainlogging():
log = logging.getLogger('')
log.setLevel(logging.DEBUG)
formatter = logging.Formatter(
"%(asctime)s - %(module)s.%(funcName)s.%(lineno)d - %(levelname)s - %(message)s")
log_file_handler = TimedRotatingFileHandler(
filename=mainPath, when="D", interval=1, encoding="utf-8")
log_file_handler.setFormatter(formatter)
log_file_handler.setLevel(logging.DEBUG)
log.addHandler(log_file_handler)
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(formatter)
log.addHandler(stream_handler)
return log
# 定时测量的logging
# logging
def measurelogging():
log = logging.getLogger('')
log.setLevel(logging.DEBUG)
......@@ -41,5 +23,6 @@ def measurelogging():
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(formatter)
stream_handler.setLevel(logging.INFO)
log.addHandler(stream_handler)
return log
......@@ -32,6 +32,7 @@ def checkData(data: bytes, houseType: str, measureType: str, pointnum):
# 如果是测温数据的话
if flag == "a1" or measureType == "temp":
tempData = data[14:]
logging.debug(f"温度原始数据为{tempData}")
realTemp = []
# 温度换算,异常坏点数据取 None 值
for i in range(0, len(tempData), 4):
......@@ -47,6 +48,7 @@ def checkData(data: bytes, houseType: str, measureType: str, pointnum):
elif flag == "a2":
tempData = data[14:18]
humiData = data[18:22]
logging.debug(f"温湿度原始数据为{tempData}-{humiData}")
# 温湿度换算
realTempValue = int(tempData, 16) / 10
realHumiValue = int(humiData, 16) / 10
......@@ -57,6 +59,7 @@ def checkData(data: bytes, houseType: str, measureType: str, pointnum):
elif flag == "aa":
# 虫害数据全部返回,分为多路多组数据
bugData = data.split("1f00000044")[1:]
logging.debug(f"虫害原始数据为{bugData}")
# 针对每组数据分别存放数据
bugValues = []
for bug1 in bugData:
......@@ -70,6 +73,7 @@ def checkData(data: bytes, houseType: str, measureType: str, pointnum):
# 气体数据 磷化氢、氧气、二氧化碳
elif flag in ["a6", "a7", "a8"]:
airData = data.split("1f00000044")[1:]
logging.debug(f"气体原始数据为{airData}")
ph2List, o2List, co2List = [], [], []
for i in airData:
if "a6" in i:
......@@ -104,6 +108,7 @@ def checkData(data: bytes, houseType: str, measureType: str, pointnum):
# 气象站
elif measureType == "weather":
weatherData = data[12:]
logging.debug(f"气象站原始数据为{tempData}")
# 分别解析相应的数据
airpeedData = hex2Int(weatherData[:4], times=10)
rainFallData = hex2Int(weatherData[4:8], times=5)
......@@ -128,9 +133,11 @@ def checkData(data: bytes, houseType: str, measureType: str, pointnum):
# 温度数据的crc位和待校验的数据
crcValue = data[-4:]
tempData = data[:-4]
logging.debug(f"温度原始数据为{tempData},crc校验值为{crcValue}")
# 经过crc16校验看数据是否一致
if crcValue == crc16s(tempData):
tempData = data[14:-4]
logging.debug(f"通过crc校验,温度原始数据为{tempData}")
realTemp = []
# 对温度数据进行解析处理,坏点补上 None 值
for i in range(0, len(tempData), 4):
......@@ -139,6 +146,7 @@ def checkData(data: bytes, houseType: str, measureType: str, pointnum):
realTemp.append(tempValue)
else:
realTemp.append(None)
logging.info(f"温度实际数据为{realTemp}")
return realTemp
else:
logging.warning(f"crc 检验失败,数据不正确!")
......@@ -149,14 +157,17 @@ def checkData(data: bytes, houseType: str, measureType: str, pointnum):
# 温度数据的crc位和待校验的数据
crcValue = data[-4:]
tempHumiData = data[:-4]
logging.debug(f"温湿度原始数据为{tempHumiData},crc校验值为{crcValue}")
# 经过crc16校验看数据是否一致
if crcValue == crc16s(tempHumiData):
logging.debug(f"通过crc校验")
# 分别取出温度和湿度数据
tempData = data[14:18]
humiData = data[18:22]
tempValue = int(tempData[1:4], 16) * 0.0625
humiValue = int(humiData[1:4], 16) / 10
realTempHumi = [tempValue, humiValue]
logging.info(f"实际温湿度值为{realTempHumi}")
return realTempHumi
else:
......@@ -199,6 +210,7 @@ def measureit(houseId, measureType="all", timeout=2):
gc = GetCmds(houseId)
houseType = gc.houseType
subIds = gc.getSubIdByType(measureType)
logging.debug(f"测试类型为{measureType},分机id为{subIds},测量超时为{timeout}")
logging.info(f"正处理测试类型为: {measureType}--{subIds}命令")
# 针对不同测试类型设置不同策略
if measureType == "temp":
......@@ -206,6 +218,7 @@ def measureit(houseId, measureType="all", timeout=2):
for subId in subIds:
# 如果命令列表数据不为空
addr, cmds, pointNums = gc.getCmdsBySubId(subId)
logging.debug(f"温度分机地址为{addr},对应命令为{cmds},点数为{pointNums}")
if cmds:
for index, cmd in enumerate(cmds):
# 根据每个通道的点数去截取数据
......@@ -219,9 +232,11 @@ def measureit(houseId, measureType="all", timeout=2):
if dataLen < int(pointNum):
needLen = int(pointNum) - dataLen
data.extend([None]*needLen)
logging.debug(f"测温数据实际长度小于给定长度,补上{needLen}个None")
elif dataLen > int(pointNum):
data = data[:int(pointNum)]
logging.debug(f"测温数据实际长度大于给定长度,截取之")
else:
pass
......@@ -238,6 +253,7 @@ def measureit(houseId, measureType="all", timeout=2):
for subId in subIds:
# 如果命令列表数据不为空
addr, cmds, pointNum = gc.getCmdsBySubId(subId)
logging.debug(f"温湿度分机地址为{addr},对应命令为{cmds},点数为{pointNums}")
if cmds:
# 分别存放外温外湿、内温内湿
for cmd in cmds:
......@@ -245,8 +261,10 @@ def measureit(houseId, measureType="all", timeout=2):
data = measureClient(addr, a2b_hex(
cmd), measureType, houseType, pointNum, timeout)
interList.extend(data)
logging.debug(f"内部温湿度数据为{interList}")
# 单独测试一次外温外湿
exterCmdData = gc.getExterCmd()
logging.debug(f"外温外湿命令为{exterCmdData}")
if exterCmdData != None:
addr = exterCmdData[0]
exterCmd = exterCmdData[1]
......@@ -262,6 +280,7 @@ def measureit(houseId, measureType="all", timeout=2):
subId = subIds[0]
# 如果命令列表数据不为空
addr, cmds, pointNum = gc.getCmdsBySubId(subId)
logging.debug(f"虫害分机地址为{addr},对应命令为{cmds},点数为{pointNums}")
dataList = []
# 测试指令和复位指令
if cmds:
......@@ -272,6 +291,7 @@ def measureit(houseId, measureType="all", timeout=2):
dataList.extend(data)
# 发送复位指令
resetCmd = cmds[1]
logging.debug(f"复位指令为{resetCmd}")
try:
tcpSocket = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
......@@ -288,6 +308,8 @@ def measureit(houseId, measureType="all", timeout=2):
subId = subIds[0]
# 如果命令列表数据不为空
addr, cmds, pointNum = gc.getCmdsBySubId(subId)
logging.debug(
f"{measureType}分机地址为{addr},对应命令为{cmds},点数为{pointNums}")
dataList = []
if cmds:
# 只有单条命令
......@@ -304,6 +326,8 @@ def measureit(houseId, measureType="all", timeout=2):
addr, cmds, pointNum = gc.getCmdsBySubId(subId)
subInfo = gc.getSubInfo(subId)
cerealsSpecies = subInfo.get("cerealsSpecies")
logging.debug(
f"水份分机地址为{addr},对应命令为{cmds},点数为{pointNums},分机信息为{subInfo},谷物类型为{cerealsSpecies}")
if cmds:
# 单条指令
cmd = cmds[0]
......@@ -344,9 +368,11 @@ def controlit(houseId, measureType="wind", flag="on", timeout=3):
gc = GetCmds(houseId)
houseType = gc.houseType
SubId = gc.getSubIdByType(measureType)
logging.debug(f"仓房类型为{houseType},分机id为:{SubId}")
result = []
for subid in SubId:
addr, cmds = gc.getCmdsByFlag(subid, flag)
logging.debug(f"分机地址为{addr},指令为{cmds}")
# 如果获取到指定的命令
if cmds:
for cmd in cmds:
......@@ -375,6 +401,8 @@ def handleCommand(command: str):
houseId = cmd.get("id")
measureCmd = cmd.get("measure")
controlCmd = cmd.get("control")
logging.debug(
f"houseid:{houseId},measureCmd:{measureCmd},controlCmd:{controlCmd}")
if houseId:
dicts = {}
dicts["id"] = houseId
......@@ -383,6 +411,7 @@ def handleCommand(command: str):
alldict = {}
try:
for tp in measureCmd:
logging.debug(f"测试类型为{tp}")
# 气体虫害测试超时为60秒
if tp in ["air", "bug"]:
timeout = 50
......@@ -399,6 +428,8 @@ def handleCommand(command: str):
subid = gc.getSubIdByType("water")
cerealsSpecies = gc.getSubInfo(
subid[0]).get("cerealsSpecies")
logging.debug(
f"测试类型为{tp},subid:{subid},谷物类型为:{cerealsSpecies}")
alldict["water"] = [
{"species": cerealsSpecies, "data": data}]
......@@ -408,29 +439,37 @@ def handleCommand(command: str):
else:
pass
logging.info("已测试完所有指令数据")
dicts["measured"] = alldict
logging.debug(f"所有的测试结果数据为{dicts}")
sendData = json.dumps(dicts)
return sendData
except Exception as f:
logging.info(f"error:{f}")
logging.info(f"判定指令类型发生错误:{f}")
sendData = None
# 如果是控制命令
elif controlCmd != None:
logging.info(controlCmd)
logging.info(f"控制指令为:{controlCmd}")
controlList = []
try:
for tp in controlCmd:
logging.debug(f"控制类型为{tp}")
data = controlit(
houseId, tp, flag=controlCmd[tp], timeout=3)
logging.debug(f"控制数据为{data}")
controlList.append({"species": tp, "data": data})
dicts["controled"] = controlList
logging.debug(f"所有控制结果数据为{dicts}")
sendData = json.dumps(dicts)
except Exception as g:
logging.info(f"指令error:{g}")
logging.info(f"控制指令错误:{g}")
sendData = None
else:
logging.debug(f"指令类型未知")
sendData = None
else:
logging.debug(f"未找到仓库id:{houseId}")
sendData = None
return sendData
......@@ -447,26 +486,26 @@ def recv(tcpSocket):
break
logging.info(f"接收到服务器数据: {data}")
if "ff" in data and len(data) < 10:
logging.info("接收心跳包成功")
logging.info("接收心跳响应成功")
elif "measure" in data or "control" in data:
logging.info("正在处理测试或控制指令")
# 命令处理后发送给服务器
result = handleCommand(data)
if result == None:
logging.info("解析指令和返回数据失败")
pass
else:
sendData = result + "eeffeeff"
logging.info(f"发送给服务器的数据为{sendData}")
tcpSocket.send(sendData.encode())
logging.info("发送给服务器数据完毕")
else:
logging.info("不明指令")
pass
logging.info("不明指令,忽略")
except Exception as e:
logging.info(f"接收error:{e}")
logging.info(f"接收服务器发来的数据异常,详细错误为:{e}")
returnData = json.dumps({"code": "0"}, ensure_ascii=False) + "eeffeeff"
tcpSocket.send(returnData.encode())
finally:
pass
# 定时发送心跳信息
......@@ -485,12 +524,13 @@ def TCPClient():
try:
tcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpSocket.connect(sendAddr)
logging.info(f"正在连接:{sendAddr}")
gevent.joinall([
gevent.spawn(recv, tcpSocket),
gevent.spawn(heartBeat, tcpSocket)
])
except Exception as e:
logging.info(f"连接error:{e},retrying....")
logging.warn(f"连接发生错误:{e},30秒后再次尝试连接....")
time.sleep(30)
# 30秒重新连接服务器
continue
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment