Commit 7c5aabee authored by liyuanhong's avatar liyuanhong

完成了新硬件并发脚本开发

parent 7a63999d
#encoding:utf-8
'''
定义数据上行透传消息
'''
import datetime
from lib.Mnew.MessageBase import MessageBase
class DataUpstreamTransport_msg(MessageBase):
def __init__(self):
super().__init__() #不执行该方法,无法使用父类里面定义的属性
self.phoneNum = 201912000000
def setPhoneNum(self, data):
self.phoneNum = data
#######################################################
# 生成一条完整的消息
#######################################################
def generateMsg(self):
msg = ""
msgHeader = self.getMsgHeader()
msgBody = self.getMsgBody()
checkCode = self.getCheckCode(msgHeader + msgBody)
msg = msg + self.IDENTIFY
info = msgHeader + msgBody + checkCode
info = self.replace7e7d(info)
msg = msg + info
msg = msg + self.IDENTIFY
return msg
# 生成一条完整的消息,针对图形界面,可传递参数
def generateMsg_GUI(self,msgID="0100",phoneNum="13146201119",msgWaterCode=1,encryptionType=0,subPkg=0,msgType="F3",data={"infoTime":"2020-02-06 11:31:56"}):
msg = ""
msgHeader = self.getMsgHeader_GUI(msgID,phoneNum,msgWaterCode,encryptionType,subPkg)
msgBody = self.getMsgBody_GUI(msgType,data)
checkCode = self.getCheckCode(msgHeader + msgBody)
msg = msg + self.IDENTIFY
info = msgHeader + msgBody + checkCode
info = self.replace7e7d(info)
msg = msg + info
msg = msg + self.IDENTIFY
return msg
#######################################################
# 获取消息体
#######################################################
def getMsgBody(self):
msg = ""
#透传消息类型
#0xF1 驾驶行程数据(熄火发送)
# 0xF2 故障码数据(状态改变发送)
# 0xF3 休眠进入(进入休眠模式发送)
# 0xF4 休眠唤醒(退出休眠模式发送)
msgType = "F2"
msgContent = ""
if msgType == "F1":
msgContent = self.getDrivingData() #驾驶行程数据(熄火发送)
elif msgType == "F2":
msgContent = self.getTroubleCodeData() #故障码数据(状态改变发送)
elif msgType == "F3":
msgContent = self.getIntoSleepData() #休眠进入(进入休眠模式发送)
elif msgType == "F4":
msgContent = self.getOutSleepData() #休眠唤醒(退出休眠模式发送)
msg = msgType + msgContent
return msg
# 获取消息体,针对图形界面,可传递参数
def getMsgBody_GUI(self,msgType="F3",data={"infoTime":"2020-02-06 11:31:56"}):
msg = ""
# 透传消息类型
# 0xF1 驾驶行程数据(熄火发送)
# 0xF2 故障码数据(状态改变发送)
# 0xF3 休眠进入(进入休眠模式发送)
# 0xF4 休眠唤醒(退出休眠模式发送)
msgType = msgType
msgContent = ""
if msgType == "F1":
# 驾驶行程数据(熄火发送)
msgContent = self.getDrivingData_GUI(data["time_1"],data["time_2"],data["fireLatitude"],data["fireLongitude"],data["unFireLatitude"], \
data["unFireLongitude"],data["drivingCircleLabel"],data["drivingCircleTotalMileageType"],data["drivingCircleTotalMileage"], \
data["drivingCircleTotalOil"],data["drivingCircleTotalTime"],data["drivingCircleOverSpeedTotalTime"], \
data["drivingCircleOverSpeedTotalTimes"],data["drivingCircleAverageSpeed"],data["drivingCircleMaxSpeed"], \
data["drivingCircleIdlingTime"],data["drivingCircleFootBrakeIsSupport"],data["drivingCircleFootBrakeTatalTimes"], \
data["drivingCircleRapidlyAccelerateTimes"],data["drivingCircleSharpSlowdownTimes"],data["drivingCircleSharpCurveTimes"], \
data["speedIn20"],data["speedIn20_40"],data["speedIn40_60"],data["speedIn60_80"],data["speedIn80_100"],data["speedIn100_120"], \
data["speedOut120"],data["rapidlyAccelerateTimes"],data["rapidlySharpSlowdownTimes"],data["sharpCurveTimes"])
elif msgType == "F2":
# 故障码数据(状态改变发送)
msgContent = self.getTroubleCodeData_GUI(data["infoTime"],data["latitude"],data["longitude"],data["troubleCodeNums"])
elif msgType == "F3":
# 休眠进入(进入休眠模式发送)
msgContent = self.getIntoSleepData_GUI(data["infoTime"])
elif msgType == "F4":
# 休眠唤醒(退出休眠模式发送)
msgContent = self.getOutSleepData_GUI(data["infoTime"],data["outSleepType"],data["carVoltage"],data["vibrateOutSleepSpeedUpVal"])
msg = msgType + msgContent
return msg
#######################################################
# 获取消息头
#######################################################
def getMsgHeader(self):
# msgID = self.int2hexStringByBytes(102,2) #消息id
msgID = "0900"
msgBodyProperty = self.getMsgBodyProperty(int(len(self.getMsgBody()) / 2)) #消息体属性
phoneNum = self.int2BCD(self.phoneNum) #终端手机号
msgWaterCode = self.int2hexStringByBytes(1,2) #消息流水号
subPkgContent = "" #消息包封装项
data = msgID + msgBodyProperty + phoneNum + msgWaterCode + subPkgContent
return data
#获取消息体属性
def getMsgBodyProperty(self,msgBodyLen=128,encryptionType=0,subPkg=0):
if msgBodyLen >= 512:
raise RuntimeError('消息体长度超长!')
msgBodyLen = msgBodyLen #消息体长度
encryptionType = encryptionType #加密方式
subPkg = subPkg #分包
retain = 0 #保留位
data = msgBodyLen + encryptionType + subPkg + retain
dataHex = self.int2hexStringByBytes(data,2)
return dataHex
#######################################################
# 获取驾驶行程数据
#######################################################
def getDrivingData(self):
time_1 = "0001" + self.int2hexStringByBytes(6) + self.getBCDTime("2020-02-05 22:07:30")
time_2 = "0002" + self.int2hexStringByBytes(6) + self.getBCDTime(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
fireLatitude = "0003" + self.int2hexStringByBytes(4) + self.getFireLatitude(29.40268) #点火纬度
fireLongitude = "0004" + self.int2hexStringByBytes(4) + self.getFireLongitude(106.54041) #点火经度
unFireLatitude = "0005" + self.int2hexStringByBytes(4) + self.getUnFireLatitude(29.40268) #熄火纬度
unFireLongitude = "0006" + self.int2hexStringByBytes(4) + self.getUnFireLongitude(106.54041) # 熄火经度
drivingCircleLabel = "0007" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(123,2) #驾驶循环标签
#一个驾驶循环总里程类型:
# 0x01:GPS 总里程(累计)
# 0x02:J1939 里程算法 1
# 0x03:J1939 里程算法 2
# 0x04:J1939 里程算法 3
# 0x05:J1939 里程算法 4
# 0x06:J1939 里程算法 5
# 0x07:OBD 仪表里程
# 0x08:OBD 速度里程
# 0x09:J1939 里程算法 6
# 0x0A:J1939 里程算法 7
# 0x0B:J1939 里程算法 8
# 0x0C:J1939 里程算法 9
drivingCircleTotalMileageType = "0008" + self.int2hexStringByBytes(1) + "01"
#一个驾驶循环总里程,单位米
drivingCircleTotalMileage = "0009" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(38090,4)
#一个驾驶循环总耗油,单位毫升(ml)
drivingCircleTotalOil = "000A" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(75400,4)
#一个驾驶循环总时长,单位秒
drivingCircleTotalTime = "000B" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(726000,4)
#一个驾驶循环超速累计时长,单位秒
drivingCircleOverSpeedTotalTime = "000C" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(54000,2)
#一个驾驶循环超速次数,单位次
drivingCircleOverSpeedTotalTimes = "000D" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(101,2)
#一个驾驶循环平均车速,单位 KM/H
drivingCircleAverageSpeed = "000E" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(65)
#一个驾驶循环最大车速,单位 KM/H
drivingCircleMaxSpeed = "000F" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(123)
#一个驾驶循环怠速时长,单位秒
drivingCircleIdlingTime = "0010" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(12600000,4)
#一个驾驶循环脚刹次数支持与否,1 为支持
drivingCircleFootBrakeIsSupport = "0011" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(1)
#一个驾驶循环脚刹总次数,单位次
drivingCircleFootBrakeTatalTimes = "0012" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(32,2)
#一个驾驶循环急加速次数
drivingCircleRapidlyAccelerateTimes = "0013" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(79,4)
#一个驾驶循环急减速次数
drivingCircleSharpSlowdownTimes = "0014" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(10,4)
#一个驾驶循环急转弯次数
drivingCircleSharpCurveTimes = "0015" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(33,4)
#速度为-20Km/H 的里程,单位:m
speedIn20 = "0016" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(1068,4)
#速度为 20-40Km/H 的里程,单位:m
speedIn20_40 = "0017" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(2020,4)
#速度为 40-60Km/H 的里程,单位:m
speedIn40_60 = "0018" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(30400,4)
#速度为 60-80Km/H 的里程,单位:m
speedIn60_80 = "0019" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(37000,4)
#速度为 80-100Km/H 的里程,单位:m
speedIn80_100 = "001A" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(10400,4)
#速度为 100-120Km/H 的里程,单位:m
speedIn100_120 = "001B" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(5000,4)
#速度为 120Km/H 以上的里程,单位:m
speedOut120 = "001C" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(3200,4)
#急加速总次数
rapidlyAccelerateTimes = "001D" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(3000,4)
#急减速总次数
rapidlySharpSlowdownTimes = "001E" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(3507,4)
#急转弯总次数
sharpCurveTimes = "001F" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(580,4)
data = time_1 + time_2 + fireLatitude + fireLongitude + unFireLatitude
data = data + unFireLongitude + drivingCircleLabel + drivingCircleTotalMileageType + drivingCircleTotalMileage + drivingCircleTotalOil
data = data + drivingCircleTotalTime + drivingCircleOverSpeedTotalTime + drivingCircleOverSpeedTotalTimes + drivingCircleAverageSpeed + drivingCircleMaxSpeed
data = data + drivingCircleIdlingTime + drivingCircleFootBrakeIsSupport + drivingCircleFootBrakeTatalTimes + drivingCircleRapidlyAccelerateTimes + drivingCircleSharpSlowdownTimes
data = data + drivingCircleSharpCurveTimes + speedIn20 + speedIn20_40 + speedIn40_60 + speedIn60_80
data = data + speedIn80_100 + speedIn100_120 + speedOut120 + rapidlyAccelerateTimes + rapidlySharpSlowdownTimes
data = data + sharpCurveTimes
return data
# 获取驾驶行程数据,针对图形界面,可传递参数
def getDrivingData_GUI(self,time_1="2020-02-05 22:07:30",time_2="2020-02-08 22:07:30",fireLatitude=29.40268,fireLongitude=106.54041, \
unFireLatitude=29.40268,unFireLongitude=106.54041,drivingCircleLabel=123,drivingCircleTotalMileageType="01", \
drivingCircleTotalMileage=38090,drivingCircleTotalOil=75400,drivingCircleTotalTime=726000, \
drivingCircleOverSpeedTotalTime=54000,drivingCircleOverSpeedTotalTimes=101,drivingCircleAverageSpeed=65, \
drivingCircleMaxSpeed=123,drivingCircleIdlingTime=12600000,drivingCircleFootBrakeIsSupport=1, \
drivingCircleFootBrakeTatalTimes=32,drivingCircleRapidlyAccelerateTimes=79,drivingCircleSharpSlowdownTimes=10, \
drivingCircleSharpCurveTimes=33,speedIn20=1068,speedIn20_40=2020,speedIn40_60=30400,speedIn60_80=37000, \
speedIn80_100=10400,speedIn100_120=5000,speedOut120=3200,rapidlyAccelerateTimes=3000, \
rapidlySharpSlowdownTimes=3507,sharpCurveTimes=580):
time_1 = "0001" + self.int2hexStringByBytes(6) + self.getBCDTime(time_1)
time_2 = "0002" + self.int2hexStringByBytes(6) + self.getBCDTime(time_2)
fireLatitude = "0003" + self.int2hexStringByBytes(4) + self.getFireLatitude(fireLatitude) #点火纬度
fireLongitude = "0004" + self.int2hexStringByBytes(4) + self.getFireLongitude(fireLongitude) #点火经度
unFireLatitude = "0005" + self.int2hexStringByBytes(4) + self.getUnFireLatitude(unFireLatitude) #熄火纬度
unFireLongitude = "0006" + self.int2hexStringByBytes(4) + self.getUnFireLongitude(unFireLongitude) # 熄火经度
drivingCircleLabel = "0007" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(drivingCircleLabel,2) #驾驶循环标签
#一个驾驶循环总里程类型:
drivingCircleTotalMileageType = "0008" + self.int2hexStringByBytes(1) + drivingCircleTotalMileageType
#一个驾驶循环总里程,单位米
drivingCircleTotalMileage = "0009" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(drivingCircleTotalMileage,4)
#一个驾驶循环总耗油,单位毫升(ml)
drivingCircleTotalOil = "000A" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(drivingCircleTotalOil,4)
#一个驾驶循环总时长,单位秒
drivingCircleTotalTime = "000B" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(drivingCircleTotalTime,4)
#一个驾驶循环超速累计时长,单位秒
drivingCircleOverSpeedTotalTime = "000C" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(drivingCircleOverSpeedTotalTime,2)
#一个驾驶循环超速次数,单位次
drivingCircleOverSpeedTotalTimes = "000D" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(drivingCircleOverSpeedTotalTimes,2)
#一个驾驶循环平均车速,单位 KM/H
drivingCircleAverageSpeed = "000E" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(drivingCircleAverageSpeed)
#一个驾驶循环最大车速,单位 KM/H
drivingCircleMaxSpeed = "000F" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(drivingCircleMaxSpeed)
#一个驾驶循环怠速时长,单位秒
drivingCircleIdlingTime = "0010" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(drivingCircleIdlingTime,4)
#一个驾驶循环脚刹次数支持与否,1 为支持
drivingCircleFootBrakeIsSupport = "0011" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(drivingCircleFootBrakeIsSupport)
#一个驾驶循环脚刹总次数,单位次
drivingCircleFootBrakeTatalTimes = "0012" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(drivingCircleFootBrakeTatalTimes,2)
#一个驾驶循环急加速次数
drivingCircleRapidlyAccelerateTimes = "0013" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(drivingCircleRapidlyAccelerateTimes,4)
#一个驾驶循环急减速次数
drivingCircleSharpSlowdownTimes = "0014" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(drivingCircleSharpSlowdownTimes,4)
#一个驾驶循环急转弯次数
drivingCircleSharpCurveTimes = "0015" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(drivingCircleSharpCurveTimes,4)
#速度为-20Km/H 的里程,单位:m
speedIn20 = "0016" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(speedIn20,4)
#速度为 20-40Km/H 的里程,单位:m
speedIn20_40 = "0017" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(speedIn20_40,4)
#速度为 40-60Km/H 的里程,单位:m
speedIn40_60 = "0018" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(speedIn40_60,4)
#速度为 60-80Km/H 的里程,单位:m
speedIn60_80 = "0019" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(speedIn60_80,4)
#速度为 80-100Km/H 的里程,单位:m
speedIn80_100 = "001A" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(speedIn80_100,4)
#速度为 100-120Km/H 的里程,单位:m
speedIn100_120 = "001B" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(speedIn100_120,4)
#速度为 120Km/H 以上的里程,单位:m
speedOut120 = "001C" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(speedOut120,4)
#急加速总次数
rapidlyAccelerateTimes = "001D" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(rapidlyAccelerateTimes,4)
#急减速总次数
rapidlySharpSlowdownTimes = "001E" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(rapidlySharpSlowdownTimes,4)
#急转弯总次数
sharpCurveTimes = "001F" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(sharpCurveTimes,4)
data = time_1 + time_2 + fireLatitude + fireLongitude + unFireLatitude
data = data + unFireLongitude + drivingCircleLabel + drivingCircleTotalMileageType + drivingCircleTotalMileage + drivingCircleTotalOil
data = data + drivingCircleTotalTime + drivingCircleOverSpeedTotalTime + drivingCircleOverSpeedTotalTimes + drivingCircleAverageSpeed + drivingCircleMaxSpeed
data = data + drivingCircleIdlingTime + drivingCircleFootBrakeIsSupport + drivingCircleFootBrakeTatalTimes + drivingCircleRapidlyAccelerateTimes + drivingCircleSharpSlowdownTimes
data = data + drivingCircleSharpCurveTimes + speedIn20 + speedIn20_40 + speedIn40_60 + speedIn60_80
data = data + speedIn80_100 + speedIn100_120 + speedOut120 + rapidlyAccelerateTimes + rapidlySharpSlowdownTimes
data = data + sharpCurveTimes
return data
#######################################################
# 获取点火纬度,单位:0.000001 度,Bit31=0/1 北纬/南纬
#######################################################
def getFireLatitude(self,data=29.40268):
orientation = 0 #0:北纬 1:南纬 (2147483648)
data = int(data * 1000000)
data = data + orientation
dataHex = self.int2hexStringByBytes(data, 4)
return dataHex
#######################################################
# 点火经度,单位:0.000001 度,Bit31=0/1 东经/西经
#######################################################
def getFireLongitude(self,data=106.54041):
orientation = 0 #0:东经 1:西经 (2147483648)
data = int(data * 1000000)
data = data + orientation
dataHex = self.int2hexStringByBytes(data, 4)
return dataHex
#######################################################
# 获取熄火纬度,单位:0.000001 度,Bit31=0/1 北纬/南纬
#######################################################
def getUnFireLatitude(self,data=29.40268):
orientation = 0 #0:北纬 1:南纬 (2147483648)
data = int(data * 1000000)
data = data + orientation
dataHex = self.int2hexStringByBytes(data, 4)
return dataHex
#######################################################
# 熄火经度,单位:0.000001 度,Bit31=0/1 东经/西经
#######################################################
def getUnFireLongitude(self,data=106.54041):
orientation = 0 #0:东经 1:西经 (2147483648)
data = int(data * 1000000)
data = data + orientation
dataHex = self.int2hexStringByBytes(data, 4)
return dataHex
#######################################################
# 获取故障码数据
#######################################################
def getTroubleCodeData(self):
infoTime = self.getBCDTime("2020-02-06 11:31:56")
#单位:0.000001 度,Bit31=0/1 北纬/南纬
latitude = self.getLatitude(29.40268)
#单位:0.000001 度,Bit31=0/1 东经/西经
longitude = self.getLongitude(106.54041)
#为 0 表示无故障码,非 0 为故障码个数
troubleCodeNums = 6
troubleCodeNumsHex = self.int2hexStringByBytes(troubleCodeNums)
#故障码
troubleCode = ""
for i in range(0,troubleCodeNums):
tbc0 = self.int2hexStringByBytes(i)
tbc1 = self.int2hexStringByBytes(1)
tbc2 = self.int2hexStringByBytes(2)
tbc3 = self.int2hexStringByBytes(3)
troubleCode = troubleCode + tbc0 + tbc1 + tbc2 + tbc3
data = infoTime + latitude + longitude + troubleCodeNumsHex + troubleCode
return data
# 获取故障码数据,针对图形界面,可传递参数
def getTroubleCodeData_GUI(self,infoTime="2020-02-06 11:31:56",latitude=29.40268,longitude=106.54041,troubleCodeNums=3):
infoTime = self.getBCDTime(infoTime)
#单位:0.000001 度,Bit31=0/1 北纬/南纬
latitude = self.getLatitude(latitude)
#单位:0.000001 度,Bit31=0/1 东经/西经
longitude = self.getLongitude(longitude)
#为 0 表示无故障码,非 0 为故障码个数
troubleCodeNums = troubleCodeNums
troubleCodeNumsHex = self.int2hexStringByBytes(troubleCodeNums)
#故障码
troubleCode = ""
for i in range(0,troubleCodeNums):
troubleCode = troubleCode + self.int2hexStringByBytes(i,4)
data = infoTime + latitude + longitude + troubleCodeNumsHex + troubleCode
return data
#获取维度
def getLatitude(self,data=29.40268):
orientation = 0 #0:北纬 1:南纬 (2147483648)
data = int(data * 1000000)
data = data + orientation
dataHex = self.int2hexStringByBytes(data, 4)
return dataHex
#获取经度
def getLongitude(self,data=106.54041):
orientation = 0 #0:东经 1:西经 (2147483648)
data = int(data * 1000000)
data = data + orientation
dataHex = self.int2hexStringByBytes(data, 4)
return dataHex
#######################################################
# 获取进入休眠数据包
#######################################################
def getIntoSleepData(self):
infoTime = self.getBCDTime("2020-02-06 11:31:56")
msg = infoTime
return msg
# 获取进入休眠数据包,针对图形界面,可传递参数
def getIntoSleepData_GUI(self,infoTime="2020-02-06 11:31:56"):
infoTime = self.getBCDTime(infoTime)
msg = infoTime
return msg
#######################################################
# 获取休眠唤醒数据包
#######################################################
def getOutSleepData(self):
infoTime = self.getBCDTime("2020-02-06 11:31:56")
#休眠唤醒类型
# 0x01:休眠定时唤醒
# 0x02:CAN1
# 0x04:CAN2
# 0x08:gSensor 0x10:电压变
outSleepType = "01"
#车辆电压,单位 0.1V
carVoltage = self.int2hexStringByBytes(360,2)
#振动唤醒加速度值,单位 mg
vibrateOutSleepSpeedUpVal = self.int2hexStringByBytes(3700,2)
data = infoTime + outSleepType + carVoltage + vibrateOutSleepSpeedUpVal
return data
#获取休眠唤醒数据包,针对图形界面,可传递参数
def getOutSleepData_GUI(self,infoTime="2020-02-06 11:31:56",outSleepType="01",carVoltage=360,vibrateOutSleepSpeedUpVal=3700):
infoTime = self.getBCDTime(infoTime)
#休眠唤醒类型
# 0x01:休眠定时唤醒
# 0x02:CAN1
# 0x04:CAN2
# 0x08:gSensor 0x10:电压变
outSleepType = outSleepType
#车辆电压,单位 0.1V
carVoltage = self.int2hexStringByBytes(carVoltage,2)
#振动唤醒加速度值,单位 mg
vibrateOutSleepSpeedUpVal = self.int2hexStringByBytes(vibrateOutSleepSpeedUpVal,2)
data = infoTime + outSleepType + carVoltage + vibrateOutSleepSpeedUpVal
return data
if __name__ == "__main__":
print(DataUpstreamTransport_msg().generateMsg())
#encoding:utf-8
'''
定义位置信息汇报消息
'''
import datetime
from random import random
from lib.Mnew.MessageBase import MessageBase
from lib.Mnew.data.AlarmEvent_data import AlarmEvent_data
from lib.Mnew.data.CarSafeStatusInfo import CarSafeStatusInfo
from lib.Mnew.data.Circum_data import Circum_data
from lib.Mnew.data.NewEnergyCar_data import NewEnergyCar_data
from lib.Mnew.data.SaloonCarOBD_data import SaloonCarOBD_data
from lib.Mnew.data.TruckCarOBD_data import TruckCarOBD_data
class Location_msg(MessageBase):
def __init__(self):
super().__init__()
self.phoneNum = 201912000000
def setPhoneNum(self, data):
self.phoneNum = data
#######################################################
# 生成一条完整的消息
#######################################################
def generateMsg(self):
msg = ""
msgHeader = self.getMsgHeader()
msgBody = self.getMsgBody()
checkCode = self.getCheckCode(msgHeader + msgBody)
msg = msg + self.IDENTIFY
info = msgHeader + msgBody + checkCode
info = self.replace7e7d(info)
msg = msg + info
msg = msg + self.IDENTIFY
return msg
# 生成一条完整的消息,针对图形界面,可传递参数
def generateMsg_GUI(self,params):
msg = ""
msgHeader = self.getMsgHeader_GUI(params["msgID"],int(params["phoneNum"]),int(params["msgWaterCode"]),int(params["encryptionType"]),int(params["subPkg"]))
msgBody = self.getMsgBody_GUI(params)
checkCode = self.getCheckCode(msgHeader + msgBody)
msg = msg + self.IDENTIFY
info = msgHeader + msgBody + checkCode
info = self.replace7e7d(info)
msg = msg + info
msg = msg + self.IDENTIFY
return msg
# 生成一条完整的消息,数据随机产生
def generateMsg_random(self):
msg = ""
msgID = "0200"
phoneNum = self.getRandomStr(11, "0123456789")
msgWaterCode = self.getRandomNum(1, 65535)
encryptionType = 0
# subPkg = self.getRandomNum(intArr=[0, 8192])
subPkg = 0
msgHeader = self.getMsgHeader_GUI(msgID,phoneNum,msgWaterCode,encryptionType,subPkg)
msgBody = self.getMsgBody_random()
checkCode = self.getCheckCode(msgHeader + msgBody)
msg = msg + self.IDENTIFY
info = msgHeader + msgBody + checkCode
info = self.replace7e7d(info)
msg = msg + info
msg = msg + self.IDENTIFY
return msg
#######################################################
# 获取消息体
#######################################################
def getMsgBody(self):
msg = ""
locationBaseInfo = self.getLocationBaseInfo() #位置基本信息
locationExtraInfo = self.getLocationExtraInfo() #位置附加信息
msg = locationBaseInfo + locationExtraInfo
return msg
# 获取消息体,针对图形界面,可传递参数
def getMsgBody_GUI(self,params):
msg = ""
locationBaseInfo = self.getLocationBaseInfo_GUI(params["baseInfo"]) #位置基本信息
locationExtraInfo = ""
if params["extraInfo"] == {}:
pass
else:
locationExtraInfo = self.getLocationExtraInfo_GUI(params["extraInfo"]) #位置附加信息
msg = locationBaseInfo + locationExtraInfo
return msg
# 获取消息体,数据随机产生
def getMsgBody_random(self):
msg = ""
locationBaseInfo = self.getLocationBaseInfo_random() #位置基本信息
locationExtraInfo = self.getLocationExtraInfo_random() #位置附加信息
msg = locationBaseInfo + locationExtraInfo
return msg
#######################################################
# 获取位置基本信息
#######################################################
def getLocationBaseInfo(self):
msg = ""
alarmFlag = self.getAlarmFlag() #报警标志
status = self.getStatus() #状态
latitude = self.getLatitude() #纬度
longtitude = self.getLongtitude() #经度
elevation = self.getElevation() #海拔高度
speed = self.getSpeed() #速度
directionAngle = self.getDirectionAngle() #获取方向角度
infoTime = self.getInfoTime() #获取时间
msg = alarmFlag + status + latitude + longtitude + elevation + speed + directionAngle + infoTime
return msg
# 获取位置基本信息,针对图形界面,可传递参数
def getLocationBaseInfo_GUI(self,baseInfo):
msg = ""
alarmFlag = self.int2hexStringByBytes(int(baseInfo["alarmFlag"]),4) #报警标志
status = self.int2hexStringByBytes(int(baseInfo["status"]),4) #状态
latitude = self.getLatitude(float(baseInfo["latitude"])) #纬度
longtitude = self.getLongtitude(float(baseInfo["longtitude"])) #经度
elevation = self.getElevation(int(baseInfo["elevation"])) #海拔高度
speed = self.getSpeed(int(baseInfo["speed"])) #速度
directionAngle = self.getDirectionAngle(int(baseInfo["directionAngle"])) #获取方向角度
infoTime = self.getInfoTime(baseInfo["infoTime"]) #获取时间
msg = alarmFlag + status + latitude + longtitude + elevation + speed + directionAngle + infoTime
return msg
# 获取位置基本信息,数据随机产生
def getLocationBaseInfo_random(self):
msg = ""
alarmFlag = self.int2hexStringByBytes(self.getRandomNum(intArr=[0,1,2,4,8,16,32,64, \
128,256,512,1024,2048,4096,8192,16384,262144,524288,1048576,2097152,4194304, \
8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,2147483648],mult=29),4) #报警标志
status = self.int2hexStringByBytes(self.getRandomNum(intArr=[0,1,2,4,8,16,32,256, \
512,768,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152],mult=21),4) #状态
latitude = self.getLatitude(self.getRandomNum(s=0,e=90000000) / 1000000) #纬度
longtitude = self.getLongtitude(self.getRandomNum(s=0,e=180000000) / 1000000) #经度
elevation = self.getElevation(self.getRandomNum(s=0,e=6000)) #海拔高度
speed = self.getSpeed(self.getRandomNum(s=0,e=150)) #速度
directionAngle = self.getDirectionAngle(self.getRandomNum(s=0,e=359)) #获取方向角度
infoTime = self.getInfoTime(self.getRandomDate()) #获取时间
msg = alarmFlag + status + latitude + longtitude + elevation + speed + directionAngle + infoTime
return msg
#######################################################
# 获取位置附加信息
#######################################################
def getLocationExtraInfo(self):
data = ""
# 里程,DWORD,1 / 10km,对应车上里程表读数;不支持OBD时,为基于GPS车速统计的车辆累计行驶总里程。
extra_01 = "01" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(20202020,4)
#油量,WORD,1/10L,对应车上油量表读数
extra_02 = "02" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(5200,2)
#超速报警附加信息
extra_11 = "11" + self.int2hexStringByBytes(int(len(self.getOverSpeedAlarmExtraInfo()) / 2)) + self.getOverSpeedAlarmExtraInfo()
#进出区域/路线报警附加信息见
extra_12 = "12" + self.int2hexStringByBytes(6) + self.getInOutAreaAlarmExtraInfo()
#路段行驶时间不足/过长报警附加信息见
extra_13 = "13" + self.int2hexStringByBytes(7) + self.getDrivingLongOrShortAlarmExtraInfo()
#IO 状态位
extra_2A = "2A" + self.int2hexStringByBytes(2) + self.getStatusBit()
#BYTE,无线通信网络信号强度
extra_30 = "30" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(33)
#BYTE,GNSS 定位卫星数
extra_31 = "31" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(2)
#基础数据项列表
extra_EA = "EA" + self.int2hexStringByBytes(int(len(self.getBaseDataList()) / 2)) + self.getBaseDataList()
#轿车 OBD 数据流
extra_EB = "EB" + self.int2hexStringByBytes(int(len(SaloonCarOBD_data().generateSaloonCarOBDData()) / 2)) + SaloonCarOBD_data().generateSaloonCarOBDData()
#货车 OBD 数据流
extra_EC = "EC" + self.int2hexStringByBytes(int(len(TruckCarOBD_data().generateTruckCarOBD_data()) / 2)) + TruckCarOBD_data().generateTruckCarOBD_data()
#新能源 OBD 数据流
extra_ED = "ED" + self.int2hexStringByBytes(int(len(NewEnergyCar_data().generateNewEnergyCar_data()) / 2)) + NewEnergyCar_data().generateNewEnergyCar_data()
#外设数据项列表
extra_EE = "EE" + self.int2hexStringByBytes(int(len(Circum_data().generateCircum_data()) / 2)) + Circum_data().generateCircum_data()
#报警事件 ID 数据项列表
extra_FA = "FA" + self.int2hexStringByBytes(int(len(AlarmEvent_data().generateAlarmEvent_data()) / 2)) + AlarmEvent_data().generateAlarmEvent_data()
data = extra_01 + extra_02 + extra_11 + extra_31 + extra_EA + extra_EB + extra_FA
# data = extra_11 + extra_31 + extra_EA + extra_EB + extra_FA
# data = extra_11 + extra_31 + extra_EA + extra_FA
# data = extra_01 + extra_02 + extra_11 + extra_12 + extra_13
# data = data + extra_2A + extra_30 + extra_31 + extra_EA + extra_EB
# data = data +extra_FA
return data
def getLocationExtraInfo_GUI(self,extraInfo):
data = ""
# 里程,DWORD,1 / 10km,对应车上里程表读数;不支持OBD时,为基于GPS车速统计的车辆累计行驶总里程。
extra_01 = "01" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(20202020,4)
#油量,WORD,1/10L,对应车上油量表读数
extra_02 = "02" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(5200,2)
#超速报警附加信息
extra_11 = "11" + self.int2hexStringByBytes(int(len(self.getOverSpeedAlarmExtraInfo()) / 2)) + self.getOverSpeedAlarmExtraInfo()
#进出区域/路线报警附加信息见
extra_12 = "12" + self.int2hexStringByBytes(6) + self.getInOutAreaAlarmExtraInfo()
#路段行驶时间不足/过长报警附加信息见
extra_13 = "13" + self.int2hexStringByBytes(7) + self.getDrivingLongOrShortAlarmExtraInfo()
#IO 状态位
extra_2A = "2A" + self.int2hexStringByBytes(2) + self.getStatusBit()
#BYTE,无线通信网络信号强度
extra_30 = "30" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(33)
#BYTE,GNSS 定位卫星数
extra_31 = "31" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(2)
#基础数据项列表
extra_EA = "EA" + self.int2hexStringByBytes(int(len(self.getBaseDataList()) / 2)) + self.getBaseDataList()
#轿车 OBD 数据流
extra_EB = "EB" + self.int2hexStringByBytes(int(len(SaloonCarOBD_data().generateSaloonCarOBDData()) / 2)) + SaloonCarOBD_data().generateSaloonCarOBDData()
#货车 OBD 数据流
extra_EC = "EC" + self.int2hexStringByBytes(int(len(TruckCarOBD_data().generateTruckCarOBD_data()) / 2)) + TruckCarOBD_data().generateTruckCarOBD_data()
#新能源 OBD 数据流
extra_ED = "ED" + self.int2hexStringByBytes(int(len(NewEnergyCar_data().generateNewEnergyCar_data()) / 2)) + NewEnergyCar_data().generateNewEnergyCar_data()
#外设数据项列表
extra_EE = "EE" + self.int2hexStringByBytes(int(len(Circum_data().generateCircum_data()) / 2)) + Circum_data().generateCircum_data()
#报警事件 ID 数据项列表
extra_FA = "FA" + self.int2hexStringByBytes(int(len(AlarmEvent_data().generateAlarmEvent_data()) / 2)) + AlarmEvent_data().generateAlarmEvent_data()
data = extra_11 + extra_31 + extra_EA + extra_EC
# data = extra_01 + extra_02 + extra_11 + extra_12 + extra_13
# data = data + extra_2A + extra_30 + extra_31 + extra_EA + extra_EB
# data = data +extra_FA
return data
# 获取位置附加信息,数据随机产生
def getLocationExtraInfo_random(self):
data = ""
# 里程,DWORD,1 / 10km,对应车上里程表读数;不支持OBD时,为基于GPS车速统计的车辆累计行驶总里程。
extra_01 = "01" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(self.getRandomNum(0,4294967295),4)
#油量,WORD,1/10L,对应车上油量表读数
extra_02 = "02" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(self.getRandomNum(0,65535),2)
#超速报警附加信息
data_11 = self.getOverSpeedAlarmExtraInfo_random()
extra_11 = "11" + self.int2hexStringByBytes(int(len(data_11) / 2)) + data_11
#进出区域/路线报警附加信息见
extra_12 = "12" + self.int2hexStringByBytes(6) + self.getInOutAreaAlarmExtraInfo_random()
#路段行驶时间不足/过长报警附加信息见
extra_13 = "13" + self.int2hexStringByBytes(7) + self.getDrivingLongOrShortAlarmExtraInfo_ramdom()
#IO 状态位
extra_2A = "2A" + self.int2hexStringByBytes(2) + self.getStatusBit_random()
#BYTE,无线通信网络信号强度
extra_30 = "30" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(self.getRandomNum(0,255))
#BYTE,GNSS 定位卫星数
extra_31 = "31" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(self.getRandomNum(0,255))
data_EA = self.getBaseDataList_random()
#基础数据项列表
extra_EA = "EA" + self.int2hexStringByBytes(int(len(data_EA) / 2)) + data_EA
#轿车 OBD 数据流
data_EB = SaloonCarOBD_data().generateSaloonCarOBDData_random()
extra_EB = "EB" + self.int2hexStringByBytes(int(len(data_EB) / 2)) + data_EB
#货车 OBD 数据流
# extra_EC = "EC" + self.int2hexStringByBytes(int(len(TruckCarOBD_data().generateTruckCarOBD_data()) / 2)) + TruckCarOBD_data().generateTruckCarOBD_data()
#新能源 OBD 数据流
# extra_ED = "ED" + self.int2hexStringByBytes(int(len(NewEnergyCar_data().generateNewEnergyCar_data()) / 2)) + NewEnergyCar_data().generateNewEnergyCar_data()
#外设数据项列表
# extra_EE = "EE" + self.int2hexStringByBytes(int(len(Circum_data().generateCircum_data()) / 2)) + Circum_data().generateCircum_data()
#报警事件 ID 数据项列表
data_FA = AlarmEvent_data().generateAlarmEvent_data_random()
extra_FA = "FA" + self.int2hexStringByBytes(int(len(data_FA) / 2)) + data_FA
arr = []
arr.append(extra_01)
arr.append(extra_02)
arr.append(extra_11)
arr.append(extra_12)
arr.append(extra_13)
arr.append(extra_2A)
arr.append(extra_30)
arr.append(extra_31)
arr.append(extra_EA)
arr.append(extra_EB)
arr.append(extra_FA)
mult = self.getRandomNum(0,11)
temp = []
for i in range(0, mult):
con = self.getRandomNum(intArr=arr,mult=1)
if con in temp:
con = ""
temp.append(con)
data = data + con
return data
#获取超速报警附加信息
def getOverSpeedAlarmExtraInfo(self):
# 0:无特定位置;
# 1:圆形区域;
# 2:矩形区域;
# 3:多边形区域;
# 4:路段
locationType = 1
areaId = "" #若位置类型为 0,无该字段
if locationType == 0:
pass
else:
areaId = self.int2hexStringByBytes(2020,4)
msg = self.int2hexStringByBytes(locationType) + areaId
return msg
#获取超速报警附加信息,数据随机产生
def getOverSpeedAlarmExtraInfo_random(self):
locationType = self.getRandomNum(intArr=[0,1,2,3,4])
areaId = "" #若位置类型为 0,无该字段
if locationType == 0:
pass
else:
areaId = self.int2hexStringByBytes(self.getRandomNum(0,4294967295),4)
msg = self.int2hexStringByBytes(locationType) + areaId
return msg
#获取进出区域/路线报警附加信息
def getInOutAreaAlarmExtraInfo(self):
# 0:无特定位置;
# 1:圆形区域;
# 2:矩形区域;
# 3:多边形区域;
# 4:路段
locationType = 1
areaId = ""
if locationType == 0:
areaId = "00000000"
else:
areaId = self.int2hexStringByBytes(2020, 4)
direction = 0 #0-进,1-出
msg = self.int2hexStringByBytes(locationType) + areaId + self.int2hexStringByBytes(direction)
return msg
#获取进出区域/路线报警附加信息,数据随机参数
def getInOutAreaAlarmExtraInfo_random(self):
locationType = self.getRandomNum(intArr=[0,1,2,3,4])
areaId = ""
if locationType == 0:
areaId = "00000000"
else:
areaId = self.int2hexStringByBytes(self.getRandomNum(1,4294967295), 4)
direction = self.getRandomNum(intArr=[0,1]) #0-进,1-出
msg = self.int2hexStringByBytes(locationType) + areaId + self.int2hexStringByBytes(direction)
return msg
#路线行驶时间不足/过长报警附加信息消息
def getDrivingLongOrShortAlarmExtraInfo(self):
areaId = self.int2hexStringByBytes(2020, 4) #路段Id
drivingTime = self.int2hexStringByBytes(36000,2) #路段行驶时间(单位:秒)
result = self.int2hexStringByBytes(0) #结果,0-不足,1-过长
msg = areaId + drivingTime + result
return msg
#路线行驶时间不足/过长报警附加信息消息,数据随机产生
def getDrivingLongOrShortAlarmExtraInfo_ramdom(self):
areaId = self.int2hexStringByBytes(self.getRandomNum(0,4294967295), 4) #路段Id
drivingTime = self.int2hexStringByBytes(self.getRandomNum(0,65535),2) #路段行驶时间(单位:秒)
result = self.int2hexStringByBytes(self.getRandomNum(intArr=[0,1])) #结果,0-不足,1-过长
msg = areaId + drivingTime + result
return msg
#获取状态位
def getStatusBit(self):
deepSleepStatus = 1 #1:深度休眠状态
sleepStatus = 2 #1:休眠状态
retain = 0
data = deepSleepStatus + sleepStatus + retain
dataHex = self.int2hexStringByBytes(data,2)
return dataHex
#获取状态位,数据随机产生
def getStatusBit_random(self):
dataHex = self.int2hexStringByBytes(self.getRandomNum(intArr=[0,1,2],mult=2),2)
return dataHex
#基础数据项列表
def getBaseDataList(self):
dataId_0001 = "0001" + self.int2hexStringByBytes(4) + self.getExpandStatusBit()
dataId_0002 = "0002" + self.int2hexStringByBytes(4) + self.getExpandAlarmBit()
dataId_0003 = "0003" + self.int2hexStringByBytes(5) + self.getTotalMileage()
dataId_0004 = "0004" + self.int2hexStringByBytes(5) + self.getTotalOil()
dataId_0005 = "0005" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(360000,4)
dataId_0006 = "0006" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(72000,4)
dataId_0007 = "0007" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(480000,4)
dataId_0010 = "0010" + self.int2hexStringByBytes(int(len(self.getSpeedupInOneSeconds()) / 2)) + self.getSpeedupInOneSeconds()
dataId_0011 = "0011" + self.int2hexStringByBytes(int(len(CarSafeStatusInfo().generateSecurityStatusData()) / 2)) + CarSafeStatusInfo().generateSecurityStatusData()
dataId_0012 = "0012" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(36,2)
dataId_0013 = "0013" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(6)
#TODO 由于被置灰,所以没有实现
# dataId_0015 = "0015" + self.int2hexStringByBytes(2)
# dataId_0016 = "0016"
#TODO 暂不支持
# dataId_0017 = "0017" + self.int2hexStringByBytes(2)
dataId_001D = "001D" + self.int2hexStringByBytes(1) + "01"
data = dataId_0001 + dataId_0002 + dataId_0003 + dataId_0004 + dataId_0005
data = data + dataId_0006 + dataId_0007 + dataId_0010 + dataId_0011 + dataId_0012
data = data + dataId_0013 + dataId_001D
return data
#基础数据项列表,数据随机产生
def getBaseDataList_random(self):
dataId_0001 = "0001" + self.int2hexStringByBytes(4) + self.getExpandStatusBit_random()
dataId_0002 = "0002" + self.int2hexStringByBytes(4) + self.getExpandAlarmBit_random()
dataId_0003 = "0003" + self.int2hexStringByBytes(5) + self.getTotalMileage_random()
dataId_0004 = "0004" + self.int2hexStringByBytes(5) + self.getTotalOil_random()
dataId_0005 = "0005" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(self.getRandomNum(0,4294967295),4)
dataId_0006 = "0006" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(self.getRandomNum(0,4294967295),4)
dataId_0007 = "0007" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(self.getRandomNum(0,4294967295),4)
dataId_0010 = "0010" + self.int2hexStringByBytes(int(len(self.getSpeedupInOneSeconds_random()) / 2)) + self.getSpeedupInOneSeconds_random()
dataId_0011 = "0011" + self.int2hexStringByBytes(int(len(CarSafeStatusInfo().generateSecurityStatusData_random()) / 2)) + CarSafeStatusInfo().generateSecurityStatusData_random()
dataId_0012 = "0012" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(self.getRandomNum(0,65535),2)
dataId_0013 = "0013" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(self.getRandomNum(0,255))
dataId_001D = "001D" + self.int2hexStringByBytes(1) + self.getRandomNum(intArr=["00","01","02"])
arr = []
arr.append(dataId_0001)
arr.append(dataId_0002)
arr.append(dataId_0003)
arr.append(dataId_0004)
arr.append(dataId_0005)
arr.append(dataId_0006)
arr.append(dataId_0007)
arr.append(dataId_0010)
arr.append(dataId_0011)
arr.append(dataId_0012)
arr.append(dataId_0013)
arr.append(dataId_001D)
mult = self.getRandomNum(0,12)
temp = []
data = ""
for i in range(0, mult):
con = self.getRandomNum(intArr=arr)
if con in temp:
con = ""
temp.append(con)
data = data + con
return data
'''扩展状态标志位,见 表 C1EXT1'''
def getExpandStatusBit(self):
defenseUndefenseRep = 0 #0:撤防上报;1:设防上报 (1)
retain = 0
data = defenseUndefenseRep + retain
dataHex = self.int2hexStringByBytes(data,4)
return dataHex
def getExpandStatusBit_random(self):
dataHex = self.int2hexStringByBytes(self.getRandomNum(intArr=[0,1]),4)
return dataHex
'''扩展报警标志位,见 表 C1EXT2'''
def getExpandAlarmBit(self):
waterTemperatureAlarm = 1 #1:水温报警 (1)
idlingOverlongAlarm = 2 #1:怠速过长报警 (2)
rapidlyAccelerateAlarm = 4 #1:急加速报警 (4)
sharpSlowsownAlarm = 8 #1:急减速报警 (8)
sharpCurve = 16 #1:急转弯报警 (16)
retain5_9 = 0
insertAlarm = 1024 #1:插入报警 (1024)
oilExpenseNotSupportAlarm = 2048 #1:油耗不支持报警 (2048)
OBDNotSupportAlarm = 4096 #1:OBD 不支持报警 (4096)
buslineNotSleepAlarm = 8192 #1:总线不睡眠报警 (8192)
illegalOpenDoor = 16384 #1:非法开门 (16384)
retain15_16 = 0
FLASHTroubleAlarm = 131072 #1: FLASH 故障报警 (131072)
CANTroubleAlarm = 262144 #1: CAN 模块故障报警 (262144)
D3SensorTroubleAlarm = 524288 #1:3D 传感器故障报警 (524288)
RTCTroubleAlarm = 1048576 #1:RTC 模块故障报警
retain21_31 = 0
data = waterTemperatureAlarm + idlingOverlongAlarm + rapidlyAccelerateAlarm + sharpSlowsownAlarm + sharpCurve
data = data + retain5_9 + insertAlarm + oilExpenseNotSupportAlarm + OBDNotSupportAlarm + buslineNotSleepAlarm
data = data + illegalOpenDoor + retain15_16 + FLASHTroubleAlarm + CANTroubleAlarm + D3SensorTroubleAlarm
data = data + RTCTroubleAlarm + retain21_31
dataHex = self.int2hexStringByBytes(data,4)
return dataHex
def getExpandAlarmBit_random(self):
data = self.getRandomNum(intArr=[0,1,2,4,8,16,1024,2048, \
4096,8192,16384,131072,262144,524288,1048576],mult=14)
dataHex = self.int2hexStringByBytes(data,4)
return dataHex
'''行驶总里程'''
def getTotalMileage(self):
caculateType = "0A"
totalMileage = self.int2hexStringByBytes(128000,4) #行驶总里程(单位米)
data = caculateType + totalMileage
return data
def getTotalMileage_random(self):
caculateType = self.getRandomNum(intArr=["01","02","03","04","05","06","07","09","0A","0B","0C"],)
totalMileage = self.int2hexStringByBytes(self.getRandomNum(0,4294967295),4) #行驶总里程(单位米)
data = caculateType + totalMileage
return data
'''行驶总油耗'''
def getTotalOil(self):
caculateType = "02"
totalOil = self.int2hexStringByBytes(120000,4) #总油耗(单位 mL)
data = caculateType + totalOil
return data
def getTotalOil_random(self):
caculateType = self.getRandomNum(intArr=["01","02","03","04","05","0B","0C"],)
totalOil = self.int2hexStringByBytes(self.getRandomNum(0,4294967295),4) #总油耗(单位 mL)
data = caculateType + totalOil
return data
'''此刻 1 秒内的加速度数据,见 表 C1EXT3'''
def getSpeedupInOneSeconds(self):
data = ""
pointCount = 4 #采集的点个数 N
collectIntercal = 100 #采集间隔(单位 ms),上传值为该采集间隔时间内的加速度均值
data = data + self.int2hexStringByBytes(pointCount,2)
data = data + self.int2hexStringByBytes(collectIntercal,2)
speedupVal = 1000 #采集点加速度均值
for i in range(0,pointCount):
data = data + self.int2hexStringByBytes(speedupVal + 10,2)
return data
def getSpeedupInOneSeconds_random(self):
data = ""
pointCount = self.getRandomNum(0,50) #采集的点个数 N
collectIntercal = self.getRandomNum(0,10000) #采集间隔(单位 ms),上传值为该采集间隔时间内的加速度均值
data = data + self.int2hexStringByBytes(pointCount,2)
data = data + self.int2hexStringByBytes(collectIntercal,2) #采集点加速度均值
for i in range(0,pointCount):
speedupVal = self.getRandomNum(0,65535)
data = data + self.int2hexStringByBytes(speedupVal,2)
return data
#######################################################
# 获取纬度信息
#######################################################
def getLatitude(self,data=29.40268):
data = int(data * 1000000)
dataHex = self.int2hexStringByBytes(data,4)
return dataHex
#######################################################
# 获取经度信息
#######################################################
def getLongtitude(self,data=106.54041):
data = int(data * 1000000)
dataHex = self.int2hexStringByBytes(data, 4)
return dataHex
#######################################################
# 获取海拔高度
#######################################################
def getElevation(self,data=521):
dataHex = self.int2hexStringByBytes(data, 2)
return dataHex
#######################################################
# 获取速度
#######################################################
def getSpeed(self,data=66):
dataHex = self.int2hexStringByBytes(data, 2)
return dataHex
#######################################################
# 获取方向角度
#######################################################
def getDirectionAngle(self,data=59):
dataHex = self.int2hexStringByBytes(data, 2)
return dataHex
#######################################################
# 获取时间
#######################################################
def getInfoTime(self,data="2020-02-04 18:57:04"):
#now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
data = data
data = data.replace("-","")
data = data.replace(" ","")
data = data.replace(":","")
data = data[2:]
data = self.int2BCD(int(data))
return data
#######################################################
# 获取消息头
#######################################################
def getMsgHeader(self):
# msgID = self.int2hexStringByBytes(102,2) #消息id
msgID = "0200"
msgBodyProperty = self.getMsgBodyProperty(int(len(self.getMsgBody()) / 2)) #消息体属性
phoneNum = self.int2BCD(self.phoneNum) #终端手机号
msgWaterCode = self.int2hexStringByBytes(1,2) #消息流水号
subPkgContent = "" #消息包封装项
data = msgID + msgBodyProperty + phoneNum + msgWaterCode + subPkgContent
return data
#获取消息体属性
def getMsgBodyProperty(self,msgBodyLen=128,encryptionType=0,subPkg=0):
if msgBodyLen >= 512:
raise RuntimeError('消息体长度超长!')
msgBodyLen = msgBodyLen #消息体长度
encryptionType = encryptionType #加密方式
subPkg = subPkg #分包
retain = 0 #保留位
data = msgBodyLen + encryptionType + subPkg + retain
dataHex = self.int2hexStringByBytes(data,2)
return dataHex
#######################################################
# 获取报警标志
#######################################################
def getAlarmFlag(self):
emergencyAlarm = 1 #紧急报警,触动报警开关后触发
overspeedAlarm = 2 #超速报警
fatigueDriving = 4 #疲劳驾驶
dangerAlarm = 8 #危险预警
GNSSTrouble = 16 #GNSS 模块发生故障
GNSSAntennaeLost = 32 #GNSS 天线未接或被剪断
GNSSAntennaeShortOut = 64 #GNSS 天线短路
TerminalMainPowerLackVoltage = 128 #终端主电源欠压
TerminalMainPowerLostConnect = 256 #终端主电源掉电(设备拔出告警)
TerMinalLCDTrouble = 512 #终端 LCD 或显示器故障
TTSTrouble = 1024 #TTS 模块故障
cameraTrouble = 2048 #摄像头故障
ICTrouble = 4096 #道路运输证 IC 卡模块故障
speedEarlyWarning = 8192 #超速预警
fatigueDrivingearlyWarning = 16384 #疲劳驾驶预警
retain1 = 0
retain2 = 0
retain3 = 0
drivingOverTime = 262144 #当天累计驾驶超时
stoppingOverTime = 524288 #超时停车
InOutArea = 1048576 #进出区域
InOutRouting = 2097152 #进出路线
drivingLongOrShort = 4194304 #路段行驶时间不足/过长
routingDivergeAlarm = 8388608 #路线偏离报警
VSSTrouble = 16777216 #车辆 VSS 故障
oilException = 33554432 #车辆油量异常
carLost = 67108864 #车辆被盗(通过车辆防盗器)
illegalFire = 134217728 #车辆非法点火
illegalMoving = 268435456 #车辆非法位移(拖车告警)
collisionAlarm = 536870912 #碰撞预警
rollOverAlarm = 1073741824 #侧翻预警
illegalOpenDoor = 2147483648 #非法开门报警(终端未设置区域时, 不判断非法开门)
# emergencyAlarm = 0 #紧急报警,触动报警开关后触发
# overspeedAlarm = 0 #超速报警
# fatigueDriving = 0 #疲劳驾驶
# dangerAlarm = 0 #危险预警
# GNSSTrouble = 0 #GNSS 模块发生故障
# GNSSAntennaeLost = 0 #GNSS 天线未接或被剪断
# GNSSAntennaeShortOut = 0 #GNSS 天线短路
# TerminalMainPowerLackVoltage = 0 #终端主电源欠压
# TerminalMainPowerLostConnect = 0 #终端主电源掉电(设备拔出告警)
# TerMinalLCDTrouble = 0 #终端 LCD 或显示器故障
# TTSTrouble = 0 #TTS 模块故障
# cameraTrouble = 0 #摄像头故障
# ICTrouble = 0 #道路运输证 IC 卡模块故障
# speedEarlyWarning = 0 #超速预警
# fatigueDrivingearlyWarning = 0 #疲劳驾驶预警
# retain1 = 0
# retain2 = 0
# retain3 = 0
# drivingOverTime = 0 #当天累计驾驶超时
# stoppingOverTime = 0 #超时停车
# InOutArea = 0 #进出区域
# InOutRouting = 0 #进出路线
# drivingLongOrShort = 0 #路段行驶时间不足/过长
# routingDivergeAlarm = 0 #路线偏离报警
# VSSTrouble = 0 #车辆 VSS 故障
# oilException = 0 #车辆油量异常
# carLost = 0 #车辆被盗(通过车辆防盗器)
# illegalFire = 0 #车辆非法点火
# illegalMoving = 0 #车辆非法位移(拖车告警)
# collisionAlarm = 0 #碰撞预警
# rollOverAlarm = 0 #侧翻预警
# illegalOpenDoor = 0 #非法开门报警(终端未设置区域时, 不判断非法开门)
data = emergencyAlarm + overspeedAlarm + fatigueDriving + dangerAlarm + GNSSTrouble + GNSSAntennaeLost
data = data + GNSSAntennaeShortOut + TerminalMainPowerLackVoltage + TerminalMainPowerLostConnect + TerMinalLCDTrouble
data = data + TTSTrouble + cameraTrouble + ICTrouble + speedEarlyWarning + fatigueDrivingearlyWarning
data = data + retain1 + retain2 + retain3 + drivingOverTime + stoppingOverTime
data = data + InOutArea + InOutRouting + drivingLongOrShort + routingDivergeAlarm + VSSTrouble
data = data + oilException + carLost + illegalFire + illegalMoving + collisionAlarm
data = data + rollOverAlarm + illegalOpenDoor
dataHex = self.int2hexStringByBytes(data,4)
return dataHex
#######################################################
# 获取状态
#######################################################
def getStatus(self):
ACCStatus = 1 #0:ACC 关;1: ACC 开 (1)
locationStatus = 2 #0:未定位;1:定位 (2)
latitudeStatus = 4 #0:北纬;1:南纬 (4)
longitudeStatus = 0 #0:东经;1:西经 (8)
runStatus = 0 #0:运营状态;1:停运状态 (16)
isLocationEncrypt = 0 #0:经纬度未经保密插件加密;1:经纬度已经保密插件加密 (32)
retain6_7 = 0
# 00:空车;01:半载;10:保留;11:满载(0 , 256 ,512 , 768)
#(可用于客车的空、重车及货车的空载、满载状态表示,人工输入或传感器 获取)
isFull = 256
oilRouteStatus = 0 #0:车辆油路正常;1:车辆油路断开 (1024)
powerStatus = 0 #0:车辆电路正常;1:车辆电路断开 (2048)
doorLockStatus = 0 #0:车门解锁;1:车门加锁 (4096)
frontDoor = 0 #0:门 1 关;1:门 1 开(前门) (8192)
middleDoor = 0 #0:门 2 关;1:门 2 开(中门) (16384)
backDoor = 0 #0:门 3 关;1:门 3 开(后门) (32768)
drivingDoor = 0 #0:门 4 关;1:门 4 开(驾驶席门) (65536)
otherDoor = 0 #0:门 5 关;1:门 5 开(自定义) (131072)
GPSStatus = 262144 #0:未使用 GPS 卫星进行定位;1:使用 GPS 卫星进行定位 (262144)
beidouStatus = 524288 #0:未使用北斗卫星进行定位;1:使用北斗卫星进行定位 (524288)
GLONSSStatus = 1048576 #0:未使用 GLONASS 卫星进行定位;1:使用 GLONASS 卫星进行定位 (1048576)
GalileoStatus = 0 #0:未使用 Galileo 卫星进行定位;1:使用 Galileo 卫星进行定位 (2097152)
retain22_31 = 0
data = ACCStatus + locationStatus + latitudeStatus + longitudeStatus + runStatus
data = data + isLocationEncrypt + retain6_7 + isFull + oilRouteStatus + powerStatus
data = data + doorLockStatus + frontDoor + middleDoor + backDoor + drivingDoor
data = data + otherDoor + GPSStatus + beidouStatus + GLONSSStatus + GalileoStatus
data = data + retain22_31
dataHex = self.int2hexStringByBytes(data,4)
return dataHex
if __name__ == "__main__":
# print(Location_msg().getAlarmFlag())
# print(Location_msg().getInfoTime())
# print(Location_msg().generateMsg())
# lati = Location_msg().getLatitude(29.40268)
# print(lati)
# print(int("01c329ed",16) / 1000000)
# print(int("0659dec5", 16) / 1000000)
print(Location_msg().getLocationBaseInfo_random())
#encoding:utf-8
import datetime
import random
import time
'''
定义消息协议类的基类
'''
class MessageBase():
def __init__(self):
self.IDENTIFY = "7e" #标识位
self.phoneNum = 201912000000
def setPhoneNum(self,data):
self.phoneNum = data
#######################################################
# 生成一条完整的消息
#######################################################
def generateMsg(self):
msg = ""
msgHeader = self.getMsgHeader()
msgBody = self.getMsgBody()
checkCode = self.getCheckCode(msgHeader + msgBody)
msg = msg + self.IDENTIFY
info = msgHeader + msgBody + checkCode
info = self.replace7e7d(info)
msg = msg + info
msg = msg + self.IDENTIFY
return msg
#######################################################
# 获取消息头
#######################################################
def getMsgHeader(self):
msgID = self.int2hexStringByBytes(102,2) #消息id
subPkg = 0
msgBodyProperty = self.getMsgBodyProperty(subPkg=subPkg) #消息体属性
phoneNum = self.int2BCD(self.phoneNum) #终端手机号
msgWaterCode = self.int2hexStringByBytes(1) #消息流水号
if subPkg != 8192:
subPkgContent = "" #消息包封装项
else:
subPkgContent = self.getMsgPackage()
data = msgID + msgBodyProperty + phoneNum + msgWaterCode + subPkgContent
return data
#获取消息头,针对图形界面,可传递参数
def getMsgHeader_GUI(self,msgID,phoneNum,msgWaterCode,encryptionType,subPkg): #消息id
msgID = msgID
subPkg = subPkg
msgBodyProperty = self.getMsgBodyProperty_GUI(msgBodyLen=int(len(self.getMsgBody()) / 2),encryptionType=encryptionType,subPkg=subPkg) #消息体属性
phoneNum = self.int2BCD(phoneNum) #终端手机号
msgWaterCode = self.int2hexStringByBytes(msgWaterCode,2) #消息流水号
if subPkg != 8192:
subPkgContent = "" #消息包封装项
else:
subPkgContent = self.getMsgPackage()
data = msgID + msgBodyProperty + phoneNum + msgWaterCode + subPkgContent
return data
#获取消息体属性
def getMsgBodyProperty(self,msgBodyLen=128,encryptionType=0,subPkg=0):
if msgBodyLen >= 512:
raise RuntimeError('消息体长度超长!')
msgBodyLen = msgBodyLen #消息体长度
encryptionType = encryptionType #加密方式
subPkg = subPkg #分包
retain = 0 #保留位
data = msgBodyLen + encryptionType + subPkg + retain
dataHex = self.int2hexStringByBytes(data,2)
return dataHex
#获取消息体属性,针对图形界面,可传递参数
def getMsgBodyProperty_GUI(self,msgBodyLen=128,encryptionType=0,subPkg=0):
if msgBodyLen >= 512:
raise RuntimeError('消息体长度超长!')
msgBodyLen = msgBodyLen #消息体长度
encryptionType = encryptionType #加密方式
subPkg = subPkg #分包
retain = 0 #保留位
data = msgBodyLen + encryptionType + subPkg + retain
dataHex = self.int2hexStringByBytes(data,2)
return dataHex
#获取消息封装项
def getMsgPackage(self):
pkgCounts = 2 #消息报包总数
pkgCountsHex = self.int2hexStringByBytes(2,2)
pkgNumsHex = ""
for i in range(0,pkgCounts):
pkgNum = i
dataHex = self.int2hexStringByBytes(pkgNum,2)
pkgNumsHex = pkgNumsHex + dataHex
msgPackage = pkgCountsHex + pkgNumsHex
return msgPackage
#######################################################
# 获取消息体
#######################################################
def getMsgBody(self):
return ""
#######################################################
# 获取校验码
#######################################################
def getCheckCode(self,data="aa"):
if len(data) % 2 == 1:
raise RuntimeError('数据段错误!')
start = data[0:2]
tmp = int(start,16)
for i in range(2,len(data),2):
tmp = tmp ^ int(data[i:i + 2],16)
dataHex = self.int2hexStringByBytes(tmp)
return dataHex
#######################################################
# 替换消息中的7e7d字符
#######################################################
def replace7e7d(self,data):
# data = data.replace("7d","7d01")
# data = data.replace("7e","7d02")
tmpR = data
tmp = tmpR[0:2]
tmpA = tmpR[0:2]
tmpR = tmpR[2:]
data = ""
while tmpA != "":
if tmp == "7d":
tmp = "7d01"
elif tmp == "7e":
tmp = "7d02"
data = data + tmp
tmp = tmpR[0:2]
tmpA = tmpR[0:2]
tmpR = tmpR[2:]
return data
#######################################################
# 字符串转16进制
#######################################################
def str2Hex(self,data):
dataHex = ""
tem = ""
for i in data:
tem = ord(i)
dataHex += hex(tem)[2:]
return dataHex
#######################################################
# 16进制转字符串
#######################################################
def hex2Str(self,data):
theStr = ""
while data != "":
tmp = data[:2]
data = data[2:]
theStr = theStr + chr(int(tmp,16))
return theStr
#####################################################
# 将字符串转换为对应的ascii值数组
#####################################################
def str2Ascsii(self,data):
asciiArr = []
for i in range(0, len(data)):
asciiValue = ord(data[i])
asciiArr.append(asciiValue)
return asciiArr
####################################################
# 将整数转换为有符号的整数
#####################################################
def num2signedNum(self,num):
return num & 0xff
#####################################################
# 数字转换为16进制字符串,通过传入字节数可自动补0
# 传入数据格式所占字节数
#####################################################
def int2hexStringByBytes(self, num,bytescount=1):
hexStr = hex(num)[2:]
while len(hexStr) < (bytescount * 2):
hexStr = "0" + hexStr
return hexStr
####################################################
# 将10进制转换位8421码
#####################################################
def int2BCD(self,data,bytescount=6):
data = str(data)
while len(data) < bytescount * 2:
data = "0" + data
return data
#######################################################
# 获取UTC时间转换位BCD格式
#######################################################
def getBCDTime(self,data="2020-02-04 18:57:04"):
now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
data = data
data = data.replace("-","")
data = data.replace(" ","")
data = data.replace(":","")
data = data[2:]
data = self.int2BCD(int(data))
return data
#######################################################
# 字符串转换为GBK的16进制
#######################################################
def GBKString2Hex(self,data):
data = str(data.encode("gbk"))
dataHex = self.str2Hex(data[2:len(data) - 1])
return dataHex
#######################################################
# 16进制转换为GBK字符串
#######################################################
def hex2GBKString(self,dataHex):
dataStr = self.hex2Str(dataHex)
data = bytes(map(ord,str(dataStr)))
data = data.decode("gbk")
return data
#######################################################
# 获取一个随机数,也可以指定获取数组中的随机字符串
#######################################################
def getRandomNum(self,s=1,e=1,intArr=[],mult=0):
if intArr == []:
data = random.randint(s, e)
else:
if mult == 0:
if type(intArr[0]) == int:
data = int(random.choice(intArr))
elif type(intArr[0]) == str:
data = random.choice(intArr)
else:
if type(intArr[0]) == int:
if len(intArr) < mult:
raise RuntimeError('个数超过数组长度!')
temp = []
data = 0
for i in range(0,mult):
num = int(random.choice(intArr))
if num in temp:
# num = int(random.choice(intArr))
num = 0
temp.append(num)
data = data + num
elif type(intArr[0]) == str:
if len(intArr) < mult:
raise RuntimeError('个数超过数组长度!')
temp = []
data = ""
for i in range(0,mult):
num = random.choice(intArr)
if num in temp:
# num = int(random.choice(intArr))
num = "0"
temp.append(num)
data = data + num
return data
#######################################################
# 获取一个随机字符串
#######################################################
def getRandomStr(self,counts,strs=""):
if strs == "":
data = random.sample("0123456789abcdefghijkmlnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-", counts)
else:
data = []
for s in range(0,counts):
data.append(random.choice(strs))
temp = ""
for ch in data:
temp = temp +ch
return temp
#######################################################
# 获取随机时间
# type:0、获取年月日时分秒 1、获取年月日 2、获取时分秒
#######################################################
def getRandomDate(self,s=631123200,e=1577808000,type=0):
timeStamp = random.randint(s, e)
timeArray = time.localtime(timeStamp)
if type == 0:
theTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
elif type == 1:
theTime = time.strftime("%Y-%m-%d", timeArray)
elif type == 2:
theTime = time.strftime("%H:%M:%S", timeArray)
return theTime
if __name__ == "__main__":
# print(MessageBase().str2Hex("uvwxyz"))
# print(MessageBase().str2Ascsii("uvwxyz"))
# print(MessageBase().int2hexStringByBytes(220400566542345564784802,20))
# print(MessageBase().str2Hex("a865h643gfdj64fd7432"))
# print(MessageBase().hex2Str("61383635683634336766646a3634666437343332"))
# print(MessageBase().GBKString2Hex("KZP200_V201001"))
# print(MessageBase().hex2GBKString("4b5a503230305f56323031303031"))
# print(MessageBase().str2Hex("\xd3\xe5B23CX"))
# print(MessageBase().getMsgBodyProperty())
# print(MessageBase().int2BCD(13146201117))
# print(MessageBase().getCheckCode("8001000501314620111800000000000200"))
# print(MessageBase().getMsgHeader())
# print(MessageBase().generateMsg())
# print(MessageBase().GBKString2Hex("渝B23CX"))
# print(MessageBase().hex2GBKString("5c7864335c7865354232334358"))
# print(MessageBase().int2BCD(123456789012345,10))
# print(MessageBase().getRandomNum(3000,5000,[2,4,6,8,10,12],4))
# print(MessageBase().getRandomStr(10))
print(MessageBase().replace7e7d("807d007e01314620111800000000000200"))
print(MessageBase().replace7e7d("87d107e501314620111800000000000200"))
#encoding:utf-8
'''
定义终端心跳消息
'''
from lib.Mnew.MessageBase import MessageBase
class TerminalHeartbeat_msg(MessageBase):
def __init__(self):
super().__init__() #不执行该方法,无法使用父类里面定义的属性
self.phoneNum = 201912000000
def setPhoneNum(self, data):
self.phoneNum = data
#######################################################
# 生成一条完整的消息
#######################################################
def generateMsg(self):
msg = ""
msgHeader = self.getMsgHeader()
msgBody = self.getMsgBody()
checkCode = self.getCheckCode(msgHeader + msgBody)
msg = msg + self.IDENTIFY
info = msgHeader + msgBody + checkCode
info = self.replace7e7d(info)
msg = msg + info
msg = msg + self.IDENTIFY
return msg
# 生成一条完整的消息,针对图形界面,可传递参数
def generateMsg_GUI(self,msgID="0002",phoneNum="13146201119",msgWaterCode=1,encryptionType=0,subPkg=0):
msg = ""
msgHeader = self.getMsgHeader_GUI(msgID,phoneNum,msgWaterCode,encryptionType,subPkg)
msgBody = self.getMsgBody()
checkCode = self.getCheckCode(msgHeader + msgBody)
msg = msg + self.IDENTIFY
info = msgHeader + msgBody + checkCode
info = self.replace7e7d(info)
msg = msg + info
msg = msg + self.IDENTIFY
return msg
# 生成一条完整的消息,数据随机产生
def generateMsg_random(self):
msgID="0002"
phoneNum=self.getRandomStr(11,"0123456789")
msgWaterCode=self.getRandomNum(1,65535)
encryptionType=0
subPkg=self.getRandomNum(intArr=[0,8192],mult=1)
msg = ""
msgHeader = self.getMsgHeader_GUI(msgID, phoneNum, msgWaterCode, encryptionType, subPkg)
msgBody = self.getMsgBody()
checkCode = self.getCheckCode(msgHeader + msgBody)
msg = msg + self.IDENTIFY
info = msgHeader + msgBody + checkCode
info = self.replace7e7d(info)
msg = msg + info
msg = msg + self.IDENTIFY
return msg
#######################################################
# 获取消息体
#######################################################
def getMsgBody(self):
msg = ""
return msg
#######################################################
# 获取消息头
#######################################################
def getMsgHeader(self):
# msgID = self.int2hexStringByBytes(102,2) #消息id
msgID = "0002"
subPkg = 0
msgBodyProperty = self.getMsgBodyProperty(msgBodyLen=int(len(self.getMsgBody()) / 2),subPkg=subPkg) #消息体属性
phoneNum = self.int2BCD(self.phoneNum) #终端手机号
msgWaterCode = self.int2hexStringByBytes(6,2) #消息流水号
if subPkg != 8192:
subPkgContent = "" #消息包封装项
else:
subPkgContent = self.getMsgPackage()
data = msgID + msgBodyProperty + phoneNum + msgWaterCode + subPkgContent
return data
#获取消息体属性
def getMsgBodyProperty(self,msgBodyLen=128,encryptionType=0,subPkg=0):
if msgBodyLen >= 512:
raise RuntimeError('消息体长度超长!')
msgBodyLen = msgBodyLen #消息体长度
encryptionType = encryptionType #加密方式
subPkg = subPkg #分包
retain = 0 #保留位
data = msgBodyLen + encryptionType + subPkg + retain
dataHex = self.int2hexStringByBytes(data,2)
return dataHex
#获取消息体属性,针对图形界面,可传递参数
def getMsgBodyProperty_GUI(self,msgBodyLen=128,encryptionType=0,subPkg=0):
if msgBodyLen >= 512:
raise RuntimeError('消息体长度超长!')
msgBodyLen = msgBodyLen #消息体长度
encryptionType = encryptionType #加密方式
subPkg = subPkg #分包
retain = 0 #保留位
data = msgBodyLen + encryptionType + subPkg + retain
dataHex = self.int2hexStringByBytes(data,2)
return dataHex
if __name__ == "__main__":
print(TerminalHeartbeat_msg().generateMsg())
print(TerminalHeartbeat_msg().getMsgBodyProperty())
\ No newline at end of file
#encoding:utf-8
'''
定义终端注册消息
'''
from lib.Mnew.MessageBase import MessageBase
class TerminalRegister_msg(MessageBase):
def __init__(self):
super().__init__() #不执行该方法,无法使用父类里面定义的属性
self.phoneNum = 201912000000
def setPhoneNum(self, data):
self.phoneNum = data
#######################################################
# 生成一条完整的消息
#######################################################
def generateMsg(self):
msg = ""
msgHeader = self.getMsgHeader()
msgBody = self.getMsgBody()
checkCode = self.getCheckCode(msgHeader + msgBody)
msg = msg + self.IDENTIFY
info = msgHeader + msgBody + checkCode
info = self.replace7e7d(info)
msg = msg + info
msg = msg + self.IDENTIFY
return msg
# 生成一条完整的消息,针对图形界面,可传递参数
def generateMsg_GUI(self,msgID="0100",phoneNum="13146201119",msgWaterCode=1,encryptionType=0,subPkg=0,provinceId=50,\
countyId=103,manufacturerId="11010",terminalType="a865h643gfdj64fd7432",terminalId="H6uyt08", \
licencePlateColor=1,carSign="渝B23CX"):
msg = ""
msgHeader = self.getMsgHeader_GUI(msgID,phoneNum,msgWaterCode,encryptionType,subPkg)
msgBody = self.getMsgBody_GUI(provinceId,countyId,manufacturerId,terminalType,terminalId,licencePlateColor,carSign)
checkCode = self.getCheckCode(msgHeader + msgBody)
msg = msg + self.IDENTIFY
info = msgHeader + msgBody + checkCode
info = self.replace7e7d(info)
msg = msg + info
msg = msg + self.IDENTIFY
return msg
# 生成一条完整的消息,数据随机产生
def generateMsg_random(self):
msgID = "0100"
phoneNum = self.getRandomStr(11, "0123456789")
msgWaterCode = self.getRandomNum(1, 65535)
encryptionType = 0
subPkg = self.getRandomNum(intArr=[0, 8192])
provinceId = self.getRandomNum(10,99)
countyId = self.getRandomNum(100,990)
manufacturerId = self.getRandomStr(5,"0123456789")
terminalType = self.getRandomStr(20)
terminalId = self.getRandomStr(7)
licencePlateColor = self.getRandomNum(intArr=[1,2,3,4,9])
carSign = self.getRandomStr(5)
msg = ""
msgHeader = self.getMsgHeader_GUI(msgID, phoneNum, msgWaterCode, encryptionType, subPkg)
msgBody = self.getMsgBody_GUI(provinceId, countyId, manufacturerId, terminalType, terminalId, licencePlateColor,
carSign)
checkCode = self.getCheckCode(msgHeader + msgBody)
msg = msg + self.IDENTIFY
info = msgHeader + msgBody + checkCode
info = self.replace7e7d(info)
msg = msg + info
msg = msg + self.IDENTIFY
return msg
#######################################################
# 获取消息体
#######################################################
def getMsgBody(self):
msg = ""
# msgNums = self.int2hexStringByBytes(1,2)
# msgNumber = self.int2hexStringByBytes(1,2)
#省域 ID (标示终端安装车辆所在的省域,0 保留,由平台取默认值。省 域 ID 采用 GB/T 2260 中规定的行政区划代 码六位中前两)
provinceId = self.int2hexStringByBytes(50,2)
#市县域 ID
countyId = self.int2hexStringByBytes(103,2)
#制造商 ID (5 个字节,终端制造商编码)
manufacturerId = self.str2Hex("man03")
#终端型号 (20 个字节,此终端型号由制造商自行定义,位数不足时,后 补“0X00”。)
terminalType = self.str2Hex("a865h643gfdj64fd7432")
#终端 ID (7 个字节,由大写字母和数字组成,此终端 ID 由制造商自行 定义,位数不足时,后补“0X00”)
terminalId = self.str2Hex("H6uyt08")
#车牌颜色 (车牌颜色,按照 JT/T415-2006 的 5.4.12。未上牌时,取值 为 0) 1:蓝色 2:黄色 3:黑色 4:白色 9:其他
licencePlateColor = self.int2hexStringByBytes(2)
#车辆标识 (车牌颜色为 0 时,表示车辆 VIN;否则,表示公安交通管理 部门颁发的机动车号牌)
carSign = self.GBKString2Hex("渝B23CX")
# msg = msg + msgNums + msgNumber
msg = msg + provinceId + countyId + manufacturerId + terminalType + terminalId + licencePlateColor + carSign
return msg
# 获取消息体,针对图形界面,可传递参数
def getMsgBody_GUI(self,provinceId=50,countyId=103,manufacturerId="11010",terminalType="a865h643gfdj64fd7432",terminalId="H6uyt08", \
licencePlateColor=1,carSign="渝B23CX"):
msg = ""
# msgNums = self.int2hexStringByBytes(1,2)
# msgNumber = self.int2hexStringByBytes(1,2)
#省域 ID (标示终端安装车辆所在的省域,0 保留,由平台取默认值。省 域 ID 采用 GB/T 2260 中规定的行政区划代 码六位中前两)
provinceId = self.int2hexStringByBytes(provinceId,2)
# 市县域 ID
countyId = self.int2hexStringByBytes(countyId, 2)
#制造商 ID (5 个字节,终端制造商编码)
manufacturerId = self.str2Hex(manufacturerId)
#终端型号 (20 个字节,此终端型号由制造商自行定义,位数不足时,后 补“0X00”。)
terminalType = self.str2Hex(terminalType)
#终端 ID (7 个字节,由大写字母和数字组成,此终端 ID 由制造商自行 定义,位数不足时,后补“0X00”)
terminalId = self.str2Hex(terminalId)
#车牌颜色 (车牌颜色,按照 JT/T415-2006 的 5.4.12。未上牌时,取值 为 0) 1:蓝色 2:黄色 3:黑色 4:白色 9:其他
licencePlateColor = self.int2hexStringByBytes(licencePlateColor)
#车辆标识 (车牌颜色为 0 时,表示车辆 VIN;否则,表示公安交通管理 部门颁发的机动车号牌)
carSign = self.GBKString2Hex(carSign)
# msg = msg + msgNums + msgNumber
msg = msg + provinceId + countyId + manufacturerId + terminalType + terminalId + licencePlateColor + carSign
return msg
#######################################################
# 获取消息头
#######################################################
def getMsgHeader(self):
# msgID = self.int2hexStringByBytes(102,2) #消息id
msgID = "0100"
msgBodyProperty = self.getMsgBodyProperty(int(len(self.getMsgBody()) / 2)) #消息体属性
phoneNum = self.int2BCD(self.phoneNum) #终端手机号
msgWaterCode = self.int2hexStringByBytes(1,2) #消息流水号
subPkgContent = "" #消息包封装项
data = msgID + msgBodyProperty + phoneNum + msgWaterCode + subPkgContent
return data
#获取消息体属性
def getMsgBodyProperty(self,msgBodyLen=128,encryptionType=0,subPkg=0):
if msgBodyLen >= 512:
raise RuntimeError('消息体长度超长!')
msgBodyLen = msgBodyLen #消息体长度
encryptionType = encryptionType #加密方式
subPkg = subPkg #分包
retain = 0 #保留位
data = msgBodyLen + encryptionType + subPkg + retain
dataHex = self.int2hexStringByBytes(data,2)
return dataHex
#获取消息体属性,针对图形界面,可传递参数
def getMsgBodyProperty_GUI(self,msgBodyLen=128,encryptionType=0,subPkg=0):
if msgBodyLen >= 512:
raise RuntimeError('消息体长度超长!')
msgBodyLen = msgBodyLen #消息体长度
encryptionType = encryptionType #加密方式
subPkg = subPkg #分包
retain = 0 #保留位
data = msgBodyLen + encryptionType + subPkg + retain
dataHex = self.int2hexStringByBytes(data,2)
return dataHex
if __name__ == "__main__":
print(TerminalRegister_msg().generateMsg())
\ No newline at end of file
#encoding:utf-8
'''
定义终端版本信息主动上报
'''
from lib.Mnew.MessageBase import MessageBase
class TerminalVersionInfo_msg(MessageBase):
def __init__(self):
super().__init__() #不执行该方法,无法使用父类里面定义的属性
self.phoneNum = 201912000000
def setPhoneNum(self, data):
self.phoneNum = data
#######################################################
# 生成一条完整的消息
#######################################################
def generateMsg(self):
msg = ""
msgHeader = self.getMsgHeader()
msgBody = self.getMsgBody()
checkCode = self.getCheckCode(msgHeader + msgBody)
msg = msg + self.IDENTIFY
info = msgHeader + msgBody + checkCode
info = self.replace7e7d(info)
msg = msg + info
msg = msg + self.IDENTIFY
return msg
# 生成一条完整的消息,针对图形界面,可传递参数
def generateMsg_GUI(self,msgID="0205",phoneNum="13146201119",msgWaterCode=1,encryptionType=0,subPkg=0, \
softwareVersion="KZP200_V201001", softwareVersionDate="2020-02-10", CPUId="CPU-12345678",GMSType="GMS-TYPE-123456", \
GMS_IMEI="GMS_IMEI_123456", SIM_IMSI="SIM_13146201119", SIM_ICCID="SIM_ICCID13146201119",carType=22, VIN="VIN_1234567891234", \
totalMileage=389000, totalOilExpend=420000
):
msg = ""
msgHeader = self.getMsgHeader_GUI(msgID,phoneNum,msgWaterCode,encryptionType,subPkg)
msgBody = self.getMsgBody_GUI(softwareVersion,softwareVersionDate,CPUId,GMSType,GMS_IMEI,SIM_IMSI,SIM_ICCID,carType,VIN,\
totalMileage,totalOilExpend)
checkCode = self.getCheckCode(msgHeader + msgBody)
msg = msg + self.IDENTIFY
info = msgHeader + msgBody + checkCode
info = self.replace7e7d(info)
msg = msg + info
msg = msg + self.IDENTIFY
return msg
# 生成一条完整的消息,数据随机产生
def generateMsg_random(self):
msgID = "0205"
phoneNum = self.getRandomStr(11, "0123456789")
msgWaterCode = self.getRandomNum(1, 65535)
encryptionType = 0
subPkg = self.getRandomNum(intArr=[0, 8192])
softwareVersion = "KZP200_" + self.getRandomStr(7)
softwareVersionDate = self.getRandomDate(type=1)
CPUId = "CPU-" + self.getRandomStr(8,"0123456789")
GMSType = "GMS-TYPE-" + self.getRandomStr(6,"0123456789")
GMS_IMEI = "GMS_IMEI_" + self.getRandomStr(6,"0123456789")
SIM_IMSI = "SIM_" + self.getRandomStr(11,"0123456789")
SIM_ICCID = "SIM_ICCID" + self.getRandomStr(11,"0123456789")
carType = self.getRandomNum(0,65535)
VIN = "VIN_" + self.getRandomStr(13,"0123456789")
totalMileage = self.getRandomNum(30000,6000000)
totalOilExpend = self.getRandomNum(30000,6000000)
msg = ""
msgHeader = self.getMsgHeader_GUI(msgID, phoneNum, msgWaterCode, encryptionType, subPkg)
msgBody = self.getMsgBody_GUI(softwareVersion, softwareVersionDate, CPUId, GMSType, GMS_IMEI, SIM_IMSI,
SIM_ICCID, carType, VIN, \
totalMileage, totalOilExpend)
checkCode = self.getCheckCode(msgHeader + msgBody)
msg = msg + self.IDENTIFY
info = msgHeader + msgBody + checkCode
info = self.replace7e7d(info)
msg = msg + info
msg = msg + self.IDENTIFY
return msg
#######################################################
# 获取消息体
#######################################################
def getMsgBody(self):
msg = ""
softwareVersion = self.GBKString2Hex("KZP200_V201001") #软件版本号
softwareVersionDate = self.GBKString2Hex("2020-02-10") #终端版本日期
CPUId = self.str2Hex("CPU-12345678") #cpuId
GSMType = self.GBKString2Hex("GSM-TYPE-123456") #GSM型号
GSM_IMEI = self.GBKString2Hex("GSM_IMEI_123456") #GSM IMEI 号
SIM_IMSI = self.GBKString2Hex("SIM_13146201119") #终端 SIM 卡 IMSI 号
SIM_ICCID = self.GBKString2Hex("SIM_ICCID13146201119") #终端 SIM 卡 ICCID 号
carType = self.int2hexStringByBytes(22,2) #车系车型 ID
VIN = self.GBKString2Hex("VIN_1234567891234") #汽车 VIN 码
totalMileage = self.int2hexStringByBytes(389000,4) #装上终端后车辆累计总里程或车辆仪表里程(单位米)
totalOilExpend = self.int2hexStringByBytes(420000,4) #装上终端后车辆累计总耗油量(ml)
msg = msg + softwareVersion + softwareVersionDate + CPUId + GSMType + GSM_IMEI
msg = msg + SIM_IMSI + SIM_ICCID + carType + VIN + totalMileage
msg = msg + totalOilExpend
return msg
# 生成一条完整的消息,针对图形界面,可传递参数
def getMsgBody_GUI(self,softwareVersion="KZP200_V201001",softwareVersionDate="2020-02-10",CPUId="CPU-12345678",GMSType="GMS-TYPE-123456",\
GMS_IMEI="GMS_IMEI_123456",SIM_IMSI="SIM_13146201119",SIM_ICCID="SIM_ICCID13146201119",carType=22,VIN="VIN_1234567891234",\
totalMileage=389000,totalOilExpend=420000):
msg = ""
softwareVersion = self.GBKString2Hex(softwareVersion) #软件版本号
softwareVersionDate = self.GBKString2Hex(softwareVersionDate) #终端版本日期
CPUId = self.str2Hex(CPUId) #cpuId
GMSType = self.GBKString2Hex(GMSType) #GMS型号
GMS_IMEI = self.GBKString2Hex(GMS_IMEI) #GSM IMEI 号
SIM_IMSI = self.GBKString2Hex(SIM_IMSI) #终端 SIM 卡 IMSI 号
SIM_ICCID = self.GBKString2Hex(SIM_ICCID) #终端 SIM 卡 ICCID 号
carType = self.int2hexStringByBytes(carType,2) #车系车型 ID
VIN = self.GBKString2Hex(VIN) #汽车 VIN 码
totalMileage = self.int2hexStringByBytes(totalMileage,4) #装上终端后车辆累计总里程或车辆仪表里程(单位米)
totalOilExpend = self.int2hexStringByBytes(totalOilExpend,4) #装上终端后车辆累计总耗油量(ml)
msg = msg + softwareVersion + softwareVersionDate + CPUId + GMSType + GMS_IMEI
msg = msg + SIM_IMSI + SIM_ICCID + carType + VIN + totalMileage
msg = msg + totalOilExpend
return msg
#######################################################
# 获取消息头
#######################################################
def getMsgHeader(self):
# msgID = self.int2hexStringByBytes(102,2) #消息id
msgID = "0205"
subPkg = 0
msgBodyProperty = self.getMsgBodyProperty(msgBodyLen=int(len(self.getMsgBody()) / 2),subPkg=subPkg) #消息体属性
phoneNum = self.int2BCD(self.phoneNum) #终端手机号
msgWaterCode = self.int2hexStringByBytes(1,2) #消息流水号
if subPkg != 8192:
subPkgContent = "" #消息包封装项
else:
subPkgContent = self.getMsgPackage()
data = msgID + msgBodyProperty + phoneNum + msgWaterCode + subPkgContent
return data
#获取消息体属性
def getMsgBodyProperty(self,msgBodyLen=128,encryptionType=0,subPkg=0):
if msgBodyLen >= 512:
raise RuntimeError('消息体长度超长!')
msgBodyLen = msgBodyLen #消息体长度
encryptionType = encryptionType #加密方式
subPkg = subPkg #分包
retain = 0 #保留位
data = msgBodyLen + encryptionType + subPkg + retain
dataHex = self.int2hexStringByBytes(data,2)
return dataHex
if __name__ == "__main__":
pass
\ No newline at end of file
#encoding:utf-8
'''
定义外设数据项
'''
from lib.Mnew.MessageBase import MessageBase
class AlarmEvent_data(MessageBase):
def __init__(self):
super().__init__()
pass
#####################################################
# 创建报警事件数据
#####################################################
def generateAlarmEvent_data(self):
data = ""
ignition = "0001" + self.int2hexStringByBytes(0) #点火上报
flameout = "0002" + self.int2hexStringByBytes(0) #熄火上报
setUpDefences = "0003" + self.int2hexStringByBytes(0) #设防上报
withdrawGarrision = "0004" + self.int2hexStringByBytes(0) #撤防上报
doorOpen = "0005" + self.int2hexStringByBytes(0) #车门打开
doorClose = "0006" + self.int2hexStringByBytes(0) #车门关闭
systemStart = "0007" + self.int2hexStringByBytes(0) #系统启动
trailCarAlarm = "0101" + self.int2hexStringByBytes(0) #拖车报警
locationTooLong = "0102" + self.int2hexStringByBytes(0) #定位过长报警
terminalPullOut = "0103" + self.int2hexStringByBytes(0) #终端拔出报警
terminalInsert = "0104" + self.int2hexStringByBytes(0) #终端插入报警
lowVoltage = "0105" + self.int2hexStringByBytes(0) #低电压报警
#怠速过长报警 附带信息见 表 C6EXT1
idlingSpeedOver = "0106" + self.int2hexStringByBytes(9) + self.getIdlingSpeedOver()
#超速报警 附带信息见 表 C6EXT2
overspeedAlarm = "0107" + self.int2hexStringByBytes(9) + self.getOverspeedAlarm()
#疲劳驾驶报警 附带信息见 表 C6EXT3
fatigueDriving = "0108" + self.int2hexStringByBytes(5) + self.getFatigueDriving()
#水温报警 附带信息见 表 C6EXT4
waterTemperatureAlarm = "0109" + self.int2hexStringByBytes(9) + self.getWaterTemperatureAlarm()
highSpeedNeutralGear = "010A" + self.int2hexStringByBytes(0) #高速空档滑行报警
oilExpendNotSurport = "010B" +self.int2hexStringByBytes(0) #油耗不支持报警
OBDNotSurport = "010C" + self.int2hexStringByBytes(0) #OBD 不支持报警
lowWaterTemperatureHighSpeed = "010D" +self.int2hexStringByBytes(0) #低水温高转速
buslineNotSleep = "010E" + self.int2hexStringByBytes(0) #总线不睡眠报警
illegalOpenDoor = "010f" + self.int2hexStringByBytes(0) #非法开门
illegalFire = "0110" + self.int2hexStringByBytes(0) #非法点火
rapidAccelerateAlarm = "0111" + self.int2hexStringByBytes(0) #急加速报警
sharpSlowdownAlarm = "0112" + self.int2hexStringByBytes(0) #急减速报警
sharpBendAlarm = "0113" + self.int2hexStringByBytes(0) #急拐弯报警
crashAlarm = "0114" + self.int2hexStringByBytes(0) #碰撞报警
rapidChangeLines = "0115" + self.int2hexStringByBytes(0) #急变道报警
# data = ignition
data = data + ignition + flameout + setUpDefences + withdrawGarrision + doorOpen
data = data + doorClose + systemStart + trailCarAlarm + locationTooLong + terminalPullOut
data = data + terminalInsert + lowVoltage + idlingSpeedOver + overspeedAlarm + fatigueDriving
data = data + waterTemperatureAlarm + highSpeedNeutralGear + oilExpendNotSurport + OBDNotSurport + lowWaterTemperatureHighSpeed
data = data + buslineNotSleep + illegalOpenDoor + illegalFire + rapidAccelerateAlarm + sharpSlowdownAlarm
data = data + sharpBendAlarm + crashAlarm + rapidChangeLines
return data
# 创建报警事件数据,数据随机产生
def generateAlarmEvent_data_random(self):
data = ""
ignition = "0001" + self.int2hexStringByBytes(0) #点火上报
flameout = "0002" + self.int2hexStringByBytes(0) #熄火上报
setUpDefences = "0003" + self.int2hexStringByBytes(0) #设防上报
withdrawGarrision = "0004" + self.int2hexStringByBytes(0) #撤防上报
doorOpen = "0005" + self.int2hexStringByBytes(0) #车门打开
doorClose = "0006" + self.int2hexStringByBytes(0) #车门关闭
systemStart = "0007" + self.int2hexStringByBytes(0) #系统启动
trailCarAlarm = "0101" + self.int2hexStringByBytes(0) #拖车报警
locationTooLong = "0102" + self.int2hexStringByBytes(0) #定位过长报警
terminalPullOut = "0103" + self.int2hexStringByBytes(0) #终端拔出报警
terminalInsert = "0104" + self.int2hexStringByBytes(0) #终端插入报警
lowVoltage = "0105" + self.int2hexStringByBytes(0) #低电压报警
#怠速过长报警 附带信息见 表 C6EXT1
idlingSpeedOver = "0106" + self.int2hexStringByBytes(9) + self.getIdlingSpeedOver_random()
#超速报警 附带信息见 表 C6EXT2
overspeedAlarm = "0107" + self.int2hexStringByBytes(9) + self.getOverspeedAlarm_random()
#疲劳驾驶报警 附带信息见 表 C6EXT3
fatigueDriving = "0108" + self.int2hexStringByBytes(5) + self.getFatigueDriving_random()
#水温报警 附带信息见 表 C6EXT4
waterTemperatureAlarm = "0109" + self.int2hexStringByBytes(9) + self.getWaterTemperatureAlarm_random()
highSpeedNeutralGear = "010A" + self.int2hexStringByBytes(0) #高速空档滑行报警
oilExpendNotSurport = "010B" +self.int2hexStringByBytes(0) #油耗不支持报警
OBDNotSurport = "010C" + self.int2hexStringByBytes(0) #OBD 不支持报警
lowWaterTemperatureHighSpeed = "010D" +self.int2hexStringByBytes(0) #低水温高转速
buslineNotSleep = "010E" + self.int2hexStringByBytes(0) #总线不睡眠报警
illegalOpenDoor = "010f" + self.int2hexStringByBytes(0) #非法开门
illegalFire = "0110" + self.int2hexStringByBytes(0) #非法点火
rapidAccelerateAlarm = "0111" + self.int2hexStringByBytes(0) #急加速报警
sharpSlowdownAlarm = "0112" + self.int2hexStringByBytes(0) #急减速报警
sharpBendAlarm = "0113" + self.int2hexStringByBytes(0) #急拐弯报警
crashAlarm = "0114" + self.int2hexStringByBytes(0) #碰撞报警
rapidChangeLines = "0115" + self.int2hexStringByBytes(0) #急变道报警
arr = []
arr.append(ignition)
arr.append(flameout)
arr.append(setUpDefences)
arr.append(withdrawGarrision)
arr.append(doorOpen)
arr.append(doorClose)
arr.append(systemStart)
arr.append(trailCarAlarm)
arr.append(locationTooLong)
arr.append(terminalPullOut)
arr.append(terminalInsert)
arr.append(lowVoltage)
arr.append(idlingSpeedOver)
arr.append(overspeedAlarm)
arr.append(fatigueDriving)
arr.append(waterTemperatureAlarm)
arr.append(highSpeedNeutralGear)
arr.append(oilExpendNotSurport)
arr.append(OBDNotSurport)
arr.append(lowWaterTemperatureHighSpeed)
arr.append(buslineNotSleep)
arr.append(illegalOpenDoor)
arr.append(illegalFire)
arr.append(rapidAccelerateAlarm)
arr.append(sharpSlowdownAlarm)
arr.append(sharpBendAlarm)
arr.append(crashAlarm)
arr.append(rapidChangeLines)
mult = self.getRandomNum(0, 28)
temp = []
for i in range(0, mult):
con = self.getRandomNum(intArr=arr, mult=1)
if con in temp:
con = ""
temp.append(con)
data = data + con
return data
#####################################################
# 获取怠速过长附带信息
#####################################################
def getIdlingSpeedOver(self):
#报警属性 1:报警触发(无下面的数据内容项)0:报警解除(有下面的数据内容项)
alarmType = self.int2hexStringByBytes(1)
#怠速持续时间 怠速持续的时间(含报警前的预判时间),单位为秒
idlingTimeOfDuration = self.int2hexStringByBytes(600,2)
#怠速耗油量 单位 mL
idlingOilExpend = self.int2hexStringByBytes(1200,2)
#怠速最高转速 单位 RPM
idlingEngineMaxSpeed = self.int2hexStringByBytes(5000,2)
#怠速最低转速 单位 RPM
idlingEngineMinSpeed = self.int2hexStringByBytes(500,2)
data = alarmType + idlingTimeOfDuration + idlingOilExpend + idlingEngineMaxSpeed + idlingEngineMinSpeed
return data
def getIdlingSpeedOver_random(self):
#报警属性 1:报警触发(无下面的数据内容项)0:报警解除(有下面的数据内容项)
alarmType = self.int2hexStringByBytes(self.getRandomNum(intArr=[0,1]))
#怠速持续时间 怠速持续的时间(含报警前的预判时间),单位为秒
idlingTimeOfDuration = self.int2hexStringByBytes(self.getRandomNum(0,65535),2)
#怠速耗油量 单位 mL
idlingOilExpend = self.int2hexStringByBytes(self.getRandomNum(0,65535),2)
#怠速最高转速 单位 RPM
idlingEngineMaxSpeed = self.int2hexStringByBytes(self.getRandomNum(0,65535),2)
#怠速最低转速 单位 RPM
idlingEngineMinSpeed = self.int2hexStringByBytes(self.getRandomNum(0,65535),2)
data = alarmType + idlingTimeOfDuration + idlingOilExpend + idlingEngineMaxSpeed + idlingEngineMinSpeed
return data
#####################################################
# 获取超速报警信息
#####################################################
def getOverspeedAlarm(self):
#报警属性 1 BYTE 1:报警触发(无下面的数据内容项) 0:报警解除(有下面的数据内容项)
alarmType = self.int2hexStringByBytes(0)
#超速持续时间 2 WORD 怠速持续的时间(含报警前的预判时间),单位为秒
overspeedTimeOfDuration = self.int2hexStringByBytes(700,2)
#最高车速 2 WORD 单位 0.1KM/H
maxSpeed = self.int2hexStringByBytes(145,2)
#平均车速 2 WORD 单位 0.1KM/H
averageSpeed = self.int2hexStringByBytes(70,2)
#超速行驶距离 2 WORD 单位米
overspeedDistance = self.int2hexStringByBytes(10000,2)
data = alarmType + overspeedTimeOfDuration + maxSpeed + averageSpeed + overspeedDistance
return data
def getOverspeedAlarm_random(self):
#报警属性 1 BYTE 1:报警触发(无下面的数据内容项) 0:报警解除(有下面的数据内容项)
alarmType = self.int2hexStringByBytes(self.getRandomNum(intArr=[0,1]))
#超速持续时间 2 WORD 怠速持续的时间(含报警前的预判时间),单位为秒
overspeedTimeOfDuration = self.int2hexStringByBytes(self.getRandomNum(0,65535),2)
#最高车速 2 WORD 单位 0.1KM/H
maxSpeed = self.int2hexStringByBytes(self.getRandomNum(0,65535),2)
#平均车速 2 WORD 单位 0.1KM/H
averageSpeed = self.int2hexStringByBytes(self.getRandomNum(0,65535),2)
#超速行驶距离 2 WORD 单位米
overspeedDistance = self.int2hexStringByBytes(self.getRandomNum(0,65535),2)
data = alarmType + overspeedTimeOfDuration + maxSpeed + averageSpeed + overspeedDistance
return data
#####################################################
# 获取疲劳驾驶报警附带信息
#####################################################
def getFatigueDriving(self):
#报警属性 1 BYTE 1:报警触发(无下面的数据内容项) 0:报警解除(有下面的数据内容项)
alarmType = self.int2hexStringByBytes(0)
#累计持续驾驶时间 4 DWORD 车辆点火行驶到报警解除的累计行驶时间,单位为秒
totalContinueDrivingTime = self.int2hexStringByBytes(21000,4)
data = alarmType + totalContinueDrivingTime
return data
def getFatigueDriving_random(self):
#报警属性 1 BYTE 1:报警触发(无下面的数据内容项) 0:报警解除(有下面的数据内容项)
alarmType = self.int2hexStringByBytes(self.getRandomNum(intArr=[0,1]))
#累计持续驾驶时间 4 DWORD 车辆点火行驶到报警解除的累计行驶时间,单位为秒
totalContinueDrivingTime = self.int2hexStringByBytes(self.getRandomNum(0,2147483648),4)
data = alarmType + totalContinueDrivingTime
return data
#####################################################
# 获取水温报警附带信息
#####################################################
def getWaterTemperatureAlarm(self):
#报警属性 1 BYTE 1:报警触发(无下面的数据内容项) 0:报警解除(有下面的数据内容项)
alarmType = self.int2hexStringByBytes(1)
#持续时长 4 DWORD 单位秒
timeOfDuration = self.int2hexStringByBytes(11000,4)
#最高温度 2 WORD 单位 0.1 度
maxTemperature = self.int2hexStringByBytes(700,2)
#平均温度 2 WORD 单位 0.1 度
averageTemperature = self.int2hexStringByBytes(55,2)
data = alarmType + timeOfDuration + maxTemperature + averageTemperature
return data
def getWaterTemperatureAlarm_random(self):
#报警属性 1 BYTE 1:报警触发(无下面的数据内容项) 0:报警解除(有下面的数据内容项)
alarmType = self.int2hexStringByBytes(self.getRandomNum(intArr=[0,1]))
#持续时长 4 DWORD 单位秒
timeOfDuration = self.int2hexStringByBytes(self.getRandomNum(0,2147483648),4)
#最高温度 2 WORD 单位 0.1 度
maxTemperature = self.int2hexStringByBytes(self.getRandomNum(0,2500),2)
#平均温度 2 WORD 单位 0.1 度
averageTemperature = self.int2hexStringByBytes(self.getRandomNum(0,1500),2)
data = alarmType + timeOfDuration + maxTemperature + averageTemperature
return data
if __name__ == "__main__":
print(AlarmEvent_data().generateAlarmEvent_data())
#encoding:utf-8
'''
定义安防状态信息
'''
from lib.Mnew.MessageBase import MessageBase
class CarSafeStatusInfo(MessageBase):
def __init__(self):
super().__init__()
pass
#####################################################
# 创建安防状态数据
#####################################################
def generateSecurityStatusData(self):
data = ""
statusCode = "ffffffffffffffffffff" #状态掩码
securityStatus = self.getSecurityStatusHex() #安全状态
doorStatus = self.getDoorStatusHex() #门状态
lockStatus = self.getLockStatusHex() #锁状态
windowStatus = self.getWindowStatusHex() #窗户状态
lightStatus = self.getLightStatusHex() #灯光状态
onoffStatusA = self.getOnoffStatusAHex() #开关状态A
onoffStatusB = self.getOnoffStatusBHex() #开关状态B
retain1 = "00" #预留
retain2 = "00" #预留
retain3 = "00" # 预留
data = data + statusCode + securityStatus + doorStatus + lockStatus + windowStatus + lightStatus + onoffStatusA + onoffStatusB + retain1 + retain2 + retain3
return data
#创建安防状态数据,数据随机产生
def generateSecurityStatusData_random(self):
data = ""
statusCode = "ffffffffffffffffffff" #状态掩码
securityStatus = self.getSecurityStatusHex_random() #安全状态
doorStatus = self.getDoorStatusHex_random() #门状态
lockStatus = self.getLockStatusHex_random() #锁状态
windowStatus = self.getWindowStatusHex_random() #窗户状态
lightStatus = self.getLightStatusHex_random() #灯光状态
onoffStatusA = self.getOnoffStatusAHex_random() #开关状态A
onoffStatusB = self.getOnoffStatusBHex_random() #开关状态B
retain1 = "00" #预留
retain2 = "00" #预留
retain3 = "00" # 预留
data = data + statusCode + securityStatus + doorStatus + lockStatus + windowStatus + lightStatus + onoffStatusA + onoffStatusB + retain1 + retain2 + retain3
return data
#####################################################
# 获取安全状态16进制数据
# 按照高位在前,低位在后的规则
#####################################################
def getSecurityStatusHex(self):
accStatus = 0 #acc状态,1:开 0:关
defenseStatus = 0 #设防撤防状态,2:设防 0:撤防
brakeStatus = 0 #脚刹状态,4:踩下 0:松开
acceleratorStatus = 0 #是否踩油门,8:踩下 0:松开
handBrakeStatus = 0 #手刹状态,16:拉起手刹 0:松开手刹
mainSafetyBelt = 0 #主驾驶安全带,32:插入安全带 0:松开安全带
subSafetyBelt = 0 #副驾驶安全带,64:插入安全带 0:松开安全带
retain = 0 #预留字段
val = accStatus +defenseStatus +brakeStatus +acceleratorStatus + handBrakeStatus + mainSafetyBelt + subSafetyBelt + retain
hexData = self.int2hexStringByBytes(val)
return hexData
def getSecurityStatusHex_random(self):
val = self.getRandomNum(intArr=[0,1,2,4,8,16,32,64],mult=7)
hexData = self.int2hexStringByBytes(val)
return hexData
#####################################################
# 获取门状态16进制数据
#####################################################
def getDoorStatusHex(self):
lfDoorStatus = 0 #左前门,1,:开 0:关
rfDoorStatus = 0 #右前门,2:开 0:关
lbDoorStatus = 0 #左后门,4:开 0:关
rbDoorStatus = 0 #右后门,8:开 0:关
trunk = 0 #后备箱,16:开 0:关
enginCover = 0 #发动机盖:32:开 0:关
retain1 = 0 #预留字段
retain2 = 0 #预留字段
val = lfDoorStatus + rfDoorStatus + lbDoorStatus +rbDoorStatus + trunk + enginCover + retain1 +retain2
hexData = self.int2hexStringByBytes(val)
return hexData
def getDoorStatusHex_random(self):
val = self.getRandomNum(intArr=[0,1,2,4,8,16,32],mult=6)
hexData = self.int2hexStringByBytes(val)
return hexData
#####################################################
# 获取锁状态16进制数据
#####################################################
def getLockStatusHex(self):
lfDoorLockStatus = 0 #左前门锁状态,1:开 0:关
rfDoorLockStatus = 0 #右前门锁状态,2:开 0:关
lbDoorLockStatus = 0 #左后门锁状态,4:开 0:关
rbDoorLockStatus = 0 #右后门锁状态,8:开 0:关
retain1 = 0
retain2 = 0
retain3 = 0
retain4 = 0
val = lfDoorLockStatus + rfDoorLockStatus + lbDoorLockStatus + rbDoorLockStatus + retain1 +retain2 + retain3 +retain4
hexData = self.int2hexStringByBytes(val)
return hexData
def getLockStatusHex_random(self):
val = self.getRandomNum(intArr=[0,1,2,4,8],mult=4)
hexData = self.int2hexStringByBytes(val)
return hexData
#####################################################
# 获取窗户状态16进制数据
#####################################################
def getWindowStatusHex(self):
lfWindowStatus = 0 #左前窗,1:开 0:关
rfWindowStatus = 0 #右前窗,2:开 0:关
lbWindowStatus = 0 # 左后窗,4:开 0:关
rbWindowStatus = 0 # 右后窗,8:开 0:关
topWindowStatus = 0 #天窗开关,16:开 0:关
lTurnLight = 0 #左转向灯,32:开 0:关
rTurnLight = 0 #右转向灯,64:开 0:关
readLight = 0 #阅读灯,128:开 0:关
val = lfWindowStatus + rfWindowStatus + lbWindowStatus + rbWindowStatus + topWindowStatus + lTurnLight + rTurnLight + readLight
hexData = self.int2hexStringByBytes(val)
return hexData
def getWindowStatusHex_random(self):
val = self.getRandomNum(intArr=[0,1,2,4,8,16,32,64,128],mult=8)
hexData = self.int2hexStringByBytes(val)
return hexData
#####################################################
# 获取灯光状态16进制数据
#####################################################
def getLightStatusHex(self):
lowHeadlight = 0 #近光灯,1:开 0:关
highHeadlight = 0 #远光灯,2:开 0:关
ffogLight = 0 #前雾灯,4:开 0:关
bfogLight = 0 #后雾灯,8:开 0:关
dangerLight = 0 #危险灯,16:开 0:关
backCarLight = 0 #倒车灯,32:开 0:关
autoLight = 0 #auto灯,64:开 0:关
widthLight = 0 #示宽灯,128:开 0:关
val = lowHeadlight + highHeadlight + ffogLight + bfogLight + dangerLight + backCarLight + autoLight + widthLight
hexData = self.int2hexStringByBytes(val)
return hexData
def getLightStatusHex_random(self):
val = self.getRandomNum(intArr=[0,1,2,4,8,16,32,64,128],mult=8)
hexData = self.int2hexStringByBytes(val)
return hexData
#####################################################
# 获取开关状态A16进制数据
#####################################################
def getOnoffStatusAHex(self):
machineOilWarning = 0 #机油报警,1:开 0:关
oilWarning = 0 #燃油报警,2:开 0:关
wiperWarning = 0 #雨刷报警,4:开 0:关
loudsspeakerWaring = 0 #喇叭报警,8:开 0:关
airConditionerWaring = 0 #空调,16:开 0:关
backMirrorWaring = 0 #后视镜状态:32开 0:关
retain1 = 0
retain2 = 0
val = machineOilWarning + oilWarning + wiperWarning + loudsspeakerWaring + airConditionerWaring + backMirrorWaring + retain1 + retain2
hexData = self.int2hexStringByBytes(val)
return hexData
def getOnoffStatusAHex_random(self):
val = self.getRandomNum(intArr=[0,1,2,4,8,16,32],mult=6)
hexData = self.int2hexStringByBytes(val)
return hexData
#####################################################
# 获取开关状态B16进制数据
#####################################################
def getOnoffStatusBHex(self):
retain1 = 0
retain2 = 0
retain3 = 0
retain4 = 0
#档位,0:p 16:R 32:N 48:D 64:1挡 80:2挡 96:3挡 112:4挡 128:5挡 144:6挡 160:M挡 176:S挡
gears = 0
val = retain1 + retain2 + retain3 + retain4 + gears
hexData = self.int2hexStringByBytes(val)
return hexData
def getOnoffStatusBHex_random(self):
val = self.getRandomNum(intArr=[0,16,32,48,64,80,96,112,128,144,160,176])
hexData = self.int2hexStringByBytes(val)
return hexData
\ No newline at end of file
#encoding:utf-8
'''
定义外设数据项
'''
from lib.Mnew.MessageBase import MessageBase
class Circum_data(MessageBase):
def __init__(self):
super().__init__()
pass
#####################################################
# 创建轿车OBD数据
#####################################################
def generateCircum_data(self):
data = ""
data_1 = "3001" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(20)
data_2 = "3002" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(21)
data = data_1 + data_2
return data
\ No newline at end of file
#encoding:utf-8
'''
定义新能源车 OBD 数据
'''
from lib.Mnew.MessageBase import MessageBase
class NewEnergyCar_data(MessageBase):
def __init__(self):
super().__init__()
pass
#####################################################
# 创建轿车OBD数据
#####################################################
def generateNewEnergyCar_data(self):
data = ""
#续航里程 , 0.1km 显示值为上传值/10
enduranceMileage = "7001" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(22000,4)
#剩余电量 , 0% - 100%
surplusPower = "7002" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(55)
#车速 , Km/h 0 - 240
speed = "7003" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(74)
#充电状态
#0x0: 初始值
# 0x1: 未充电
# 0x2: 交流充电中
# 0x3: 直流充电中
# 0x4: 充电完成 0x5: Void 0x6: Void 0x7: 无效值
chargeStatus = "7004" + self.int2hexStringByBytes(1) + "01"
#充电桩状态 , 0x01:插入 0x00:未插入
chargingPileStatus = "7005" + self.int2hexStringByBytes(1) + "00"
#动力电池充放电电流 0.01A 0x0-0xFFFF
batteryStream = "7006" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(30,2)
#单体电芯最高电压 0.001V 0x0-0xFFFF
batteryMaxVoltage_1 = "7007" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(7000,2)
# 单体电芯最高电压 0.001V 0x0-0xFFFF
batteryMaxVoltage_2 = "7008" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(7000, 2)
#驱动电机当前转速 Rpm
electromotorSpeed = "7009" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(5000,2)
#驱动电机当前转矩 Nm
electromotorTorque = "700a" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(2000,2)
#驱动电机当前温度 C 上传值减去 40
electromotorTemperature = "700b" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(90)
#直流母线电压 0.001V 0x0-0xFFFF
DCBusVotage = "700c" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(3000,2)
#直流母线电流 0.01A 0x0-0xFFFF
DCBusStream = "700d" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(36,2)
#动力电池可用能量 0.01Kwh 0x0-0xFFFF
batteryAvailablePower = "700e" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(30000,2)
#1 号单体电池电压 V
batteryVotage_1 = "7021" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(6)
batteryVotage_2 = "7022" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(6)
batteryVotage_3 = "7023" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(6)
batteryVotage_4 = "7024" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(6)
batteryVotage_5 = "7025" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(6)
batteryVotage_6 = "7026" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(6)
batteryVotage_7 = "7027" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(6)
batteryVotage_8 = "7028" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(6)
batteryVotage_9 = "7029" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(6)
batteryVotage_10 = "702A" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(6)
data = data + enduranceMileage + surplusPower + speed + chargeStatus + chargingPileStatus
data = data + batteryStream + batteryMaxVoltage_1 + batteryMaxVoltage_2 + electromotorSpeed + electromotorTorque
data = data + electromotorTemperature + DCBusVotage + DCBusStream + batteryAvailablePower + batteryVotage_1
data = data + batteryVotage_2 + batteryVotage_3 + batteryVotage_4 + batteryVotage_5 + batteryVotage_6
data = data + batteryVotage_7 + batteryVotage_8 + batteryVotage_9 + batteryVotage_10
return data
if __name__ == "__main__":
print(NewEnergyCar_data().generateNewEnergyCar_data())
\ No newline at end of file
#encoding:utf-8
'''
定义轿车OBD数据
'''
from lib.Mnew.MessageBase import MessageBase
class SaloonCarOBD_data(MessageBase):
def __init__(self):
super().__init__()
pass
#####################################################
# 创建轿车OBD数据
#####################################################
def generateSaloonCarOBDData(self):
data = ""
#发动机转速 , 0 - 8000 rpm
engineSpeed = "60C0" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(3000,2)
#车速 , 0 - 240 Km/h
carSpeed = "60D0" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(60)
#剩余油量 ,剩余油量,单位 L 或%Bit15=0 百分比%,OBD 都为百分比Bit15=1 单位 L,显示值为上传值/10
surplusOil = "62f0" + self.int2hexStringByBytes(2) + self.getSurplusOil()
#冷却液温度 ,-40.0℃ 到 +210℃,上传值减去 40
coolingLiquidTemperature = "6050" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(76)
#进气口温度 ,-40.0℃ 到 +210℃,上传值减去 40
airInletTemperature = "60F0" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(88)
#进气(岐管绝对)压力 , 0 - 250kpa
intakeManifoldPressure = "60B0" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(20)
#大气压力 , 0 - 125kpa
atmosphericPressure = "6330" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(28)
#环境温度 , -40.0℃ 到 +210℃,上传值减去 40
envTemperature = "6460" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(65)
#加速踏板位置 , 0% - 100%
acceleratorLocation = "6490" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(32)
#燃油压力 , 0 - 500kpa
oilPressure = "60A0" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(276,2)
#故障码状态 , 发动机故障码状态
troubleCodeStatus = "6014" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(0)
#故障码个数
troubleCodeNum = "6010" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(2)
#空气流量 , 0.1 实际值为上传值/10 0.1g/s
airFlow = "6100" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(550,2)
#绝对气门位置
valveLocation = "6110" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(51,2)
#自发动机启动运行时间 sec
engineRunTime = "61F0" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(3700,2)
#故障行驶里程 , Km
troubleMileage = "6210" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(4508,4)
#计算负荷值
calculateLoadValue = "6040" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(44)
#长期燃油修正(气缸列 1 和 3)
fuelTrim = "6070" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(89,2)
#第一缸点火正时提前角 ,显示值为上传值-64
fireAngle = "60E0" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(154,2)
#前刹车片磨损 , 0 正常/否则,显示对应数据,单位:级
frontBrakeBlockAbrasion = "6701" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(0)
#后刹车片磨损 , 0 正常/否则,显示对应数据,单位:级
backBrakeBlockAbrasion = "6702" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(0)
#制动液液位 , 0:不正 1:正常 其他:无法使用
brakeFluidLocation = "6703" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(1)
#机油液位 , 显示值为上传值/1000 单位 毫米
engineOilLocation = "6704" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(20000,2)
#胎压报警 0:当前无警告 1:存在胎压失压 其他:不可用
tirePressureAlarm = "6705" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(0,2)
#冷却液液位 , 显示值为上传值-48
coolingLiquidLocation = "6706" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(65,2)
#续航里程 0.1 km ; 显示值为上传值/10
enduranceMileage = "6707" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(382,4)
data = data + engineSpeed + carSpeed + surplusOil + coolingLiquidTemperature + airInletTemperature
data = data + intakeManifoldPressure + atmosphericPressure + envTemperature + acceleratorLocation + oilPressure
data = data + troubleCodeStatus + troubleCodeNum + airFlow + valveLocation + engineRunTime
data = data + troubleMileage + calculateLoadValue + fuelTrim + fireAngle + frontBrakeBlockAbrasion
data = data + backBrakeBlockAbrasion + brakeFluidLocation + engineOilLocation + tirePressureAlarm + coolingLiquidLocation
data = data + enduranceMileage
return data
def generateSaloonCarOBDData_random(self):
data = ""
#发动机转速 , 0 - 8000 rpm
engineSpeed = "60C0" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(self.getRandomNum(0,8000),2)
#车速 , 0 - 240 Km/h
carSpeed = "60D0" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(self.getRandomNum(0,240))
#剩余油量 ,剩余油量,单位 L 或%Bit15=0 百分比%,OBD 都为百分比Bit15=1 单位 L,显示值为上传值/10
surplusOil = "62f0" + self.int2hexStringByBytes(2) + self.getSurplusOil_random()
#冷却液温度 ,-40.0℃ 到 +210℃,上传值减去 40
coolingLiquidTemperature = "6050" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(self.getRandomNum(0,250))
#进气口温度 ,-40.0℃ 到 +210℃,上传值减去 40
airInletTemperature = "60F0" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(self.getRandomNum(0,250))
#进气(岐管绝对)压力 , 0 - 250kpa
intakeManifoldPressure = "60B0" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(self.getRandomNum(0,250))
#大气压力 , 0 - 125kpa
atmosphericPressure = "6330" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(self.getRandomNum(0,125))
#环境温度 , -40.0℃ 到 +210℃,上传值减去 40
envTemperature = "6460" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(self.getRandomNum(0,250))
#加速踏板位置 , 0% - 100%
acceleratorLocation = "6490" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(self.getRandomNum(0,100))
#燃油压力 , 0 - 500kpa
oilPressure = "60A0" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(self.getRandomNum(0,500),2)
#故障码状态 , 发动机故障码状态
troubleCodeStatus = "6014" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(self.getRandomNum(intArr=[0,1]))
#故障码个数
troubleCodeNum = "6010" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(self.getRandomNum(0,255))
#空气流量 , 0.1 实际值为上传值/10 0.1g/s
airFlow = "6100" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(self.getRandomNum(0,65535),2)
#绝对气门位置
valveLocation = "6110" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(self.getRandomNum(0,65535),2)
#自发动机启动运行时间 sec
engineRunTime = "61F0" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(self.getRandomNum(0,65535),2)
#故障行驶里程 , Km
troubleMileage = "6210" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(self.getRandomNum(0,2147483648),4)
#计算负荷值
calculateLoadValue = "6040" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(self.getRandomNum(0,255))
#长期燃油修正(气缸列 1 和 3)
fuelTrim = "6070" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(self.getRandomNum(0,65535),2)
#第一缸点火正时提前角 ,显示值为上传值-64
fireAngle = "60E0" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(self.getRandomNum(0,65435),2)
#前刹车片磨损 , 0 正常/否则,显示对应数据,单位:级
frontBrakeBlockAbrasion = "6701" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(self.getRandomNum(0,255))
#后刹车片磨损 , 0 正常/否则,显示对应数据,单位:级
backBrakeBlockAbrasion = "6702" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(self.getRandomNum(0,255))
#制动液液位 , 0:不正 1:正常 其他:无法使用
brakeFluidLocation = "6703" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(self.getRandomNum(intArr=[0,1]))
#机油液位 , 显示值为上传值/1000 单位 毫米
engineOilLocation = "6704" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(self.getRandomNum(0,65535),2)
#胎压报警 0:当前无警告 1:存在胎压失压 其他:不可用
tirePressureAlarm = "6705" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(self.getRandomNum(intArr=[0,1]),2)
#冷却液液位 , 显示值为上传值-48
coolingLiquidLocation = "6706" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(self.getRandomNum(0,65435),2)
#续航里程 0.1 km ; 显示值为上传值/10
enduranceMileage = "6707" + self.int2hexStringByBytes(4) + self.int2hexStringByBytes(self.getRandomNum(0,2147483648),4)
data = data + engineSpeed + carSpeed + surplusOil + coolingLiquidTemperature + airInletTemperature
data = data + intakeManifoldPressure + atmosphericPressure + envTemperature + acceleratorLocation + oilPressure
data = data + troubleCodeStatus + troubleCodeNum + airFlow + valveLocation + engineRunTime
data = data + troubleMileage + calculateLoadValue + fuelTrim + fireAngle + frontBrakeBlockAbrasion
data = data + backBrakeBlockAbrasion + brakeFluidLocation + engineOilLocation + tirePressureAlarm + coolingLiquidLocation
data = data + enduranceMileage
return data
#####################################################
# 获取剩余油量
#####################################################
def getSurplusOil(self):
# 剩余油量 ,剩余油量,单位L或% ; Bit15=0 百分比%,OBD都为百分比 ;Bit15=1 单位 L,显示值为上传值/10 (32768)
units = 0
surplusOil = 801
data = units + surplusOil
dataHex = self.int2hexStringByBytes(data,2)
return dataHex
def getSurplusOil_random(self):
# 剩余油量 ,剩余油量,单位L或% ; Bit15=0 百分比%,OBD都为百分比 ;Bit15=1 单位 L,显示值为上传值/10 (32768)
units = self.getRandomNum(intArr=[0,32768])
surplusOil = self.getRandomNum(0,16384)
data = units + surplusOil
dataHex = self.int2hexStringByBytes(data,2)
return dataHex
if __name__ == "__main__":
print(SaloonCarOBD_data().generateSaloonCarOBDData())
\ No newline at end of file
#encoding:utf-8
'''
定义终端注销消息
'''
from lib.Mnew.MessageBase import MessageBase
class TerminalCancle_msg(MessageBase):
def __init__(self):
super().__init__() #不执行该方法,无法使用父类里面定义的属性
pass
#######################################################
# 生成一条完整的消息
#######################################################
def generateMsg(self):
msg = ""
msgHeader = self.getMsgHeader()
msgBody = self.getMsgBody()
checkCode = self.getCheckCode(msgHeader + msgBody)
msg = msg + self.IDENTIFY
info = msgHeader + msgBody + checkCode
info = self.replace7e7d(info)
msg = msg + info
msg = msg + self.IDENTIFY
return msg
#######################################################
# 获取消息体
#######################################################
def getMsgBody(self):
msg = ""
return msg
#######################################################
# 获取消息头
#######################################################
def getMsgHeader(self):
# msgID = self.int2hexStringByBytes(102,2) #消息id
msgID = "0003"
msgBodyProperty = self.getMsgBodyProperty(len(self.getMsgBody())) #消息体属性
phoneNum = self.int2BCD(13146201119) #终端手机号
msgWaterCode = self.int2hexStringByBytes(1,2) #消息流水号
subPkgContent = "" #消息包封装项
data = msgID + msgBodyProperty + phoneNum + msgWaterCode + subPkgContent
return data
#获取消息体属性
def getMsgBodyProperty(self,msgBodyLen=128,encryptionType=0,subPkg=0):
if msgBodyLen >= 512:
raise RuntimeError('消息体长度超长!')
msgBodyLen = msgBodyLen #消息体长度
encryptionType = encryptionType #加密方式
subPkg = subPkg #分包
retain = 0 #保留位
data = msgBodyLen + encryptionType + subPkg + retain
dataHex = self.int2hexStringByBytes(data,2)
return dataHex
\ No newline at end of file
#encoding:utf-8
'''
定义轿车OBD数据
'''
from lib.Mnew.MessageBase import MessageBase
class TruckCarOBD_data(MessageBase):
def __init__(self):
super().__init__()
pass
#####################################################
# 创建轿车OBD数据
#####################################################
def generateTruckCarOBD_data(self):
data = ""
#发动机转速 , 0 - 8000 rpm
engineSpeed = "60C0" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(3000,2)
#车速 , 0 - 240 Km/h
carSpeed = "60D0" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(60)
#剩余油量 ,剩余油量,单位 L 或%Bit15=0 百分比%,OBD 都为百分比Bit15=1 单位 L,显示值为上传值/10
surplusOil = "62f0" + self.int2hexStringByBytes(2) + self.getSurplusOil()
#冷却液温度 ,-40.0℃ 到 +210℃,上传值减去 40
coolingLiquidTemperature = "6050" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(76)
#进气口温度 ,-40.0℃ 到 +210℃,上传值减去 40
airInletTemperature = "60F0" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(88)
#进气(岐管绝对)压力 , 0 - 250kpa
intakeManifoldPressure = "60B0" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(20)
#大气压力 , 0 - 125kpa
atmosphericPressure = "6330" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(28)
#环境温度 , -40.0℃ 到 +210℃,上传值减去 40
envTemperature = "6460" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(65)
#加速踏板位置 , 0% - 100%
acceleratorLocation = "6490" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(32)
#燃油压力 , 0 - 500kpa
oilPressure = "60A0" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(276,2)
#故障码个数
troubleCodeNum = "6010" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(2)
#OBD 离合器开关 ,0x00/0x01 关/开
clutchSwitch = "5001" + self.int2hexStringByBytes(1) + "01"
#OBD 制动刹车开关 , 0x00/0x01 关/开
brakeSwich = "5002" + self.int2hexStringByBytes(1) + "01"
#OBD 驻车刹车开关 , 0x00/0x01 关/开
parkingBrakeSwitch = "5003" + self.int2hexStringByBytes(1) + "01"
#OBD 节流阀位置 , 0% - 100%
throttleLocation = "5004" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(33)
#OBD 油料使用率 , 0 - 3212.75L/h
oilUsageRate = "5005" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(1000,2)
#OBD 燃油温度 , 起始值-273℃ 范围(-273 到+1735)
oilTemperature = "5006" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(299,2)
#OBD 机油温度 , 起始值-273℃ 范围(-273 到+1735)
engineOilTemperature = "5007" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(300,2)
#OBD 发动机润滑油压力 , 0 - 1000kpa
engineOilPresure = "5008" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(120)
#OBD 制动器踏板位置 , 0% - 100%
brekeLocation = "5009" + self.int2hexStringByBytes(1) + self.int2hexStringByBytes(31)
#OBD 空气流量 , 0.1 G/S
airFlow = "500A" + self.int2hexStringByBytes(2) + self.int2hexStringByBytes(800,2)
data = data + engineSpeed + carSpeed + surplusOil + coolingLiquidTemperature + airInletTemperature
data = data + intakeManifoldPressure + atmosphericPressure + envTemperature + acceleratorLocation + oilPressure
data = data + troubleCodeNum + clutchSwitch + brakeSwich + parkingBrakeSwitch + throttleLocation
data = data + oilUsageRate + oilTemperature + engineOilTemperature + engineOilPresure + brekeLocation
data = data + airFlow
return data
#####################################################
# 获取剩余油量
#####################################################
def getSurplusOil(self):
# 剩余油量 ,剩余油量,单位 L 或%Bit15=0 百分比%,OBD 都为百分比Bit15=1 单位 L,显示值为上传值/10 (32768)
units = 32768
surplusOil = 800
data = units + surplusOil
dataHex = self.int2hexStringByBytes(data,2)
return dataHex
if __name__ == "__main__":
print(TruckCarOBD_data().generateTruckCarOBD_data())
\ No newline at end of file
#coding:utf-8
import binascii
import json
import random
import socket
import threading
import time
from lib.Mnew.DataUpstreamTransport_msg import DataUpstreamTransport_msg
from lib.Mnew.Location_msg import Location_msg
from lib.Mnew.TerminalHeartbeat_msg import TerminalHeartbeat_msg
from lib.Mnew.TerminalRegister_msg import TerminalRegister_msg
from lib.Mnew.TerminalVersionInfo_msg import TerminalVersionInfo_msg
from lib.pressure.ThreadBase import ThreadBase
class SendMultMsgNewThread(ThreadBase):
def __init__(self,host="10.100.11.20",port=9001,msg=""):
self.host = host
self.port = port
self.msg = msg
self.timeOut = 30 #socket超时时间
self.BUF_SIZE = 1024 #接收消息缓存
self.threadCount = 1000 #并发线程数
self.totalTime = 0 #所有线程的运行总和
self.threadArr = {} #保存每个线程的信息
self.failThreadCount = 0 #失败线程数
self.durThreads = [] #持续发送线程数组,当数组为空,表示所有线程已经结束
dt = 1 * 10 * 60
self.durTime = dt #线程持续时间
self.connectTimeoutNum = 0 #连接超时线程数
self.sendTimeoutNum = 0 #发送超时线程数
self.reviceTimeoutNum = 0 #接收超时线程数
self.sucessNum = 0 #成功线程数
self.setStartCarNumber = 0 #开始车机号
self.messageCon = [] #用来统计每个线程所发的消息数
self.messageCons = 0 # 用来统计每个线程所发的消息数
pass
############################################
# 设置host
############################################
def setHost(self,host):
self.host = host
############################################
# 设置端口号
############################################
def setPort(self,port):
self.port = port
############################################
# 设置消息
############################################
def setMsg(self,msg):
self.msg = msg
############################################
# 设置并发线程数
############################################
def setThreadCount(self,threadCount):
self.threadCount = threadCount
############################################
# 设置持续时间
############################################
def setDurTime(self,durTime):
self.durTime = durTime
############################################
# 设置超时时间
############################################
def setTimeOut(self,timeOut):
self.timeOut = timeOut
############################################
# 设置开始车机号
############################################
def setSetStartCarNumber(self,setStartCarNumber):
self.setStartCarNumber = setStartCarNumber
############################################
# 发送一条消息
############################################
def sendMsg(self,msg,threadName):
msg = msg
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) # 在客户端开启心跳
client.settimeout(self.timeOut)
startTime = int(time.time() * 1000)
try:
client.connect((self.host, self.port))
client.send(binascii.a2b_hex(msg))
except BaseException as e:
client.close()
self.threadArr[threadName]["status"] = 1
self.failThreadCount = self.failThreadCount + 1
print("连接超时,socket断开")
return
try:
data = client.recv(self.BUF_SIZE)
# print(data)
except BaseException as e:
# traceback.print_exc()
client.close()
# raise RuntimeError('socket 接收消息超时!')
self.threadArr[threadName]["status"] = 1
self.failThreadCount = self.failThreadCount + 1
print('socket 接收消息超时!')
return
endTime = int(time.time() * 1000)
timeExpend = endTime - startTime
self.threadArr[threadName]["timeExp"] = timeExpend
self.totalTime = self.totalTime + timeExpend
client.close()
############################################
# 持续发送消息
# dur: 持续发送时间,如果为0一直发送, 设置了事件为持续发送多少秒,默认为一分钟
############################################
def sendMsgContinuous(self,carId,threadName="thread0"):
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) # 在客户端开启心跳
client.settimeout(self.timeOut)
startTime = int(time.time())
endTime = int(time.time())
msgCon = 0 #统计线程发的消息数量
self.durThreads.append(threadName)
try:
client.connect((self.host, self.port))
except BaseException as e:
client.close()
self.durThreads.remove(threadName)
self.threadArr[threadName]["status"] = 1
self.failThreadCount = self.failThreadCount + 1
endTime = int(time.time())
timeExpend = endTime - startTime
self.threadArr[threadName]["timeExp"] = timeExpend
self.connectTimeoutNum = self.connectTimeoutNum + 1
self.messageCon.append(msgCon)
self.threadArr[threadName]["msgCon"] = msgCon
print(threadName + ":" + "连接超时,socket断开")
return
while (endTime - startTime) < self.durTime:
msg = self.getRandomMsg_new(carId)
try:
client.send(binascii.a2b_hex(msg))
msgCon = msgCon + 1
self.messageCons = self.messageCons + 1
except BaseException as e:
client.close()
self.durThreads.remove(threadName)
self.threadArr[threadName]["status"] = 1
self.failThreadCount = self.failThreadCount + 1
endTime = int(time.time())
timeExpend = endTime - startTime
self.threadArr[threadName]["timeExp"] = timeExpend
self.sendTimeoutNum = self.sendTimeoutNum + 1
self.messageCon.append(msgCon)
self.threadArr[threadName]["msgCon"] = msgCon
print(threadName + ":" + "发送超时,socket断开")
return
try:
data = client.recv(self.BUF_SIZE)
except BaseException as e:
client.close()
self.durThreads.remove(threadName)
self.threadArr[threadName]["status"] = 1
self.failThreadCount = self.failThreadCount + 1
self.reviceTimeoutNum = self.reviceTimeoutNum + 1
self.messageCon.append(msgCon)
self.threadArr[threadName]["msgCon"] = msgCon
print(threadName + ":" + 'socket 接收消息超时!')
endTime = int(time.time())
timeExpend = endTime - startTime
self.threadArr[threadName]["timeExp"] = timeExpend
return
endTime = int(time.time())
sleepTime = random.randint(1, 5)
time.sleep(sleepTime)
endTime = int(time.time())
timeExpend = endTime - startTime
self.threadArr[threadName]["timeExp"] = timeExpend
self.messageCon.append(msgCon)
self.threadArr[threadName]["msgCon"] = msgCon
client.close()
self.sucessNum = self.sucessNum + 1
self.durThreads.remove(threadName)
############################################
# 启动并发线程
############################################
def startThread(self):
timeStart = int(time.time() * 1000)
for i in range(0,self.threadCount):
threadName = "thread-" + str(i)
theThread = threading.Thread(target=self.sendMsg, args=("7e0002000001314620111800065b7e",threadName,)) # 数据写死,心跳
threadInfo = {}
threadInfo["name"] = threadName
threadInfo["status"] = 0
self.threadArr[threadName] = threadInfo
theThread.start()
timeEnd = int(time.time() * 1000)
timeExpend = timeEnd - timeStart
if timeExpend == 0:
timeExpend = 1000
time.sleep(3)
print("耗时:" + str(timeExpend) + " 毫秒")
print("并发数据每秒发送:" + str(int(self.threadCount / (timeExpend / 1000))))
print("平均响应时间:" + str(self.totalTime / self.threadCount) + "毫秒")
print("发送总数:" + str(self.threadCount))
print("响应失败数:" + str(self.failThreadCount))
self.writeToFile("./data/threadDetails.json",self.threadArr)
############################################
# 启动持续并发线程
############################################
def startThreadContinuous(self):
timeStart = int(time.time() * 1000)
for i in range(0,self.threadCount):
threadName = "thread-" + str(i)
carid = 201912000000 + i + self.setStartCarNumber
print(threadName + " 车机号:" + str(carid))
theThread = threading.Thread(target=self.sendMsgContinuous, args=(carid,threadName,)) # 数据写死,心跳
threadInfo = {}
threadInfo["name"] = threadName
threadInfo["status"] = 0
self.threadArr[threadName] = threadInfo
theThread.start()
timeEnd = int(time.time() * 1000)
timeExpend = timeEnd - timeStart
print("耗时:" + str(timeExpend) + " 毫秒产生了" + str(self.threadCount) + "线程")
time.sleep(0.5) #防止启动的时候溜掉某些启动比较慢的线程
tmp = 1
while len(self.durThreads) != 0:
print("剩余线程数_" + str(tmp) + ":" + str(len(self.durThreads)))
tmp = tmp + 1
timeArray = time.localtime(timeStart / 1000)
testStart = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
timeCur = int(time.time() * 1000)
timeArray = time.localtime(timeCur / 1000)
testCur = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
info_0 = "-------------------------- 统计信息(pre) --------------------------"
info_1 = "耗时:" + str(timeExpend) + " 毫秒产生了" + str(self.threadCount) + "线程"
info_2 = "开始测试时间:" + testStart
info_4 = "设置socket超时时间:" + str(self.timeOut)
info_5 = "设置线程持续时间:" + str(self.durTime)
info_6 = "剩余线程数:" + str(len(self.durThreads))
info_8 = "连接失败:" + str(self.connectTimeoutNum)
info_9 = "发送失败:" + str(self.sendTimeoutNum)
info_10 = "接收失败:" + str(self.reviceTimeoutNum)
info_11 = "当前写入时间:" + testCur
info_12 = "当前发送消息总数:" + str(self.messageCons)
result = info_0 + "\n" + info_1 + "\n" + info_2 + "\n" + info_4 + "\n" + info_5 + "\n" + info_6 + "\n"
result = result + info_8 + "\n" + info_9 + "\n" + info_10 + "\n" + info_11 + "\n" + info_12 + "\n"
self.writeToFile("./result_pre.txt",result)
time.sleep(5)
timeArray = time.localtime(timeStart / 1000)
testStart = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
timeEnd = int(time.time() * 1000)
timeArray = time.localtime(timeEnd / 1000)
testestEnd = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
time.sleep(2) #防止线程慢的时候,某些线程被漏统计的情况
info_0 = "-------------------------- 统计信息 --------------------------"
print(info_0)
totalMsg = 0
for i in self.messageCon:
totalMsg = totalMsg + i
info_1 = "耗时:" + str(timeExpend) + " 毫秒产生了" + str(self.threadCount) + "线程"
info_2 = "开始测试时间:" + testStart
info_3 = "结束测试时间:" + testestEnd
info_4 = "设置socket超时时间:" + str(self.timeOut)
info_5 = "设置线程持续时间:" + str(self.durTime)
info_6 = "成功线程数:" + str(self.sucessNum)
info_7 = "消息总数:" + str(totalMsg)
info_8 = "连接失败:" + str(self.connectTimeoutNum)
info_9 = "发送失败:" + str(self.sendTimeoutNum)
info_10 = "接收失败:" + str(self.reviceTimeoutNum)
print(info_1)
print(info_2)
print(info_3)
print(info_4)
print(info_5)
print(info_6)
print(info_7)
print(info_8)
print(info_9)
print(info_10)
self.writeToFile("./threadDetailsContinuous.json",json.dumps(self.threadArr))
info_11 = self.getInfoFromResult("./threadDetailsContinuous.json")
result = info_0 + "\n" + info_1 + "\n" + info_2 + "\n" + info_3 + "\n" + info_4 + "\n" + info_5 + "\n" + info_6 + "\n"
result = result + info_7 + "\n" + info_8 + "\n" + info_9 + "\n" + info_10 + "\n" + info_11
self.writeToFile("./result.txt", result)
def writeToFile(self,path,data):
with open(path, "w", encoding='utf-8') as fi:
#json.dump(data, fi)
fi.write(data)
# 获取随机消息数据(新硬件车机)
def getRandomMsg_new(self, carId):
# carId = 201912010002
wh = random.randint(0,5)
msg = ""
if wh == 0:
hearbeatObj = TerminalHeartbeat_msg()
hearbeatObj.setPhoneNum(carId)
hearbeat_msg = hearbeatObj.generateMsg()
msg = hearbeat_msg
elif wh == 1:
registerObj = TerminalRegister_msg()
register_msg = registerObj.generateMsg()
msg = register_msg
elif wh == 2:
versionInfoObj = TerminalVersionInfo_msg()
versionInfo_msg = versionInfoObj.generateMsg()
msg = versionInfo_msg
elif wh == 3:
dataUpstreamObj = DataUpstreamTransport_msg()
dataUpstream_msg = dataUpstreamObj.generateMsg()
msg = dataUpstream_msg
elif wh == 4:
locationObj = Location_msg()
location_msg = locationObj.generateMsg()
msg = location_msg
return msg
def getInfoFromResult(self,path):
with open(path, "r", encoding='utf-8') as fi:
d = fi.read()
d = json.loads(d)
msgC = 0
failT = 0
for i in d:
msgC = msgC + d[i]["msgCon"]
if d[i]["status"] == 1:
failT = failT +1
info_1 = "文件统计总消息数:" + str(msgC)
info_2 = "文件统计总失败数:" + str(failT)
print(info_1)
print(info_2)
return info_1 + "\n" +info_2 + "\n"
if __name__ == "__main__":
t = SendMultMsgNewThread()
t.setHost("10.100.11.20")
t.setPort(9001)
t.startThreadContinuous()
#coding:utf-8
import binascii
import json
import socket
import threading
import time
from lib.multiThread.ThreadBase import ThreadBase
from lib.protocol.message.Location_msg import Location_msg
from lib.protocol.message.TerminalRegister_msg import TerminalRegister_msg
class SendMultMsgThread():
def __init__(self,host="10.100.11.20",port=9001,msg=""):
self.host = host
self.port = port
self.msg = msg
self.timeOut = 1 #socket超时时间
self.BUF_SIZE = 1024 #接收消息缓存
self.threadCount = 10000 #并发线程数
self.totalTime = 0 #所有线程的运行总和
self.threadArr = {} #保存每个线程的信息
self.failThreadCount = 0 #失败线程数
pass
############################################
# 设置host
############################################
def setHost(self,host):
self.host = host
############################################
# 设置端口号
############################################
def setPort(self,port):
self.port = port
############################################
# 设置消息
############################################
def setMsg(self,msg):
self.msg = msg
############################################
# 设置并发线程数
############################################
def setThreadCount(self,threadCount):
self.threadCount = threadCount
############################################
# 发送一条消息
############################################
def sendMsg(self,msg,threadName):
msg = msg
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) # 在客户端开启心跳
client.settimeout(self.timeOut)
startTime = int(time.time() * 1000)
try:
client.connect((self.host, self.port))
client.send(binascii.a2b_hex(msg))
except BaseException as e:
client.close()
self.threadArr[threadName]["status"] = 1
self.failThreadCount = self.failThreadCount + 1
print("连接超时,socket断开")
return
try:
data = client.recv(self.BUF_SIZE)
# print(data)
except BaseException as e:
# traceback.print_exc()
client.close()
# raise RuntimeError('socket 接收消息超时!')
self.threadArr[threadName]["status"] = 1
self.failThreadCount = self.failThreadCount + 1
print('socket 接收消息超时!')
return
endTime = int(time.time() * 1000)
timeExpend = endTime - startTime
self.threadArr[threadName]["timeExp"] = timeExpend
self.totalTime = self.totalTime + timeExpend
client.close()
############################################
# 启动并发线程
############################################
def startThread(self):
timeStart = int(time.time() * 1000)
for i in range(0,self.threadCount):
threadName = "thread" + str(i)
# theThread = threading.Thread(target=self.sendMsg, args=("7e0002000001314620111800065b7e",threadName,)) # 数据写死,心跳
theThread = threading.Thread(target=self.sendMsg,args=("4040007000094d20191201000200120114030409123426d7fffff0000000000505000000143c00000bb80100000fa00000000a0000000000005e5f68e768e739331e100055320000001312001007d0001e0000000000000096000000280096ffff3e0001f40000003e00000000000000000000000f9a", threadName,)) # 数据写死
# theThread = threading.Thread(target=self.sendMsg, \
# args=(TerminalRegister_msg().generateMsg_random(), threadName,)) #终端注册
# theThread = threading.Thread(target=self.sendMsg, \
# args=(Location_msg().generateMsg_random(), threadName,)) #地理位置
threadInfo = {}
threadInfo["name"] = threadName
threadInfo["status"] = 0
self.threadArr[threadName] = threadInfo
theThread.start()
timeEnd = int(time.time() * 1000)
timeExpend = timeEnd - timeStart
time.sleep(6)
print("耗时:" + str(timeExpend) + " 毫秒")
print("并发数据每秒发送:" + str(int(self.threadCount / (timeExpend / 1000))))
print("平均响应时间:" + str(self.totalTime / self.threadCount) + "毫秒")
print("发送总数:" + str(self.threadCount))
print("响应失败数:" + str(self.failThreadCount))
self.writeToFile("../../data/threadDetails.json",self.threadArr)
# print(json.dumps( self.threadArr))
def writeToFile(self,path,data):
with open(path, "w", encoding='utf-8') as fi:
json.dump(data, fi)
# fi.write(data)
if __name__ == "__main__":
t = SendMultMsgThread()
t.setHost("10.100.12.32")
t.setPort(9008)
# t.setMsg("7e0002000001314620111800065b7e")
# t.setMsg("7e020001020131462011190001fffc7fff001c010401c0a6380659ad7a02090042003b200204185704310102EA6600010400000000000204001e7c1f0003050A0001f400000405020001d4c000050400057d0240000604000119400007040007530000100c0004006403f203f203f203f2001114ffffffffffffffffffff00200000000000000000001202002400130106001D0101EB7960C0020bb860D0013c62f00203216050014c60F0015860B001146330011c646001416490012060A00201146014010160100102610002022661100201f561F0020e746210040000119c6040012c60700200e660E00203206701010067020100670301016704024e20670502000067060200416707040000017d02097e")
t.startThread()
......@@ -302,30 +302,6 @@ class SendMultMsgThread_m500(ThreadBase):
msg = OBD_msg
return msg
# 获取随机消息数据(新硬件车机)
def getRandomMsg_new(self, carId):
# carId = 201912010002
wh = random.randint(0, 2)
msg = ""
wh = 0
if wh == 0:
hearbeat_msg = "4040000e00044d" + str(carId) + "8000000300cf91"
hearbeat_msg = hearbeat_msg + self.getCheckCode(hearbeat_msg[2:]) + "7e"
hearbeat_msg = self.replace7e7d(hearbeat_msg)
msg = hearbeat_msg
elif wh == 1:
GPS_msg = "4040003d00054d" + str(
carId) + "001001140305031e0301c329ed0659dec501f402e8000000b4050a0b0c9305050258001400000fa0000000005e606f115e60723be44b"
GPS_msg = GPS_msg[:-4] + self.crc16(GPS_msg[:-4])
msg = GPS_msg
elif wh == 2:
OBD_msg = "4040007000064d" + str(
carId) + "00120114030503202d26d7fffff0000000000505000000143c00000bb80100000fa00000000a0000000000005e60723b723b39331e100055320000001312001007d0001e0000000000000096000000280096ffff3e0001f40000003e00000000000000000000007213"
OBD_msg = OBD_msg[:-4] + self.crc16(OBD_msg[:-4])
msg = OBD_msg
return msg
####################################################
# 定义生成校验字段的函数(M500 校验方式)
# inputStr:需要传入一个已经转换为16进制的字符串
......
......@@ -3,6 +3,7 @@
'''
启动压力测试脚本
'''
from lib.pressure.SendMultMsgNewThread import SendMultMsgNewThread
from lib.pressure.SendMultMsgThread_m300 import SendMultMsgThread_m300
from lib.pressure.SendMultMsgThread_m500 import SendMultMsgThread_m500
......@@ -12,9 +13,9 @@ def startM300():
# t.setHost("10.100.12.32")
t.setHost("10.100.5.251")
t.setPort(9009) # M300
t.setThreadCount(3500)
t.setThreadCount(3)
t.setTimeOut(30)
t.setDurTime(1 * 20 * 60)
t.setDurTime(1 * 1.5 * 60)
t.setSetStartCarNumber(0)
# t.startThread()
t.startThreadContinuous()
......@@ -26,11 +27,23 @@ def startM500():
t.setPort(9008) #M500
t.setThreadCount(4) #设置线程数
t.setTimeOut(30) #设置超时时间
t.setDurTime(1 * 1 * 60) #设置持续时间
t.setDurTime(1 * 1.5 * 60) #设置持续时间
t.setSetStartCarNumber(0) #设置开始的车机号,每启动一个线程自动加1
# t.startThread()
t.startThreadContinuous()
def startMNew():
t = SendMultMsgNewThread()
t.setHost("10.100.11.20")
t.setPort(9001) # 车安优
t.setThreadCount(3)
t.setTimeOut(30)
t.setDurTime(1 * 1 * 60)
t.setSetStartCarNumber(0)
t.startThreadContinuous()
if __name__ == "__main__":
startM500()
\ No newline at end of file
# startM300()
# startM500()
startMNew()
\ No newline at end of file
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