Commit 5903a330 authored by liyuanhong's avatar liyuanhong

增加了数据不发送,保存到文件的功能,以及增加了GPS和obd数据转换为大包脚本

parent d54f9b19
# coding: utf-8
import binascii
import socket
#####################################################
# 数字转换为16进制字符串
#####################################################
def int2hexString(num):
hexStr = hex(num)[2:]
if (len(hexStr) % 2) == 1:
hexStr = "0" + hexStr
return hexStr
#####################################################
# 数字转换为16进制字符串,通过传入字节数可自动补0
# 传入数据格式所占字节数
#####################################################
def int2hexStringByBytes(num, bytescount=1):
hexStr = hex(num)[2:]
while len(hexStr) < (bytescount * 2):
hexStr = "0" + hexStr
return hexStr
#####################################################
# 设备id转换为16进制字符串
#####################################################
def devid2hexString(id):
# 获取第一个字符的ASCII值
ascii = ord(id[0:1])
# 将10进制的ASCII值转换为16进制
ascii = int2hexString(int(ascii))
devid = str(ascii) + id[1:]
return devid
#####################################################
# 定义生成校验字段的函数
# inputStr:需要传入一个已经转换为16进制的字符串
#####################################################
# add crc 16 check at the end of the string
def crc16(inputStr):
inputStrByte = bytes.fromhex(inputStr)
crc = 0xFFFF
for i in range(0, len(inputStrByte)):
for j in range(0, 8):
c15 = (crc >> 15) == 1
bit = ((inputStrByte[i] >> (7 - j)) & 1) == 1
crc <<= 1
crc &= 0xFFFF
if c15 ^ bit:
crc ^= 0x1021
crc = str(hex(crc))
crc = leftPad(crc[2:], 4)
# outputStr = inputStr + crc
outputStr = crc
return outputStr
# pad zero to the left of the string if not long enough
def leftPad(inputStr, strLen):
if (strLen > len(inputStr)):
outputStr = "0000000000000000000000000000000000000000" + inputStr
outputStr = outputStr[len(outputStr) - strLen:]
return outputStr
else:
return inputStr
# pad zero to the right of the string if not long enough
def rightPad(inputStr, strLen):
if (strLen > len(inputStr)):
outputStr = inputStr + "0000000000000000000000000000000000000000"
outputStr = outputStr[: strLen]
return outputStr
else:
return inputStr
##############################################################################
def getEventPkg():
with open("event.txt", "r", encoding="utf-8") as fi:
content = fi.readlines()
pkg = ""
msgs = []
pkgCounts = 0
for i in content:
onePkg = i[21:].replace("\n", "")
onePkg = onePkg[30:][:-4]
onePkg = onePkg[2:]
pkg = pkg + onePkg
pkgCounts = pkgCounts + 1
if len(pkg) > 2000:
pkgCounts = int2hexStringByBytes(pkgCounts)
HEADER = "4040"
WATER_CODE = int2hexStringByBytes(1, 2)
DEV_ID = devid2hexString("M202003060520")
FUN_ID = "0021"
LENGTH = int2hexStringByBytes(int(len(WATER_CODE + DEV_ID + FUN_ID + pkgCounts + pkg) / 2), 2)
CHECK_CODE = crc16(HEADER + LENGTH + WATER_CODE + DEV_ID + FUN_ID + pkgCounts + pkg)
msg = HEADER + LENGTH + WATER_CODE + DEV_ID + FUN_ID + pkgCounts + pkg + CHECK_CODE
msgs.append(msg)
pkg = ""
pkgCounts = 0
pkgCounts = int2hexStringByBytes(pkgCounts)
HEADER = "4040"
WATER_CODE = int2hexStringByBytes(1, 2)
DEV_ID = devid2hexString("M202003060520")
FUN_ID = "0021"
LENGTH = int2hexStringByBytes(int(len(WATER_CODE + DEV_ID + FUN_ID + pkgCounts + pkg) / 2), 2)
CHECK_CODE = crc16(HEADER + LENGTH + WATER_CODE + DEV_ID + FUN_ID + pkgCounts + pkg)
msg = HEADER + LENGTH + WATER_CODE + DEV_ID + FUN_ID + pkgCounts + pkg + CHECK_CODE
msgs.append(msg)
with open("event_big.txt", "w", encoding="utf-8") as fi2:
for txt in msgs:
fi2.write(txt + "\n")
return msgs
def getGpsPkg():
with open("gps.txt", "r", encoding="utf-8") as fi:
content = fi.readlines()
pkg = ""
msgs = []
pkgCounts = 0
for i in content:
onePkg = i[21:].replace("\n", "")
onePkg = onePkg[30:][:-4]
onePkg = onePkg[2:]
pkg = pkg + onePkg
pkgCounts = pkgCounts + 1
if len(pkg) > 2000:
pkgCounts = int2hexStringByBytes(pkgCounts)
HEADER = "4040"
WATER_CODE = int2hexStringByBytes(1, 2)
DEV_ID = devid2hexString("M202003060520")
FUN_ID = "0010"
LENGTH = int2hexStringByBytes(int(len(WATER_CODE + DEV_ID + FUN_ID + pkgCounts + pkg) / 2), 2)
CHECK_CODE = crc16(HEADER + LENGTH + WATER_CODE + DEV_ID + FUN_ID + pkgCounts + pkg)
msg = HEADER + LENGTH + WATER_CODE + DEV_ID + FUN_ID + pkgCounts + pkg + CHECK_CODE
msgs.append(msg)
pkg = ""
pkgCounts = 0
pkgCounts = int2hexStringByBytes(pkgCounts)
HEADER = "4040"
WATER_CODE = int2hexStringByBytes(1, 2)
DEV_ID = devid2hexString("M202003060520")
FUN_ID = "0010"
LENGTH = int2hexStringByBytes(int(len(WATER_CODE + DEV_ID + FUN_ID + pkgCounts + pkg) / 2), 2)
CHECK_CODE = crc16(HEADER + LENGTH + WATER_CODE + DEV_ID + FUN_ID + pkgCounts + pkg)
msg = HEADER + LENGTH + WATER_CODE + DEV_ID + FUN_ID + pkgCounts + pkg + CHECK_CODE
msgs.append(msg)
with open("gps_big.txt", "w", encoding="utf-8") as fi2:
for txt in msgs:
fi2.write(txt + "\n")
return msgs
def getObdPkg():
with open("obd.txt", "r", encoding="utf-8") as fi:
content = fi.readlines()
pkg = ""
msgs = []
pkgCounts = 0
for i in content:
onePkg = i[21:].replace("\n", "")
onePkg = onePkg[30:][:-4]
onePkg = onePkg[2:]
print(onePkg)
pkg = pkg + onePkg
pkgCounts = pkgCounts + 1
if len(pkg) > 2000:
pkgCounts = int2hexStringByBytes(pkgCounts)
HEADER = "4040"
WATER_CODE = int2hexStringByBytes(1, 2)
DEV_ID = devid2hexString("M202003060520")
FUN_ID = "0012"
LENGTH = int2hexStringByBytes(int(len(WATER_CODE + DEV_ID + FUN_ID + pkgCounts + pkg) / 2), 2)
CHECK_CODE = crc16(HEADER + LENGTH + WATER_CODE + DEV_ID + FUN_ID + pkgCounts + pkg)
msg = HEADER + LENGTH + WATER_CODE + DEV_ID + FUN_ID + pkgCounts + pkg + CHECK_CODE
msgs.append(msg)
pkg = ""
pkgCounts = 0
pkgCounts = int2hexStringByBytes(pkgCounts)
HEADER = "4040"
WATER_CODE = int2hexStringByBytes(1, 2)
DEV_ID = devid2hexString("M202003060520")
FUN_ID = "0012"
LENGTH = int2hexStringByBytes(int(len(WATER_CODE + DEV_ID + FUN_ID + pkgCounts + pkg) / 2), 2)
CHECK_CODE = crc16(HEADER + LENGTH + WATER_CODE + DEV_ID + FUN_ID + pkgCounts + pkg)
msg = HEADER + LENGTH + WATER_CODE + DEV_ID + FUN_ID + pkgCounts + pkg + CHECK_CODE
msgs.append(msg)
with open("obd_big.txt", "w", encoding="utf-8") as fi2:
for txt in msgs:
fi2.write(txt + "\n")
return msgs
def getLenOfFile():
with open("event_big.txt", "r", encoding="utf-8") as fi:
data = fi.readline()
print(len(data))
def sendMsg(msgs):
host = "10.100.12.32"
port = 9008
BUF_SIZE = 1024
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.settimeout(2)
client.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) # 在客户端开启心跳
client.connect((host, port))
for msg in msgs:
print(msg)
msg = msg.replace("\n", "")
client.send(binascii.a2b_hex(msg))
data = client.recv(BUF_SIZE)
print(data)
print(binascii.b2a_hex(data))
client.close()
if __name__ == "__main__":
# msg = getEventPkg()
# msg = getGpsPkg()
msg = getObdPkg()
sendMsg(msg)
# getLenOfFile()
...@@ -261,6 +261,8 @@ class EventReport_protocol(ProtocolBase): ...@@ -261,6 +261,8 @@ class EventReport_protocol(ProtocolBase):
int(eventData["0022"]["direction"]), int(eventData["0022"]["direction"]),
int(eventData["0022"]["dataProperty"])) int(eventData["0022"]["dataProperty"]))
data = data + "0022" + self.int2hexStringByBytes(int((len(theData) / 2)), 2) + theData data = data + "0022" + self.int2hexStringByBytes(int((len(theData) / 2)), 2) + theData
if ("0023" in eventData.keys()): #碰撞告警
pass
if ("0036" in eventData.keys()): #低档高速报警 if ("0036" in eventData.keys()): #低档高速报警
eventObj = EventClass() eventObj = EventClass()
theData = eventObj.lowGearHighSpeedAlarm(int(eventData["0036"]["alarmType"]),int(eventData["0036"]["durationTime"])) theData = eventObj.lowGearHighSpeedAlarm(int(eventData["0036"]["alarmType"]),int(eventData["0036"]["durationTime"]))
......
...@@ -218,12 +218,12 @@ class OBDReport_CAN_protocol(ProtocolBase): ...@@ -218,12 +218,12 @@ class OBDReport_CAN_protocol(ProtocolBase):
torquePercentage = self.getTorquePercentageHex(self.torquePercentage) torquePercentage = self.getTorquePercentageHex(self.torquePercentage)
#档位(仅商用车) #档位(仅商用车)
gearsLocation = self.getGearsLocationHex(self.gearsLocation) gearsLocation = self.getGearsLocationHex(self.gearsLocation)
#GPS车速 # #GPS车速
GPSSpeed = self.getGPSSpeedHex(self.GPSSpeed) # GPSSpeed = self.getGPSSpeedHex(self.GPSSpeed)
#GPS里程 # #GPS里程
GPSMileage = self.getGPSMileageHex(self.GPSMileage) # GPSMileage = self.getGPSMileageHex(self.GPSMileage)
#预留字段 # #预留字段
retain = self.getRetainHex() # retain = self.getRetainHex()
data = data + infoTime + dataFlowCode + protocolType + fireStatus + ACCStatus + voltage + troubleLightStatus data = data + infoTime + dataFlowCode + protocolType + fireStatus + ACCStatus + voltage + troubleLightStatus
data = data + toubleCodeCount + engineSpeed + speed + meterMileage + mileageStatisticsStyle + totalMileage data = data + toubleCodeCount + engineSpeed + speed + meterMileage + mileageStatisticsStyle + totalMileage
data = data + troubleMileage + totalOilExpend + surplusOil + totalRunTime + totalEngineTime + airIntoAisleTemperture data = data + troubleMileage + totalOilExpend + surplusOil + totalRunTime + totalEngineTime + airIntoAisleTemperture
...@@ -231,7 +231,7 @@ class OBDReport_CAN_protocol(ProtocolBase): ...@@ -231,7 +231,7 @@ class OBDReport_CAN_protocol(ProtocolBase):
data = data + valveLocationSensor + acceleratorLocation + engineLoad + fuelTrim + fireAngle data = data + valveLocationSensor + acceleratorLocation + engineLoad + fuelTrim + fireAngle
data = data + B1S1oxygenSensorVoltage + B1S2oxygenSensorVoltage + B1S1oxygenSensorElectricity + B1S2oxygenSensorElectricity data = data + B1S1oxygenSensorVoltage + B1S2oxygenSensorVoltage + B1S1oxygenSensorElectricity + B1S2oxygenSensorElectricity
data = data + momentOilExpend + meterOilExpend + engineAbsoluteLoad + steeringWheelAngle + torquePercentage data = data + momentOilExpend + meterOilExpend + engineAbsoluteLoad + steeringWheelAngle + torquePercentage
data = data + gearsLocation + GPSSpeed + GPSMileage + retain data = data + gearsLocation # + GPSSpeed + GPSMileage + retain
return data return data
......
...@@ -35,7 +35,7 @@ port = 9008 ...@@ -35,7 +35,7 @@ port = 9008
# msg = GPSReport_protocol().generateGpsMsg() #GPS消息数据 # msg = GPSReport_protocol().generateGpsMsg() #GPS消息数据
# msg = OBDReport_protocol().generateOBDReportMsg() #OBD终端上报数据 # msg = OBDReport_protocol().generateOBDReportMsg() #OBD终端上报数据
# msg = OBDReport_CAN_protocol().generateOBDReportCANMsg() #OBD终端上报CAN数据 msg = OBDReport_CAN_protocol().generateOBDReportCANMsg() #OBD终端上报CAN数据
# msg = HeartBeatReport_protocol().generateHeartBeatMsg() #终端上报心跳协议 # msg = HeartBeatReport_protocol().generateHeartBeatMsg() #终端上报心跳协议
# msg = LoginReport_protocol().generateLoginMsg() #终端上报登录协议 # msg = LoginReport_protocol().generateLoginMsg() #终端上报登录协议
# msg = SecurityStatusReport_protocol().generateSecurityStatusMsg() #终端上报安防状态协议 # msg = SecurityStatusReport_protocol().generateSecurityStatusMsg() #终端上报安防状态协议
...@@ -46,7 +46,7 @@ port = 9008 ...@@ -46,7 +46,7 @@ port = 9008
# msg = SleepReport_protocol().generateSleepMsg() #终端休眠数据包 # msg = SleepReport_protocol().generateSleepMsg() #终端休眠数据包
# msg = CommonReport_protocol().generateCommonMsg() #通用应答消息 # msg = CommonReport_protocol().generateCommonMsg() #通用应答消息
# msg = VoltageDataReport_protocol().generateMsg() #终端上报电瓶电压采样数据 # msg = VoltageDataReport_protocol().generateMsg() #终端上报电瓶电压采样数据
msg = TroubleCode_protocol().generateMsg() #终端上报故障码数据包 # msg = TroubleCode_protocol().generateMsg() #终端上报故障码数据包
print(msg) print(msg)
BUF_SIZE = 1024 BUF_SIZE = 1024
......
...@@ -39,6 +39,11 @@ class ProtocolSimulaterService(): ...@@ -39,6 +39,11 @@ class ProtocolSimulaterService():
self.sn = 0 #消息流水号 self.sn = 0 #消息流水号
self.travelDirection = 0 #行驶方向,0表示正向行驶,1表示反向行驶 self.travelDirection = 0 #行驶方向,0表示正向行驶,1表示反向行驶
self.directAngle = 60 #汽车方向角 self.directAngle = 60 #汽车方向角
'''
为0表示正常发送,type为1表示数据写入本地
# 用来控制发送消息的方式(是正常发送,还是将发送的数据保存到本地,不发送)
'''
self.sendType = 1
# 定义要发送的obd数据 # 定义要发送的obd数据
self.OBDdata = {"fireStatus":1,"ACCStatus":0,"engineSpeed":300,"speed":0,"meterMileage":6000,"totailMileage":600,"totalOilExpen":30,"totalRunTime":10} self.OBDdata = {"fireStatus":1,"ACCStatus":0,"engineSpeed":300,"speed":0,"meterMileage":6000,"totailMileage":600,"totalOilExpen":30,"totalRunTime":10}
# 定义初始的obd数据,与上面的OBD数据保持一致,主要用于汽车行驶过程中数据变化量的计算 # 定义初始的obd数据,与上面的OBD数据保持一致,主要用于汽车行驶过程中数据变化量的计算
...@@ -72,6 +77,8 @@ class ProtocolSimulaterService(): ...@@ -72,6 +77,8 @@ class ProtocolSimulaterService():
self.data["travelData"]["oilExpend"] = data self.data["travelData"]["oilExpend"] = data
def setSendDur(self,data): def setSendDur(self,data):
self.sendDur = int(data) self.sendDur = int(data)
def setSendType(self,data):
self.sendType = data
...@@ -88,10 +95,21 @@ class ProtocolSimulaterService(): ...@@ -88,10 +95,21 @@ class ProtocolSimulaterService():
def getCarData(self): def getCarData(self):
return self.carData return self.carData
#######################################################
# type 为0表示正常发送,type为1表示数据写入本地
#######################################################
def sendMsg(self,msg): def sendMsg(self,msg):
if self.sendType == 0:
self.socket.setTimeOut(self.timeout) self.socket.setTimeOut(self.timeout)
self.socket.send(msg) self.socket.send(msg)
elif self.sendType == 1:
msgId = self.getMsgFunId(msg)
if msgId == "0021":
self.saveMsgLocal("event.txt",msg)
elif msgId == "0010":
self.saveMsgLocal("gps.txt",msg)
elif msgId == "0012":
self.saveMsgLocal("obd.txt",msg)
def revMsg(self): def revMsg(self):
self.socket.setTimeOut(self.timeout) self.socket.setTimeOut(self.timeout)
return self.socket.receive() return self.socket.receive()
...@@ -502,6 +520,23 @@ class ProtocolSimulaterService(): ...@@ -502,6 +520,23 @@ class ProtocolSimulaterService():
elif lngCut < 0 and latCut < 0: elif lngCut < 0 and latCut < 0:
dire = 180 + 90 - dire dire = 180 + 90 - dire
###########################################################
# 将要发送的数据保存到本地
###########################################################
def saveMsgLocal(self,fName,data):
timeStamp = time.time()
timeArray = time.localtime(timeStamp)
curTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
thePath = 'data/protocolTools/sendMsg'
if not os.path.exists(thePath):
os.makedirs(thePath)
thePath = thePath + "/" + self.carId + "/"
if not os.path.exists(thePath):
os.makedirs(thePath)
with open(thePath + fName, "a", encoding="utf-8") as fi:
fi.write("[" + curTime +"]" + data + "\n")
if __name__ == "__main__": if __name__ == "__main__":
ProtocolSimulaterService().getDirAngleTest() ProtocolSimulaterService().getDirAngleTest()
......
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