Commit 44bb56da authored by liyuanhong's avatar liyuanhong

优化了M500 模拟器

parent 0198e4ba
{"time": {"dateTime": "2020-04-14 11:32:27", "date": "2020-04-14", "time": "11:32:27"}, "curDayTravel": {"todayTotalMilleage": 4375, "todayTotalOil": 400, "todayTotalTime": 265, "theMilleage": 640, "theOil": 40, "theTime": 40}, "travelData": {"totallMilleage": 0, "totalOil": 0, "totalTime": 0}}
\ No newline at end of file
...@@ -34,13 +34,13 @@ class MessageBase(Base): ...@@ -34,13 +34,13 @@ class MessageBase(Base):
# 获取消息头 # 获取消息头
####################################################### #######################################################
def getMsgHeader(self): def getMsgHeader(self):
msgID = self.int2hexStringByBytes(102,2) #消息id msgID = self.int2hexStringByBytes(102,2) #消息id
subPkg = 0 subPkg = 0
msgBodyProperty = self.getMsgBodyProperty(subPkg=subPkg) #消息体属性 msgBodyProperty = self.getMsgBodyProperty(subPkg=subPkg) #消息体属性
phoneNum = self.int2BCD(13146201118) #终端手机号 phoneNum = self.int2BCD(13146201118) #终端手机号
msgWaterCode = self.int2hexStringByBytes(1) #消息流水号 msgWaterCode = self.int2hexStringByBytes(1) #消息流水号
if subPkg != 8192: if subPkg != 8192:
subPkgContent = "" #消息包封装项 subPkgContent = "" #消息包封装项
else: else:
subPkgContent = self.getMsgPackage() subPkgContent = self.getMsgPackage()
data = msgID + msgBodyProperty + phoneNum + msgWaterCode + subPkgContent data = msgID + msgBodyProperty + phoneNum + msgWaterCode + subPkgContent
......
...@@ -138,6 +138,7 @@ class GPSReport_protocol(ProtocolBase): ...@@ -138,6 +138,7 @@ class GPSReport_protocol(ProtocolBase):
Vdop = self.getVdop(self.Vdop) Vdop = self.getVdop(self.Vdop)
#状态字节 #状态字节
statusBit = self.getStatusBit(self.statusBit) statusBit = self.getStatusBit(self.statusBit)
print(statusBit)
#电压 #电压
valtage = self.getValtage(self.valtage) valtage = self.getValtage(self.valtage)
#OBD车速 #OBD车速
...@@ -335,12 +336,7 @@ class GPSReport_protocol(ProtocolBase): ...@@ -335,12 +336,7 @@ class GPSReport_protocol(ProtocolBase):
# 获取电压16进制值,2字节表示 # 获取电压16进制值,2字节表示
##################################################### #####################################################
def getValtage(self,num): def getValtage(self,num):
valtageStr = str(num) valtageHex = self.int2hexStringByBytes(int(num *100),2)
valtageStr = valtageStr.replace(".", "")
while (len(valtageStr) < 4):
valtageStr = "0" + valtageStr
valtageHex = hex(int(valtageStr))
valtageHex = self.leftPad(str(valtageHex)[2:], 4)
return valtageHex return valtageHex
##################################################### #####################################################
......
#coding:utf-8
##################################################
# 定义M500 车机行驶过程中产生的数据类
##################################################
import datetime
import json
import time
class MessageSimulaterDataService():
def __init__(self,path="/data/protocolTools/carData/",fileName="default.json"):
self.data = {}
self.path = path #保存车机数据文件地址
self.fileName = fileName #保存车机数据文件
def setPath(self,data):
self.path = data
def setFileName(self,data):
self.fileName = data
def setData(self,data):
self.data = data
####################################################
# 生成一个默认数据模板
####################################################
def genDataTemplate(self):
data = {}
timeStamp = time.time()
timeArray = time.localtime(timeStamp)
data["time"] = {} #定义时间数据项
data["time"]["dateTime"] = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
data["time"]["date"] = time.strftime("%Y-%m-%d", timeArray)
data["time"]["time"] = time.strftime("%H:%M:%S", timeArray)
data["curDayTravel"] = {} #定义当天行驶数据项
data["curDayTravel"]["todayTotalMilleage"] = 0 #今日行驶总里程
data["curDayTravel"]["todayTotalOil"] = 0 #今日行驶总油耗
data["curDayTravel"]["todayTotalTime"] = 0 #今日行驶总时间
data["curDayTravel"]["theMilleage"] = 0 #本次行驶总里程
data["curDayTravel"]["theOil"] = 0 #本次行驶总油耗
data["curDayTravel"]["theTime"] = 0 #本次行驶总时间
data["travelData"] = {} #定义所有行驶数据
data["travelData"]["totallMilleage"] = 0 #行驶总里程
data["travelData"]["totalOil"] = 0 #行驶总油耗
data["travelData"]["totalTime"] = 0 #行驶总时间
return data
#设今日行驶总里程,同时写入文件
def setTodayTotalMilleage(self,data):
self.data["curDayTravel"]["todayTotalMilleage"] = data
self.writeToFile(self.path + self.fileName,self.data)
#设今日行驶总油耗,同时写入文件
def setTodayTodayTotalOil(self,data):
self.data["curDayTravel"]["todayTotalOil"] = data
self.writeToFile(self.path + self.fileName,self.data)
#设今日行驶总时间,同时写入文件
def setTodayTodayTotalTime(self,data):
self.data["curDayTravel"]["todayTotalTime"] = data
self.writeToFile(self.path + self.fileName,self.data)
#设本次行驶总里程,同时写入文件
def setTheMilleage(self,data):
self.data["curDayTravel"]["theMilleage"] = data
self.writeToFile(self.path + self.fileName,self.data)
#设本次行驶总油耗,同时写入文件
def setTheOil(self,data):
self.data["curDayTravel"]["theOil"] = data
self.writeToFile(self.path + self.fileName,self.data)
#设本次行驶总时间,同时写入文件
def setTheTime(self,data):
self.data["curDayTravel"]["theTime"] = data
self.writeToFile(self.path + self.fileName,self.data)
#设今日日期时间
def setDateTime2file(self,data):
self.data["time"]["dateTime"] = data
self.writeToFile(self.path + self.fileName,self.data)
#设今日日期
def setData2file(self,data):
self.data["time"]["date"] = data
self.writeToFile(self.path + self.fileName,self.data)
#设今日时间
def setTime2file(self,data):
self.data["time"]["time"] = data
self.writeToFile(self.path + self.fileName,self.data)
####################################################
# 将数据写入文件
####################################################
def writeToFile(self,path,data):
with open(path,"w",encoding="utf-8") as fi:
data = json.dumps(data)
fi.write(data)
####################################################
# 从文件读取数据
####################################################
def readFromFile(self,path):
with open(path, "r", encoding="utf-8") as fi:
content = fi.read()
conJson = json.loads(content)
timeStamp = time.time()
timeArray = time.localtime(timeStamp)
dateTimeM = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
dateM = time.strftime("%Y-%m-%d", timeArray)
timeM = time.strftime("%H:%M:%S", timeArray)
if dateM == conJson["time"]["date"]:
pass
else: #如果不是当天日期,则将日期设置为当天
conJson["time"]["dateTime"] = dateTimeM
conJson["time"]["date"] = dateM
conJson["time"]["time"] = timeM
data["curDayTravel"]["todayTotalMilleage"] = 0 # 今日行驶总里程
data["curDayTravel"]["todayTotalOil"] = 0 # 今日行驶总油耗
data["curDayTravel"]["todayTotalTime"] = 0 # 今日行驶总时间
self.setTodayTotalMilleage(0)
self.setTodayTodayTotalOil(0)
self.setTodayTodayTotalTime(0)
self.setDateTime2file(dateTimeM)
self.setData2file(dateM)
self.setTime2file(timeM)
self.data = conJson
if __name__ == "__main__":
print(MessageSimulaterDataService().genDataTemplate())
data = MessageSimulaterDataService().genDataTemplate()
MessageSimulaterDataService().writeToFile("../../../data/protocolTools/carData/M202003060520.json",data)
\ No newline at end of file
#coding:utf-8
'''
新硬件车机模拟服务类
'''
import binascii
import json
import os
import threading
import time
import traceback
from time import sleep
from lib.socket.service.websocket_service import Websocket_service
class MessageSimulaterService():
def __init__(self):
self.data = {} #用来接收模拟器传过来的参数
self.carData = {} #保存车辆行驶数据
self.carDataObj = None #管理车辆行驶数据对象
self.socket = None
self.sendDur = 5 #设置默认多久发一条消息
self.serviceStatus = 0 #服务状态,0表示未启动,1表示启动
self.websocket = None #网页与服务的通信socket
self.timeout = 1 #socket的超时时间
self.gpsLine = [] #GPS 轨迹
self.gpsLineIndex = 0 #GPS 轨迹索引
self.travelStatus = 0 #0,表示为行驶,1表示开始行驶
self.carId = "" #车机号
self.sn = 0 #消息流水号
self.travelDirection = 0 #行驶方向,0表示正向行驶,1表示反向行驶
# 定义要发送的obd数据
self.OBDdata = {}
# 定义初始的obd数据,与上面的OBD数据保持一致,主要用于汽车行驶过程中数据变化量的计算
self.OBDdataOri = {}
#设置套接字
def setSocket(self,data):
self.socket = data
def setSendDur(self,data):
self.sendDur = data
def setTimeout(self,data):
self.timeout = data
def setCarId(self,data):
self.carId = data
def setData(self,data):
self.data = data
def getWebsocket(self):
return self.websocket
def sendMsg(self,msg):
self.socket.setTimeOut(self.timeout)
self.socket.send(msg)
def revMsg(self):
self.socket.setTimeOut(self.timeout)
return self.socket.receive()
#websocket向网页发送消息,可指定消息的描述类型
def serviceSendMsg(self,msg):
self.sendMsg(msg)
type = self.getMsgFunId(msg)
self.websocket.send(">>>>" + type + ":" + msg)
########################################################
#启动与页面交互的websockt服务
########################################################
def websocketService(self):
self.websocket = Websocket_service()
self.websocket.setHost("0.0.0.0")
self.websocket.setPort(5007)
self.websocket.startWebsocketServer()
...@@ -40,7 +40,7 @@ class ProtocolSimulaterDataService(): ...@@ -40,7 +40,7 @@ class ProtocolSimulaterDataService():
data["curDayTravel"]["theOil"] = 0 #本次行驶总油耗 data["curDayTravel"]["theOil"] = 0 #本次行驶总油耗
data["curDayTravel"]["theTime"] = 0 #本次行驶总时间 data["curDayTravel"]["theTime"] = 0 #本次行驶总时间
data["travelData"] = {} #定义所有行驶数据 data["travelData"] = {} #定义所有行驶数据
data["travelData"]["totallMilleage"] = 0 #行驶总里程 data["travelData"]["totalMilleage"] = 0 #行驶总里程
data["travelData"]["totalOil"] = 0 #行驶总油耗 data["travelData"]["totalOil"] = 0 #行驶总油耗
data["travelData"]["totalTime"] = 0 #行驶总时间 data["travelData"]["totalTime"] = 0 #行驶总时间
return data return data
...@@ -71,6 +71,19 @@ class ProtocolSimulaterDataService(): ...@@ -71,6 +71,19 @@ class ProtocolSimulaterDataService():
self.data["curDayTravel"]["theTime"] = data self.data["curDayTravel"]["theTime"] = data
self.writeToFile(self.path + self.fileName,self.data) self.writeToFile(self.path + self.fileName,self.data)
#设总里程,同时写入文件
def setTotalMilleage(self,data):
self.data["travelData"]["totalMilleage"] = data
self.writeToFile(self.path + self.fileName,self.data)
#设总油耗,同时写入文件
def setTotalOil(self,data):
self.data["travelData"]["totalOil"] = data
self.writeToFile(self.path + self.fileName,self.data)
#设总时间,同时写入文件
def setTotalTime(self,data):
self.data["travelData"]["totalTime"] = data
self.writeToFile(self.path + self.fileName,self.data)
#设今日日期时间 #设今日日期时间
def setDateTime2file(self,data): def setDateTime2file(self,data):
self.data["time"]["dateTime"] = data self.data["time"]["dateTime"] = data
......
...@@ -113,25 +113,26 @@ class ProtocolSimulaterService(): ...@@ -113,25 +113,26 @@ class ProtocolSimulaterService():
self.OBDdata["totalOilExpen"], self.OBDdata["totalRunTime"]) self.OBDdata["totalOilExpen"], self.OBDdata["totalRunTime"])
self.OBDdata["engineSpeed"] = 3000 self.OBDdata["engineSpeed"] = 3000
self.OBDdata["speed"] = int(self.data["travelData"]["carSpeed"]) self.OBDdata["speed"] = int(self.data["travelData"]["carSpeed"])
self.OBDdata["meterMileage"] = self.OBDdata["meterMileage"] + int( self.OBDdata["meterMileage"] = self.OBDdata["meterMileage"] + int(self.sendDur * (self.OBDdata["speed"] * 1000 / 3600))
self.sendDur * (self.OBDdata["speed"] * 1000 / 3600)) self.OBDdata["totailMileage"] = self.OBDdata["totailMileage"] + int(self.sendDur * (self.OBDdata["speed"] * 1000 / 3600))
self.OBDdata["totailMileage"] = self.OBDdata["totailMileage"] + int(
self.sendDur * (self.OBDdata["speed"] * 1000 / 3600))
oilExpend = int(self.data["travelData"]["oilExpend"]) oilExpend = int(self.data["travelData"]["oilExpend"])
self.OBDdata["totalOilExpen"] = self.OBDdata["totalOilExpen"] + int( self.OBDdata["totalOilExpen"] = self.OBDdata["totalOilExpen"] + int((self.sendDur * (self.OBDdata["speed"] * 1000 / 3600)) * (1000 / (oilExpend * 1000)))
(self.sendDur * (self.OBDdata["speed"] * 1000 / 3600)) * (1000 / (oilExpend * 1000)))
self.OBDdata["totalRunTime"] = self.OBDdata["totalRunTime"] + self.sendDur self.OBDdata["totalRunTime"] = self.OBDdata["totalRunTime"] + self.sendDur
latitude = self.gpsLine[self.gpsLineIndex]["lat"] latitude = self.gpsLine[self.gpsLineIndex]["lat"]
longitude = self.gpsLine[self.gpsLineIndex]["lng"] longitude = self.gpsLine[self.gpsLineIndex]["lng"]
gpsMsg = self.genGPSMsg(latitude, longitude) gpsMsg = self.genGPSMsg(latitude, longitude)
self.carDataObj.setTodayTotalMilleage(self.carData["curDayTravel"]["todayTotalMilleage"] + self.OBDdata["totailMileage"] - self.OBDdataOri["totailMileage"]) self.carDataObj.setTodayTotalMilleage(self.carData["curDayTravel"]["todayTotalMilleage"] + self.OBDdata["totailMileage"] - self.OBDdataOri["totailMileage"])
self.carDataObj.setTheMilleage(self.carData["curDayTravel"]["theMilleage"] + self.OBDdata["totailMileage"] -self.OBDdataOri["totailMileage"]) self.carDataObj.setTheMilleage(self.carData["curDayTravel"]["theMilleage"] + self.OBDdata["totailMileage"] -self.OBDdataOri["totailMileage"])
self.OBDdataOri["totailMileage"] = self.OBDdata["totailMileage"] self.carDataObj.setTotalMilleage(self.carData["travelData"]["totalMilleage"] + self.OBDdata["totailMileage"] - self.OBDdataOri["totailMileage"])
temp = self.OBDdata["totailMileage"]
self.OBDdataOri["totailMileage"] = temp
self.carDataObj.setTodayTodayTotalOil(self.carData["curDayTravel"]["todayTotalOil"] + self.OBDdata["totalOilExpen"] - self.OBDdataOri["totalOilExpen"]) self.carDataObj.setTodayTodayTotalOil(self.carData["curDayTravel"]["todayTotalOil"] + self.OBDdata["totalOilExpen"] - self.OBDdataOri["totalOilExpen"])
self.carDataObj.setTheOil(self.carData["curDayTravel"]["theOil"] + self.OBDdata["totalOilExpen"] - self.OBDdataOri["totalOilExpen"]) self.carDataObj.setTheOil(self.carData["curDayTravel"]["theOil"] + self.OBDdata["totalOilExpen"] - self.OBDdataOri["totalOilExpen"])
self.carDataObj.setTotalOil(self.carData["travelData"]["totalOil"] + self.OBDdata["totalOilExpen"] - self.OBDdataOri["totalOilExpen"])
self.OBDdataOri["totalOilExpen"] = self.OBDdata["totalOilExpen"] self.OBDdataOri["totalOilExpen"] = self.OBDdata["totalOilExpen"]
self.carDataObj.setTodayTodayTotalTime(self.carData["curDayTravel"]["todayTotalTime"] + self.OBDdata["totalRunTime"] - self.OBDdataOri["totalRunTime"]) self.carDataObj.setTodayTodayTotalTime(self.carData["curDayTravel"]["todayTotalTime"] + self.OBDdata["totalRunTime"] - self.OBDdataOri["totalRunTime"])
self.carDataObj.setTheTime(self.carData["curDayTravel"]["theTime"] + self.OBDdata["totalRunTime"] - self.OBDdataOri["totalRunTime"]) self.carDataObj.setTheTime(self.carData["curDayTravel"]["theTime"] + self.OBDdata["totalRunTime"] - self.OBDdataOri["totalRunTime"])
self.carDataObj.setTotalTime(self.carData["travelData"]["totalTime"] + self.OBDdata["totalRunTime"] - self.OBDdataOri["totalRunTime"])
self.OBDdataOri["totalRunTime"] = self.OBDdata["totalRunTime"] self.OBDdataOri["totalRunTime"] = self.OBDdata["totalRunTime"]
if OBDMsg != "": if OBDMsg != "":
self.sendMsg(OBDMsg) self.sendMsg(OBDMsg)
...@@ -269,11 +270,13 @@ class ProtocolSimulaterService(): ...@@ -269,11 +270,13 @@ class ProtocolSimulaterService():
self.carDataObj = ProtocolSimulaterDataService("data/protocolTools/carData/", dataFile) self.carDataObj = ProtocolSimulaterDataService("data/protocolTools/carData/", dataFile)
self.carDataObj.setData(conJson) self.carDataObj.setData(conJson)
if dateM == conJson["time"]["date"]: if dateM == conJson["time"]["date"]:
pass self.OBDdata["totailMileage"] = conJson["travelData"]["totalMilleage"]
self.OBDdataOri["totailMileage"] = conJson["travelData"]["totalMilleage"]
self.OBDdata["totalOilExpen"] = conJson["travelData"]["totalOil"]
self.OBDdataOri["totalOilExpen"] = conJson["travelData"]["totalOil"]
self.OBDdata["totalRunTime"] = conJson["travelData"]["totalTime"]
self.OBDdataOri["totalRunTime"] = conJson["travelData"]["totalTime"]
else: #如果不是当天日期,则将日期设置为当天,并写入车辆数据文件 else: #如果不是当天日期,则将日期设置为当天,并写入车辆数据文件
conJson["time"]["dateTime"] = dateTimeM
conJson["time"]["date"] = dateM
conJson["time"]["time"] = timeM
conJson["curDayTravel"]["todayTotalMilleage"] = 0 # 今日行驶总里程 conJson["curDayTravel"]["todayTotalMilleage"] = 0 # 今日行驶总里程
conJson["curDayTravel"]["todayTotalOil"] = 0 # 今日行驶总油耗 conJson["curDayTravel"]["todayTotalOil"] = 0 # 今日行驶总油耗
conJson["curDayTravel"]["todayTotalTime"] = 0 # 今日行驶总时间 conJson["curDayTravel"]["todayTotalTime"] = 0 # 今日行驶总时间
...@@ -300,7 +303,9 @@ class ProtocolSimulaterService(): ...@@ -300,7 +303,9 @@ class ProtocolSimulaterService():
self.sn = self.sn + 1 self.sn = self.sn + 1
self.websocket.send(type + ">>>>:" + gpsMsg) self.websocket.send(type + ">>>>:" + gpsMsg)
sleep(0.1) sleep(0.1)
OBDMsg = self.genOBDMsg() OBDMsg = self.genOBDMsg(self.OBDdata["fireStatus"],1,self.OBDdata["engineSpeed"], \
self.OBDdata["speed"],self.OBDdata["meterMileage"],self.OBDdata["totailMileage"], \
self.OBDdata["totalOilExpen"],self.OBDdata["totalRunTime"])
type = self.getMsgFunId(OBDMsg) type = self.getMsgFunId(OBDMsg)
self.sendMsg(OBDMsg) self.sendMsg(OBDMsg)
self.sn = self.sn + 1 self.sn = self.sn + 1
......
...@@ -7,6 +7,9 @@ from configparser import ConfigParser ...@@ -7,6 +7,9 @@ from configparser import ConfigParser
import json import json
import traceback import traceback
from lib.socket.ClientSocket import ClientSocket
from lib.socket.service.MessageSimulaterService import MessageSimulaterService
M_simulater_process = Blueprint('M_simulater_process', __name__) M_simulater_process = Blueprint('M_simulater_process', __name__)
connects = [] #用来保存连接的信息 connects = [] #用来保存连接的信息
...@@ -41,4 +44,43 @@ def porcessSocketSetting(): ...@@ -41,4 +44,43 @@ def porcessSocketSetting():
traceback.print_exc() traceback.print_exc()
data["status"] = "4003" data["status"] = "4003"
data["message"] = "Error: 处理失败!" data["message"] = "Error: 处理失败!"
return Response(json.dumps(data), mimetype='application/json')
##########################################
# 【接口类型】车机联网
##########################################
@M_simulater_process.route("/porcessConnect",methods=['POST'])
def porcessConnect():
params = request.get_data()
params = json.loads(params.decode("utf-8"))
print(params)
data = {}
try:
conf_R = ConfigParser()
conf_R.read("config/messageTools/carSimulater.conf")
if len(connects) < 1:
cliSocket = ClientSocket(conf_R.get("socket", "host"), conf_R.getint("socket", "port"))
cliSocket.setTimeOut(timeout)
cliSocket.connect()
connect = {}
socketName = "socket_" + str(len(connects) + 1)
connect["name"] = socketName
connects.append(connect)
service = MessageSimulaterService()
service.setSocket(cliSocket)
service.setTimeout(timeout)
service.setData(params)
service.setSocket(cliSocket)
service.startWebsocketService()
connects[0]["service"] = service
data["status"] = "200"
data["message"] = "创建连接成功!"
else:
data["status"] = "4003"
data["message"] = "已经创建了连接!"
except BaseException as e:
# 打印异常信息
traceback.print_exc()
data["status"] = "4003"
data["message"] = "Error: 连接失败!"
return Response(json.dumps(data), mimetype='application/json') return Response(json.dumps(data), mimetype='application/json')
\ 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