Commit cc9ab483 authored by liyuanhong's avatar liyuanhong

M300模拟器开发完成

parent 910ca259
{"time": {"dateTime": "2020-05-29 18:06:43", "date": "2020-05-29", "time": "18:06:43"}, "curDayTravel": {"todayTotalMilleage": 166, "todayTotalOil": 16, "todayTotalTime": 10, "theMilleage": 166, "theOil": 16, "theTime": 10}, "travelData": {"totalMilleage": 166, "totalOil": 16, "totalTime": 10}}
\ No newline at end of file
{"time": {"dateTime": "2020-05-28 10:09:51", "date": "2020-05-28", "time": "10:09:51"}, "curDayTravel": {"todayTotalMilleage": 5491, "todayTotalOil": 421, "todayTotalTime": 338, "theMilleage": 1497, "theOil": 102, "theTime": 93}, "travelData": {"totalMilleage": 341804, "totalOil": 32099, "totalTime": 20303}, "event": {"threeRapid": {"totalRapidlyAccelerate": 19, "totalSharpSlowdown": 18, "totalSharpTurn": 17}}} {"time": {"dateTime": "2020-05-29 14:34:14", "date": "2020-05-29", "time": "14:34:14"}, "curDayTravel": {"todayTotalMilleage": 1469, "todayTotalOil": 134, "todayTotalTime": 89, "theMilleage": 307, "theOil": 22, "theTime": 19}, "travelData": {"totalMilleage": 343273, "totalOil": 32233, "totalTime": 20392}, "event": {"threeRapid": {"totalRapidlyAccelerate": 19, "totalSharpSlowdown": 18, "totalSharpTurn": 17}}}
\ No newline at end of file \ No newline at end of file
...@@ -21,10 +21,12 @@ class Alarm_protocol_m300(M300Base): ...@@ -21,10 +21,12 @@ class Alarm_protocol_m300(M300Base):
self.GSMPkg = "0000000000" self.GSMPkg = "0000000000"
self.CANStatus = "ffffffffffffffffffff00000000000000000000" self.CANStatus = "ffffffffffffffffffff00000000000000000000"
else: else:
self.waterCode = data["waterCode"]
self.DEV_ID = data["DEV_ID"]
self.alarm = data["alarm"]
GPSData = data["GPSData"] GPSData = data["GPSData"]
GSMData = data["GSMData"] GSMData = data["GSMData"]
OBDData = data["OBDCANData"] OBDData = data["OBDCANData"]
self.alarm = data["alarm"]
self.GPSPkg = GPS_protocol_m300(dateInfo=GPSData["dateInfo"],latitude=float(GPSData["latitude"]),longitude=float(GPSData["longitude"]) \ self.GPSPkg = GPS_protocol_m300(dateInfo=GPSData["dateInfo"],latitude=float(GPSData["latitude"]),longitude=float(GPSData["longitude"]) \
,positionStar=int(GPSData["positionStar"]),speed=float(GPSData["speed"]),direction=float(GPSData["direction"]), \ ,positionStar=int(GPSData["positionStar"]),speed=float(GPSData["speed"]),direction=float(GPSData["direction"]), \
altitude=float(GPSData["altitude"]),ACCStatus=int(GPSData["ACCStatus"]),valtage=float(GPSData["valtage"]),OBDSpeed=float(GPSData["OBDSpeed"]), \ altitude=float(GPSData["altitude"]),ACCStatus=int(GPSData["ACCStatus"]),valtage=float(GPSData["valtage"]),OBDSpeed=float(GPSData["OBDSpeed"]), \
......
...@@ -66,9 +66,9 @@ class OBDCAN_protocol_m300(M300Base): ...@@ -66,9 +66,9 @@ class OBDCAN_protocol_m300(M300Base):
self.timeInfo = data self.timeInfo = data
def setAccstatus(self,data): def setAccstatus(self,data):
if data == 1: if data == 1:
return self.safeStatus | 1 self.safeStatus = self.safeStatus | 1
elif data == 0: elif data == 0:
return self.safeStatus & ~1 self.safeStatus = self.safeStatus & ~1
def setEngineSpeed(self,data): def setEngineSpeed(self,data):
self.engineSpeed = data self.engineSpeed = data
def setSpeed(self,data): def setSpeed(self,data):
......
...@@ -43,28 +43,6 @@ class M300SimulaterDataService(): ...@@ -43,28 +43,6 @@ class M300SimulaterDataService():
data["travelData"]["totalMilleage"] = 0 #行驶总里程 data["travelData"]["totalMilleage"] = 0 #行驶总里程
data["travelData"]["totalOil"] = 0 #行驶总油耗 data["travelData"]["totalOil"] = 0 #行驶总油耗
data["travelData"]["totalTime"] = 0 #行驶总时间 data["travelData"]["totalTime"] = 0 #行驶总时间
data["event"] = {}
data["event"]["threeRapid"] = {} #急加速,急减速,急转弯基本数据
data["event"]["threeRapid"]["totalRapidlyAccelerate"] = 0 #急加速总次数
data["event"]["threeRapid"]["totalSharpSlowdown"] = 0 #急减速总次数
data["event"]["threeRapid"]["totalSharpTurn"] = 0 #急转弯总次数
return data
####################################################
# 修复默认数据模板
# 用于在升级模拟器的时候,对增加的字段进行初始化
####################################################
def fixDataTemplate(self,data):
if not "event" in data:
data["event"] = {}
data["event"]["threeRapid"] = {}
data["event"]["threeRapid"]["totalRapidlyAccelerate"] = 0 # 急加速总次数
data["event"]["threeRapid"]["totalSharpSlowdown"] = 0 # 急减速总次数
data["event"]["threeRapid"]["totalSharpTurn"] = 0 # 急转弯总次数
if not "threeRapid" in data["event"]:
data["event"]["threeRapid"] = {}
data["event"]["threeRapid"]["totalRapidlyAccelerate"] = 0 #急加速总次数
data["event"]["threeRapid"]["totalSharpSlowdown"] = 0 #急减速总次数
data["event"]["threeRapid"]["totalSharpTurn"] = 0 #急转弯总次数
return data return data
#设今日行驶总里程,同时写入文件 #设今日行驶总里程,同时写入文件
...@@ -106,31 +84,6 @@ class M300SimulaterDataService(): ...@@ -106,31 +84,6 @@ class M300SimulaterDataService():
self.data["travelData"]["totalTime"] = data self.data["travelData"]["totalTime"] = data
self.writeToFile(self.path + self.fileName,self.data) self.writeToFile(self.path + self.fileName,self.data)
#设置急加速总次数,同时写入文件
def setTotalRapidlyAccelerateCount(self,data):
if not "event" in data:
data["event"] = {}
if not "threeRapid" in data["event"]:
data["event"]["threeRapid"] = {}
data["event"]["threeRapid"]["totalRapidlyAccelerate"] = data
self.writeToFile(self.path + self.fileName, self.data)
# 设置急减速总次数,同时写入文件
def setTotalSharpSlowdown(self,data):
if not "event" in data:
data["event"] = {}
if not "threeRapid" in data["event"]:
data["event"]["threeRapid"] = {}
data["event"]["threeRapid"]["totalSharpSlowdown"] = data
self.writeToFile(self.path + self.fileName, self.data)
# 设置急转弯总次数,同时写入文件
def setTotalSharpTurn(self,data):
if not "event" in data:
data["event"] = {}
if not "threeRapid" in data["event"]:
data["event"]["threeRapid"] = {}
data["event"]["threeRapid"]["totalSharpTurn"] = 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
......
#coding:utf-8
'''
M300车机模拟服务类
'''
import binascii
import json
import math
import os
import threading
import time
import traceback
from time import sleep
from lib.protocol.m300.Alarm_protocol_m300 import Alarm_protocol_m300
from lib.protocol.m300.GPS_protocol_m300 import GPS_protocol_m300
from lib.protocol.m300.Login_protocol_m300 import Login_protocol_m300
from lib.protocol.m300.OBDCAN_protocol_m300 import OBDCAN_protocol_m300
from lib.protocol.m300.VersionInfo_protocol_m300 import VersionInfo_protocol_m300
from lib.socket.service.M300SimulaterDataService import M300SimulaterDataService
from lib.socket.service.websocket_service import Websocket_service
class M300SimulaterService():
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.websocketId = "" # 当前连接的webSocketId
self.timeout = 1 #socket的超时时间
self.gpsLine = [] #GPS 轨迹
self.gpsLineIndex = 0 #GPS 轨迹索引
self.travelStatus = 0 #0,表示未行驶,1表示开始行驶同时开启了接收消息服务,2表示值开启了接收消息的服务
self.carId = "" #车机号
self.sn = 0 #消息流水号
self.travelDirection = 0 #行驶方向,0表示正向行驶,1表示反向行驶
self.directAngle = 59 #定义默认方向角
'''
为0表示正常发送,type为1表示数据写入本地
# 用来控制发送消息的方式(是正常发送,还是将发送的数据保存到本地,不发送)
'''
self.sendType = 0
self.GPSValid = 1 #用来控制GPS数据是有效还是无效 0:无效 1:有效
self.lngLatIsOk = 1 #用来控制经纬度是否都为0 0:都为0 1:正常
# 定义要发送的obd数据
self.OBDdata = {"accStatus":1,"engineSpeed":300,"speed":0,"dashboardTotailMilleage":6000,"totalMilleage":60,"totalOil":30,"carTotalRunTime":10}
# 定义初始的obd数据,与上面的OBD数据保持一致,主要用于汽车行驶过程中数据变化量的计算
self.OBDdataOri = {"accStatus":1,"engineSpeed": 300, "speed": 0,"dashboardTotailMilleage": 6000, "totalMilleage":60,"totalOil": 30, "carTotalRunTime": 10}
def getSn(self):
return self.sn
def getWebsocket(self):
return self.websocket
def getTravelStatus(self):
return self.travelStatus
def getCurLatitude(self):
return self.gpsLine[self.gpsLineIndex]["lat"]
def getCurLongtitude(self):
return self.gpsLine[self.gpsLineIndex]["lng"]
#设置套接字
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 setWebsocketId(self):
sleep(0.1)
self.websocketId = self.websocket.getCurrentClientId()
def setWebsocket(self,data):
self.websocket = data
def setSn(self,data):
self.sn = data
def setCarSpeed(self,data):
self.data["travelData"]["carSpeed"] = data
def setOilExpend(self,data):
self.data["travelData"]["oilExpend"] = data
def setSendDur(self,data):
self.sendDur = data
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.sendMsgToClient(">>>>" + type + ":" + msg,self.websocketId)
########################################################
#车机登录
########################################################
def carLogin(self):
loginObj = Login_protocol_m300(waterCode=self.sn,DEV_ID=self.data["carId"])
msg = loginObj.generateMsg()
self.sendMsg(msg)
type = self.getMsgFunId(msg)
info = type + ">>>>:" + msg
self.websocket.sendMsgToClient(info,self.websocketId)
self.sn = self.sn + 1
time.sleep(0.5)
verObj = VersionInfo_protocol_m300(waterCode=self.sn,DEV_ID=self.data["carId"],SWVersion=self.data["version"]["SWVersion"], \
SWDate=self.data["version"]["SWDate"],HWVersion=self.data["version"]["HWVersion"], GSMType=self.data["version"]["GSMType"], \
carType=int(self.data["version"]["carType"]),engineCode=int(self.data["version"]["engineCode"]),VINCode=self.data["version"]["VINCode"])
msg = verObj.generateMsg()
self.sendMsg(msg)
type = self.getMsgFunId(msg)
info = type + ">>>>:" + msg
self.websocket.sendMsgToClient(info, self.websocketId)
self.sn = self.sn + 1
########################################################
#车机点火
########################################################
def fireOn(self):
if not os.path.exists("data/m300Tools/carData/" + self.carId + ".json"):
psdsObj = M300SimulaterDataService()
data = psdsObj.genDataTemplate()
psdsObj.writeToFile("data/m300Tools/carData/" + self.carId + ".json",data)
#读取车机行驶数据
with open("data/m300Tools/carData/" + self.carId + ".json", "r", encoding="utf-8") as fi:
############################# 读取车机的数据 ############################
content = fi.read()
conJson = json.loads(content)
conJson["curDayTravel"]["theMilleage"] = 0 # 本次行驶总里程
conJson["curDayTravel"]["theOil"] = 0 # 本次行驶总油耗
conJson["curDayTravel"]["theTime"] = 0 # 本次行驶总时间
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)
dataFile = self.carId + ".json"
self.carDataObj = M300SimulaterDataService("data/m300Tools/carData/", dataFile)
self.carDataObj.setData(conJson)
if dateM == conJson["time"]["date"]:
self.OBDdata["totalMilleage"] = conJson["travelData"]["totalMilleage"]
self.OBDdataOri["totalMilleage"] = conJson["travelData"]["totalMilleage"]
self.OBDdata["totalOil"] = conJson["travelData"]["totalOil"]
self.OBDdataOri["totalOil"] = conJson["travelData"]["totalOil"]
self.OBDdata["carTotalRunTime"] = conJson["travelData"]["totalTime"]
self.OBDdataOri["carTotalRunTime"] = conJson["travelData"]["totalTime"]
else: #如果不是当天日期,则将日期设置为当天,并写入车辆数据文件
conJson["curDayTravel"]["todayTotalMilleage"] = 0 # 今日行驶总里程
conJson["curDayTravel"]["todayTotalOil"] = 0 # 今日行驶总油耗
conJson["curDayTravel"]["todayTotalTime"] = 0 # 今日行驶总时间
self.carDataObj.setTodayTotalMilleage(0)
self.carDataObj.setTodayTodayTotalOil(0)
self.carDataObj.setTodayTodayTotalTime(0)
self.carDataObj.setDateTime2file(dateTimeM)
self.carDataObj.setDate2file(dateM)
self.carDataObj.setTime2file(timeM)
self.OBDdata["totalMilleage"] = conJson["travelData"]["totalMilleage"]
self.OBDdataOri["totalMilleage"] = conJson["travelData"]["totalMilleage"]
self.OBDdata["totalOil"] = conJson["travelData"]["totalOil"]
self.OBDdataOri["totalOil"] = conJson["travelData"]["totalOil"]
self.OBDdata["carTotalRunTime"] = conJson["travelData"]["totalTime"]
self.OBDdataOri["carTotalRunTime"] = conJson["travelData"]["totalTime"]
self.carData = conJson
############################# 发送点火数据 ############################
fireOnParams = {"FUNID": "0021", "waterCode": "1", "DEV_ID": "M202004070000", "encryptionType": "0",
"GPSData": {"dateInfo": "2020-05-29 15:23:48", "latitude": 40.22077, "longitude": 116.23128,
"positionStar": "2", "speed": "66.0", "direction": "55.3", "altitude": "11.0",
"ACCStatus": "1", "valtage": "36.0", "OBDSpeed": "66.4", "valid": 1, "tripMark": "0"},
"OBDCANData": {"statusMask": "ffffffffffffffffffff", "safeStatus": 0, "doorStatus": 0, "lockStatus": 0,
"windowStatus": 0, "lightStatus": 0, "swichStatusA": 0, "swichStatusB": 0},
"GSMData": {"operatorType": "1", "LAC": "1234", "CellId": "5678"}, "alarm": {"0001": {}}}
timeStamp = time.time() - 8 * 3600
timeArray = time.localtime(timeStamp)
curTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
fireOnParams["DEV_ID"] = self.data["carId"]
fireOnParams["waterCode"] = self.sn
fireOnParams["GPSData"]["dateInfo"] = curTime
fireOnParams["GPSData"]["latitude"] = self.gpsLine[self.gpsLineIndex]["lat"]
fireOnParams["GPSData"]["longitude"] = self.gpsLine[self.gpsLineIndex]["lng"]
fireOnParams["GPSData"]["direction"] = self.getDirAngle()
msgObj = Alarm_protocol_m300(data=fireOnParams)
msg = msgObj.generateMsg()
self.sendMsg(msg)
type = self.getMsgFunId(msg)
info = type + ">>>>:" + msg
self.websocket.sendMsgToClient(info,self.websocketId)
self.sn = self.sn + 1
time.sleep(0.1)
gpsMsg = self.genGPSMsg(float(self.gpsLine[0]["lat"]), float(self.gpsLine[0]["lng"]))
type = self.getMsgFunId(gpsMsg)
self.sendMsg(gpsMsg)
self.sn = self.sn + 1
self.websocket.sendMsgToClient(type + ">>>>:" + gpsMsg, self.websocketId)
sleep(0.1)
OBDMsg = self.genOBDMsg(1, self.OBDdata["engineSpeed"],self.OBDdata["speed"], self.OBDdata["dashboardTotailMilleage"], \
self.OBDdata["totalMilleage"],self.OBDdata["totalOil"], self.OBDdata["carTotalRunTime"])
type = self.getMsgFunId(OBDMsg)
self.sendMsg(OBDMsg)
self.sn = self.sn + 1
self.websocket.sendMsgToClient(type + ">>>>:" + OBDMsg, self.websocketId)
########################################################
#车机行驶服务
########################################################
def serviceTrave(self):
while self.serviceStatus == 1:
gpsMsg = ""
OBDMsg = ""
if self.travelStatus == 0: #行驶服务未启动
latitude = self.gpsLine[self.gpsLineIndex]["lat"]
longitude = self.gpsLine[self.gpsLineIndex]["lng"]
gpsMsg = self.genGPSMsg(latitude,longitude)
elif self.travelStatus == 1: #行驶服务启动
if self.gpsLineIndex < len(self.gpsLine) and self.gpsLineIndex != -1: #如果正向行驶和反向行驶的轨迹点都没有跑完
OBDMsg = self.genOBDMsg(1, self.OBDdata["engineSpeed"], self.OBDdata["speed"],self.OBDdata["dashboardTotailMilleage"], \
self.OBDdata["totalMilleage"], self.OBDdata["totalOil"],self.OBDdata["carTotalRunTime"])
self.OBDdata["engineSpeed"] = 3000
self.OBDdata["speed"] = int(self.data["travelData"]["carSpeed"])
self.OBDdata["dashboardTotailMilleage"] = self.OBDdata["dashboardTotailMilleage"] + int(self.sendDur * (self.OBDdata["speed"] * 1000 / 3600))
self.OBDdata["totalMilleage"] = self.OBDdata["totalMilleage"] + int(self.sendDur * (self.OBDdata["speed"] * 1000 / 3600))
oilExpend = int(self.data["travelData"]["oilExpend"])
self.OBDdata["totalOil"] = self.OBDdata["totalOil"] + int((self.sendDur * (self.OBDdata["speed"] * 1000 / 3600)) * (1000 / (oilExpend *1000)))
self.OBDdata["carTotalRunTime"] = self.OBDdata["carTotalRunTime"] + self.sendDur
latitude = self.gpsLine[self.gpsLineIndex]["lat"]
longitude = self.gpsLine[self.gpsLineIndex]["lng"]
gpsMsg = self.genGPSMsg(latitude, longitude)
if self.travelDirection == 0:
self.gpsLineIndex = self.gpsLineIndex + 1 #正向行驶
else:
self.gpsLineIndex = self.gpsLineIndex - 1 #反向行驶
elif self.gpsLineIndex == len(self.gpsLine) or self.gpsLineIndex == -1: #如果反向行驶和反向行驶刚好跑完
if int(self.data["travelData"]["travelLoop"]) == 0: #没有设置循环行驶
self.gpsLineIndex = self.gpsLineIndex - 1
self.stopTravel()
self.websocket.sendMsgToClient("gps轨迹跑完,自动停止行驶!",self.websocketId)
else: #设置了循环行驶
if self.travelDirection == 0:
self.gpsLineIndex = self.gpsLineIndex - 1
self.travelDirection = 1
self.websocket.sendMsgToClient("gps轨迹正向行驶跑完,变换行驶方向......",self.websocketId)
else:
self.gpsLineIndex = self.gpsLineIndex + 1
self.travelDirection = 0
self.websocket.sendMsgToClient("gps轨迹反向行驶跑完,变换行驶方向......",self.websocketId)
OBDMsg = self.genOBDMsg(1, self.OBDdata["engineSpeed"], self.OBDdata["speed"],self.OBDdata["dashboardTotailMilleage"], \
self.OBDdata["totalMilleage"], self.OBDdata["totalOil"],self.OBDdata["carTotalRunTime"])
self.OBDdata["engineSpeed"] = 3000
self.OBDdata["speed"] = int(self.data["travelData"]["carSpeed"])
self.OBDdata["dashboardTotailMilleage"] = self.OBDdata["dashboardTotailMilleage"] + int(self.sendDur * (self.OBDdata["speed"] * 1000 / 3600))
self.OBDdata["totalMilleage"] = self.OBDdata["totalMilleage"] + int(self.sendDur * (self.OBDdata["speed"] * 1000 / 3600))
oilExpend = int(self.data["travelData"]["oilExpend"])
self.OBDdata["totalOil"] = self.OBDdata["totalOil"] + int((self.sendDur * (self.OBDdata["speed"] * 1000 / 3600)) * (1000 / (oilExpend * 1000)))
self.OBDdata["carTotalRunTime"] = self.OBDdata["carTotalRunTime"] + self.sendDur
latitude = self.gpsLine[self.gpsLineIndex]["lat"]
longitude = self.gpsLine[self.gpsLineIndex]["lng"]
gpsMsg = self.genGPSMsg(latitude, longitude)
self.carDataObj.setTodayTotalMilleage(self.carData["curDayTravel"]["todayTotalMilleage"] + self.OBDdata["totalMilleage"] - self.OBDdataOri["totalMilleage"])
self.carDataObj.setTheMilleage(self.carData["curDayTravel"]["theMilleage"] + self.OBDdata["totalMilleage"] -self.OBDdataOri["totalMilleage"])
self.carDataObj.setTotalMilleage(self.carData["travelData"]["totalMilleage"] + self.OBDdata["totalMilleage"] - self.OBDdataOri["totalMilleage"])
temp = self.OBDdata["totalMilleage"]
self.OBDdataOri["totalMilleage"] = temp
self.carDataObj.setTodayTodayTotalOil(self.carData["curDayTravel"]["todayTotalOil"] + self.OBDdata["totalOil"] - self.OBDdataOri["totalOil"])
self.carDataObj.setTheOil(self.carData["curDayTravel"]["theOil"] + self.OBDdata["totalOil"] - self.OBDdataOri["totalOil"])
self.carDataObj.setTotalOil(self.carData["travelData"]["totalOil"] + self.OBDdata["totalOil"] - self.OBDdataOri["totalOil"])
self.OBDdataOri["totalOil"] = self.OBDdata["totalOil"]
self.carDataObj.setTodayTodayTotalTime(self.carData["curDayTravel"]["todayTotalTime"] + self.OBDdata["carTotalRunTime"] - self.OBDdataOri["carTotalRunTime"])
self.carDataObj.setTheTime(self.carData["curDayTravel"]["theTime"] + self.OBDdata["carTotalRunTime"] - self.OBDdataOri["carTotalRunTime"])
self.carDataObj.setTotalTime(self.carData["travelData"]["totalTime"] + self.OBDdata["carTotalRunTime"] - self.OBDdataOri["carTotalRunTime"])
self.OBDdataOri["carTotalRunTime"] = self.OBDdata["carTotalRunTime"]
if OBDMsg != "":
self.sendMsg(OBDMsg)
self.sn = self.sn + 1
type = self.getMsgFunId(OBDMsg)
info = type + ">>>>:" + OBDMsg
self.websocket.sendMsgToClient(info,self.websocketId)
if gpsMsg != "":
sleep(0.1)
self.sendMsg(gpsMsg)
self.sn = self.sn + 1
type = self.getMsgFunId(gpsMsg)
info = type + ">>>>:" + gpsMsg
self.websocket.sendMsgToClient(info,self.websocketId)
sleep(self.sendDur)
# 熄火,发送熄火事件
def fireOff(self):
gpsLineIndex = self.gpsLineIndex
if gpsLineIndex >= len(self.gpsLine):
gpsLineIndex = gpsLineIndex - 1
fireOffParams = {"FUNID": "0021", "waterCode": "1", "DEV_ID": "M202004070000", "encryptionType": "0",
"GPSData": {"dateInfo": "2020-05-29 15:23:48", "latitude": 40.22077, "longitude": 116.23128,
"positionStar": "2", "speed": "66.0", "direction": "55.3", "altitude": "11.0",
"ACCStatus": "1", "valtage": "36.0", "OBDSpeed": "66.4", "valid": 1, "tripMark": "0"},
"OBDCANData": {"statusMask": "ffffffffffffffffffff", "safeStatus": 0, "doorStatus": 0, "lockStatus": 0,
"windowStatus": 0, "lightStatus": 0, "swichStatusA": 0, "swichStatusB": 0},
"GSMData": {"operatorType": "1", "LAC": "1234", "CellId": "5678"}, "alarm": {"0002": {}}}
timeStamp = time.time() - 8 * 3600
timeArray = time.localtime(timeStamp)
curTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
fireOffParams["DEV_ID"] = self.data["carId"]
fireOffParams["waterCode"] = self.sn
fireOffParams["GPSData"]["dateInfo"] = curTime
fireOffParams["GPSData"]["latitude"] = self.gpsLine[self.gpsLineIndex]["lat"]
fireOffParams["GPSData"]["longitude"] = self.gpsLine[self.gpsLineIndex]["lng"]
fireOffParams["GPSData"]["direction"] = self.getDirAngle()
msgObj = Alarm_protocol_m300(data=fireOffParams)
msg = msgObj.generateMsg()
self.sendMsg(msg)
type = self.getMsgFunId(msg)
info = type + ">>>>:" + msg
self.websocket.sendMsgToClient(info,self.websocketId)
self.sn = self.sn + 1
# time.sleep(0.1)
# gpsMsg = self.genGPSMsg(float(self.gpsLine[0]["lat"]), float(self.gpsLine[0]["lng"]))
# type = self.getMsgFunId(gpsMsg)
# self.sendMsg(gpsMsg)
# self.sn = self.sn + 1
# self.websocket.sendMsgToClient(type + ">>>>:" + gpsMsg, self.websocketId)
# sleep(0.1)
# OBDMsg = self.genOBDMsg(0, self.OBDdata["engineSpeed"],self.OBDdata["speed"], self.OBDdata["dashboardTotailMilleage"], \
# self.OBDdata["totalMilleage"], self.OBDdata["totalOil"], self.OBDdata["carTotalRunTime"])
# type = self.getMsgFunId(OBDMsg)
# self.sendMsg(OBDMsg)
# self.sn = self.sn + 1
# self.websocket.sendMsgToClient(type + ">>>>:" + OBDMsg, self.websocketId)
#根据特定参数,生成GPS消息
def genGPSMsg(self,latitude,longtitude):
gpsObj = GPS_protocol_m300(waterCode=self.sn,DEV_ID=self.data["carId"])
gpsObj.setLatitude(float(latitude))
gpsObj.setLongitude(float(longtitude))
gpsObj.setDirection(self.getDirAngle())
timeS = int(time.time()) - 8 * 3600
timeArray = time.localtime(timeS)
UTCTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
gpsObj.setDateInfo(UTCTime)
msg = gpsObj.generateMsg()
return msg
#根据特定参数,生成GPS消息体,不包含消息头
def genGPSData(self,latitude,longtitude):
gpsObj = GPS_protocol_m300(waterCode=self.sn,DEV_ID=self.data["carId"])
gpsObj.setLatitude(float(latitude))
gpsObj.setLongitude(float(longtitude))
gpsObj.setDirection(self.getDirAngle())
timeS = int(time.time()) - 8 * 3600
timeArray = time.localtime(timeS)
UTCTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
gpsObj.setDateInfo(UTCTime)
data = gpsObj.generateMsg()
return data
#根据当前所在GPS点,生成GPS消息体,不包含消息头
def genGPSData2(self):
gpsObj = GPS_protocol_m300(waterCode=self.sn,DEV_ID=self.data["carId"])
gpsObj.setLatitude(self.gpsLine[self.gpsLineIndex]["lat"])
gpsObj.setLongitude(self.gpsLine[self.gpsLineIndex]["lng"])
gpsObj.setDirection(self.getDirAngle())
timeS = int(time.time()) - 8 * 3600
timeArray = time.localtime(timeS)
UTCTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
gpsObj.setDateInfo(UTCTime)
data = gpsObj.generateMsg()
return data
# 根据特定参数,生成OBD CAN消息
def genOBDMsg(self,accStatus=1,engineSpeed=300,speed=0,dashboardTotailMilleage=6000,totalMilleage=60,totalOil=30,carTotalRunTime=10):
OBDObj = OBDCAN_protocol_m300(waterCode=self.sn,DEV_ID=self.data["carId"])
timeS = int(time.time()) - 8 * 3600
timeArray = time.localtime(timeS)
UTCTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
OBDObj.setTimeInfo(UTCTime)
OBDObj.setAccstatus(accStatus)
OBDObj.setEngineSpeed(engineSpeed) # 设置发动机转速
OBDObj.setSpeed(speed) # 设置车辆速度
OBDObj.setDashboardTotailMilleage(dashboardTotailMilleage) # 设置仪表里程值
OBDObj.setTotalMilleage(totalMilleage) # 设置总里程值
OBDObj.setTotalOil(totalOil) # 设置总耗油量
OBDObj.setCarTotalRunTime(carTotalRunTime) # 设置车辆运行时间
msg = OBDObj.generateMsg()
return msg
###########################################################
#获取方向角
###########################################################
def getDirAngle(self):
dire = self.directAngle
if self.travelDirection == 0:
if self.gpsLineIndex == 0:
return int(self.directAngle)
lngCut = (float(self.gpsLine[self.gpsLineIndex]["lng"]) - float(self.gpsLine[self.gpsLineIndex - 1]["lng"])) * 1000000
latCut = (float(self.gpsLine[self.gpsLineIndex]["lat"]) - float(self.gpsLine[self.gpsLineIndex - 1]["lat"])) * 1000000
if latCut == 0: #除数维度不能为0
latCut = 1
if lngCut == 0 or latCut == 0:
return int(self.directAngle)
val = lngCut / latCut
dire = math.atan2(1, val) * 180 / math.pi
if lngCut > 0 and latCut > 0:
dire = 90 - dire
if lngCut < 0 and latCut > 0:
dire = 270 + 180 - dire
elif latCut < 0 and lngCut > 0:
dire = 270 - dire
elif lngCut < 0 and latCut < 0:
dire = 180 + 90 - dire
self.directAngle = dire
elif self.travelDirection == 1:
if self.gpsLineIndex == (len(self.gpsLine) - 1):
return int(self.directAngle)
lngCut = (float(self.gpsLine[self.gpsLineIndex]["lng"]) - float(self.gpsLine[self.gpsLineIndex + 1]["lng"])) * 1000000
latCut = (float(self.gpsLine[self.gpsLineIndex]["lat"]) - float(self.gpsLine[self.gpsLineIndex + 1]["lat"])) * 1000000
if latCut == 0: #除数维度不能为0
latCut = 1
if lngCut == 0 or latCut == 0:
return int(self.directAngle)
val = lngCut / latCut
dire = math.atan2(1, val) * 180 / math.pi
if lngCut > 0 and latCut > 0:
dire = 90 - dire
if lngCut < 0 and latCut > 0:
dire = 270 + 180 - dire
elif latCut < 0 and lngCut > 0:
dire = 270 - dire
elif lngCut < 0 and latCut < 0:
dire = 180 + 90 - dire
self.directAngle = dire
return int(dire)
########################################################
# 接收消息的服务
########################################################
def serviceRev(self):
self.serviceStatus = 2 #2代表只启动了接收消息的进程,1代表了接收和发送都启动了
while self.serviceStatus != 0:
timeStamp = time.time()
timeArray = time.localtime(timeStamp)
curTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
self.socket.setTimeOut(self.timeout)
d = self.revMsg()
d = str(binascii.b2a_hex(d))[2:][:-1]
type = self.getMsgFunId(d)
info = type + "<<<<:" + d
self.websocket.sendMsgToClient(info,self.websocketId)
self.doResponse(d)
########################################################
#启动与页面交互的websockt服务
########################################################
def websocketService(self):
self.websocket = Websocket_service()
self.websocket.setHost("0.0.0.0")
self.websocket.setPort(5009)
self.websocket.startWebsocketServer()
########################################################
#启动与页面交互的websocket服务
########################################################
def startWebsocketService(self):
if self.websocket == None:
t = threading.Thread(target=self.websocketService, args=())
t.start()
t3 = threading.Thread(target=self.setWebsocketId, args=())
t3.start()
# 为websocket服务添加一个新的客户端连接
def addNewWebsocket(self):
t3 = threading.Thread(target=self.setWebsocketId, args=())
t3.start()
########################################################
#停止websocket服务
########################################################
def stopWebsocketService(self):
try:
self.websocket.close()
self.websocket = None
except BaseException as e:
# 打印异常信息
traceback.print_exc()
########################################################
#关闭车机的连接
########################################################
def closeSocket(self):
try:
self.socket.close()
except BaseException as e:
# 打印异常信息
traceback.print_exc
########################################################
#获取收到消息的功能id
########################################################
def getMsgFunId(self,msg):
funId = msg[2:6]
return funId
########################################################
#收到 某些类型的消息后执行回复操作
########################################################
def doResponse(self,msg):
msgFunId = self.getMsgFunId(msg)
#设置GPS轨迹
def setGpsLine(self,fileName):
with open("data/m300Tools/GPSLines/" + fileName,"r",encoding="utf-8") as fi:
content = fi.read()
conJson = json.loads(content)
self.gpsLine = conJson["GPSLine"]
########################################################
#启动接收消息的服务
########################################################
def startReciveService(self):
t2 = threading.Thread(target=self.serviceRev, args=())
t2.start()
########################################################
# 开启发送消息的服务
########################################################
def startService(self):
self.serviceStatus = 1
t1 = threading.Thread(target=self.serviceTrave,args=())
t1.start()
########################################################
#停止发送消息的服务
########################################################
def stopService(self):
self.serviceStatus = 0
self.gpsLine = []
self.gpsLineIndex = 0
self.travelStatus = 0
########################################################
# 开始行驶
########################################################
def startTravel(self):
self.travelStatus = 1
########################################################
# 停止行驶
########################################################
def stopTravel(self):
self.travelStatus = 0
self.serviceStatus = 0
\ No newline at end of file
...@@ -106,7 +106,7 @@ class MessageSimulaterService(): ...@@ -106,7 +106,7 @@ class MessageSimulaterService():
def revMsg(self): def revMsg(self):
self.socket.setTimeOut(self.timeout) self.socket.setTimeOut(self.timeout)
return self.socket.receive() return self.socket.receive()
#websocket向网页发送消息,可指定消息的描述类型 #websocket向网页发送消息
def serviceSendMsg(self,msg): def serviceSendMsg(self,msg):
self.sendMsg(msg) self.sendMsg(msg)
type = self.getMsgFunId(msg) type = self.getMsgFunId(msg)
......
...@@ -447,12 +447,12 @@ class ProtocolSimulaterService(): ...@@ -447,12 +447,12 @@ class ProtocolSimulaterService():
self.sn = self.sn + 1 self.sn = self.sn + 1
self.websocket.sendMsgToClient(type + ">>>>:" + msg, self.websocketId) self.websocket.sendMsgToClient(type + ">>>>:" + msg, self.websocketId)
sleep(0.1) # sleep(0.1)
gpsMsg = self.genGPSMsg(self.gpsLine[gpsLineIndex]["lat"], self.gpsLine[gpsLineIndex]["lng"]) # gpsMsg = self.genGPSMsg(self.gpsLine[gpsLineIndex]["lat"], self.gpsLine[gpsLineIndex]["lng"])
type = self.getMsgFunId(gpsMsg) # type = self.getMsgFunId(gpsMsg)
self.sendMsg(gpsMsg) # self.sendMsg(gpsMsg)
self.sn = self.sn + 1 # self.sn = self.sn + 1
self.websocket.sendMsgToClient(type + ">>>>:" + gpsMsg,self.websocketId) # self.websocket.sendMsgToClient(type + ">>>>:" + gpsMsg,self.websocketId)
#根据特定参数,生成GPS消息 #根据特定参数,生成GPS消息
def genGPSMsg(self,latitude,longtitude,direct=0): def genGPSMsg(self,latitude,longtitude,direct=0):
......
...@@ -38,81 +38,75 @@ ...@@ -38,81 +38,75 @@
{% block content_1 %} {% block content_1 %}
<div id="container3" style="width:100%;min-height:750px;float:left;_background:green;margin-top:10px;_border-top: 1px solid #eee;"> <div id="container3" style="width:100%;min-height:750px;float:left;_background:green;margin-top:10px;_border-top: 1px solid #eee;">
<div style="width:100%;padding-bottom:10px;border-bottom: 1px solid #eee;"> <div style="width:100%;padding-bottom:10px;border-bottom: 1px solid #eee;">
<span><label>车机Id:</label><input id="carId" type="text" class="form-control" value="M202003060540"></span> <span><label>车机Id:</label><input id="carId" type="text" class="form-control" value="M202003060518"></span>
<span><label>上报间隔(秒):</label><input id="durTime" style="width:60px;" type="text" class="form-control" value="5"></span> <span><label>上报间隔(秒):</label><input id="durTime" style="width:60px;" type="text" class="form-control" value="5"></span>
<span><label>设置超时时间:</label><input style="width:80px;" id="timeout" type="text" class="form-control" value="36000"></span> <span><label>设置超时时间:</label><input style="width:80px;" id="timeout" type="text" class="form-control" value="36000"></span>
</div> </div>
<!-- <div style="display: block; width: 100%; border-width: 1px; border-style: solid; border-color: darkgray; border-radius: 10px; padding: 2px; margin-top: 5px;">--> <div style="display: block; width: 100%; border-width: 1px; border-style: solid; border-color: darkgray; border-radius: 10px; padding: 2px; margin-top: 5px;">
<!-- <h5><b>多人在线状态面板:</b></h5>--> <h5><b>多人在线状态面板:</b></h5>
<!-- <span><label>我的id:</label><input disabled=disabled type="text" id="curSession" class="form-control" style="display:inline;width:200px;" value=""/></span>--> <span><label>我的id:</label><input disabled=disabled type="text" id="curSession" class="form-control" style="display:inline;width:200px;" value=""/></span>
<!-- <span><label>在线人数:</label><input disabled=disabled type="text" id="totalSessionNums" class="form-control" style="display:inline;width:80px;" value="1"/></span>--> <span><label>在线人数:</label><input disabled=disabled type="text" id="totalSessionNums" class="form-control" style="display:inline;width:80px;" value="1"/></span>
<!-- <button id="sessionRefresh" type="button" class="btn btn-primary" onclick="getAllUsers(this)">刷新</button><label style="font-size:10px;width:100px;">刷新后,可在控制台查看在线用户详细信息</label>--> <button id="sessionRefresh" type="button" class="btn btn-primary" onclick="getAllUsers(this)">刷新</button><label style="font-size:10px;width:100px;">刷新后,可在控制台查看在线用户详细信息</label>
<!-- </div>--> </div>
<!-- <div style="width:100%;_padding-bottom:10px;border-bottom: 1px solid #eee;">--> <div style="width:100%;_padding-bottom:10px;border-bottom: 1px solid #eee;">
<!--&lt;!&ndash; <h4>点击登录按钮发送报文:</h4>&ndash;&gt;--> <!-- <h4>点击登录按钮发送报文:</h4>-->
<!-- <div style="display: block; width: 100%; border-width: 1px; border-style: solid; border-color: darkgray; border-radius: 10px; padding: 2px; margin-top: 5px;">--> <div style="display: block; width: 100%; border-width: 1px; border-style: solid; border-color: darkgray; border-radius: 10px; padding: 2px; margin-top: 5px;">
<!-- <h5><b>登录报文数据:</b>--> <h5><b>登录报文数据:</b>
<!-- <span style="border-width:1px;border-style:solid;border-color:darkgray;border-radius:10px;padding:1px 10px;">--> <span style="border-width:1px;border-style:solid;border-color:darkgray;border-radius:10px;padding:1px 10px;">
<!-- <label><input name="login" type="radio" value="0" checked="checked" onclick="isShowLoginArea(this)"/>隐藏</label>--> <label><input name="login" type="radio" value="0" checked="checked" onclick="isShowLoginArea(this)"/>隐藏</label>
<!-- <label style="margin-left:10px;"><input name="login" type="radio" value="1" onclick="isShowLoginArea(this)"/>显示</label>--> <label style="margin-left:10px;"><input name="login" type="radio" value="1" onclick="isShowLoginArea(this)"/>显示</label>
<!-- </span>--> </span>
<!-- </h5>--> </h5>
<!-- <div id="login_area" style="display:none;">--> <div id="login_area" style="display:none;">
<!-- <ul class="protocol_content" style="padding:0px;">--> <ul class="protocol_content" style="padding:0px;">
<!-- <li style="width:320px;"><label>CPU-ID:</label><input style="width:220px;" id="cpuId" type="text" class="form-control" value="CPU-ID001122334455667788"></li>--> <li><label>软件版本号:</label><input id="SWVersion" type="text" class="form-control" value="VSTA000GV100"></li>
<!-- <li><label style="word-break:break-all;font-size:12px;">SIM卡IMSI号:</label><input id="imsi" type="text" class="form-control" value="IMSI13145678902"></li>--> <li><label>软件日期:</label><input id="SWDate" type="text" class="form-control" value="2020-03-30"></li>
<!-- <li style="width:300px;"><label style="word-break:break-all;font-size:12px;">SIM卡CCID号:</label><input style="width:200px;" id="ccid" type="text" class="form-control" value="CCID1122334455667788"></li>--> <li><label>硬件版本:</label><input id="HWVersion" type="text" class="form-control" value="M1.0"></li>
<!-- <li><label style="word-break:break-all;font-size:10px;">GSM模块IMEI码:</label><input id="imei" type="text" class="form-control" value="IMEI12233445566"></li>--> <li><label>GSM 型号:</label><input id="GSMType" type="text" class="form-control" value="GSM_type_123456"></li>
<!-- </ul>--> <li><label>车系车型ID:</label><input id="carType" type="text" class="form-control" value="150"></li>
<li><label style="word-break:break-all;font-size:10px;">发动机编码类别:</label><input id="engineCode" type="text" class="form-control" value="1"></li>
<!-- <ul class="protocol_content" style="padding:0px;">--> <li style="width:350px;"><label style="word-break:break-all;font-size:10px;">汽车VIN码或发动机ECU编码:</label><input style="width:250px;" id="VINCode" type="text" class="form-control" value="VIN_CODE_01234567890"></li>
<!-- <li style="width:320px;"><label style="word-break:break-all;font-size:12px;">车机版本信息:</label><input style="width:220px;" id="verInfo" type="text" class="form-control" value="M100AB01010.0000"></li>--> </ul>
<!-- <li><label>编译日期:</label><input id="compileDate" type="text" class="form-control" value="2020-03-23"></li>--> </div>
<!-- <li style="width:300px;"><label style="word-break:break-all;font-size:12px;">GSM模块型号:</label><input style="width:200px;" id="GSM" type="text" class="form-control" value="GSM_123456"></li>--> </div>
<!-- </ul>--> </div>
<!-- </div>--> <div style="display: block; width: 100%; border-width: 1px; border-style: solid; border-color: darkgray; border-radius: 10px; padding: 2px; margin-top: 5px;">
<!-- </div>--> <h5><b>GPS行驶轨迹设置:</b></h5>
<!-- </div>--> <div class="input-group" style="width:380px;padding-bottom:10px;margin-left:10px;display:inline;">
<!-- <div style="display: block; width: 100%; border-width: 1px; border-style: solid; border-color: darkgray; border-radius: 10px; padding: 2px; margin-top: 5px;">--> <form id="form" enctype="multipart/form-data">
<!-- <h5><b>GPS行驶轨迹设置:</b></h5>--> <input type="file" id="fileAttach" name="file" class="form-control" style="display:inline;width:250px;"/>
<!-- <div class="input-group" style="width:380px;padding-bottom:10px;margin-left:10px;display:inline;">--> <input type="button" onclick="uploadFile()" value="上传" class="form-control" style="display:inline;width:80px;font-weight: bolder;"/>
<!-- <form id="form" enctype="multipart/form-data">--> </form>
<!-- <input type="file" id="fileAttach" name="file" class="form-control" style="display:inline;width:250px;"/>--> </div>
<!-- <input type="button" onclick="uploadFile()" value="上传" class="form-control" style="display:inline;width:80px;font-weight: bolder;"/>--> <span style="margin-left:10px;"><label>选择轨迹:</label><select id="selectGPSLine" class="form-control" style="width:250px;">
<!-- </form>--> {% for key,value in arg["gpsLines"].items() %}
<!-- </div>--> <option value="{{ key }}">{{ value }}</option>
<!-- <span style="margin-left:10px;"><label>选择轨迹:</label><select id="selectGPSLine" class="form-control" style="width:250px;">--> {% endfor %}
<!-- {% for key,value in arg["gpsLines"].items() %}--> </select></span>
<!-- <option value="{{ key }}">{{ value }}</option>--> <a style="margin-left:10px;font-weight:bold;" onclick="download_sample()">下载示例轨迹</a>
<!-- {% endfor %}--> </div>
<!-- </select></span>--> <div style="display: block; width: 100%; border-width: 1px; border-style: solid; border-color: darkgray; border-radius: 10px; padding: 2px; margin-top: 5px;">
<!-- <a style="margin-left:10px;font-weight:bold;" onclick="download_sample()">下载示例轨迹</a>--> <h5><b>行驶参数设置:</b></h5>
<!--&lt;!&ndash; <label><input style="margin-left:30px;" type="checkbox" id="ignition" />轨迹管理</label>&ndash;&gt;--> <span><label>速度(Km/h):</label><input type="text" id="carSpeed" class="form-control" style="display:inline;width:80px;" value="60"/></span>
<!--&lt;!&ndash; <div style="display: block;margin:10px; width: 95%; border-width: 1px; border-style: solid; border-color: darkgray; border-radius: 10px; padding: 2px; margin-top: 5px;">&ndash;&gt;--> <span><label>油耗(Km/L):</label><input type="text" id="oilExpend" class="form-control" style="display:inline;width:80px;" value="10"/></span>
<!--&lt;!&ndash; </div>&ndash;&gt;--> <span><label>是否循环行驶:</label><select style="width:80px;" id="travelLoop" class="form-control">
<!-- </div>--> <option value="0"></option>
<!-- <div style="display: block; width: 100%; border-width: 1px; border-style: solid; border-color: darkgray; border-radius: 10px; padding: 2px; margin-top: 5px;">--> <option value="1"></option></select><label style="font-size:9px;width: 100px;">开启后会在所选择的轨迹上来回行驶</label></span>
<!-- <h5><b>行驶参数设置:</b></h5>--> </div>
<!-- <span><label>速度(Km/h):</label><input type="text" id="carSpeed" class="form-control" style="display:inline;width:80px;" value="60"/></span>--> <div style="width:100%;padding-bottom:10px;border-bottom: 1px solid #eee;">
<!-- <span><label>油耗(Km/L):</label><input type="text" id="oilExpend" class="form-control" style="display:inline;width:80px;" value="10"/></span>--> <h3>操作:</h3>
<!-- <span><label>是否循环行驶:</label><select style="width:80px;" id="travelLoop" class="form-control">--> <button id="connect_B" type="button" class="btn btn-primary" onclick="connect()">1、连网</button>
<!-- <option value="0">否</option>--> <button id="fire_B" type="button" class="btn btn-primary" onclick="login()">2、登录</button>
<!-- <option value="1">是</option></select><label style="font-size:9px;width: 100px;">开启后会在所选择的轨迹上来回行驶</label></span>--> <button id="login_B" type="button" class="btn btn-primary" onclick="fire()">3、点火</button>
<!-- </div>--> <button id="run_B" type="button" class="btn btn-primary" onclick="startTravel()">4、行驶</button>
<!-- <div style="width:100%;padding-bottom:10px;border-bottom: 1px solid #eee;">--> <button id="stopRun_B" type="button" class="btn btn-primary" onclick="stopTravel()">5、停止行驶</button>
<!-- <h3>操作:</h3>--> <button id="unFire_B" type="button" class="btn btn-primary" onclick="unFire()">6、熄火</button>
<!-- <button id="connect_B" type="button" class="btn btn-primary" onclick="connect()">1、连网</button>--> <button id="unConnect_B" type="button" class="btn btn-primary" onclick="stopConnect()">7、断网</button>
<!-- <button id="fire_B" type="button" class="btn btn-primary" onclick="login()">2、登录</button>--> <button id="unConnectAll_B" type="button" class="btn btn-danger" onclick="reset()">复位</button>
<!-- <button id="login_B" type="button" class="btn btn-primary" onclick="fire()">3、点火</button>--> <button id="clear_B" type="button" class="btn btn-warning" onclick="clearlog()">清空日志</button>
<!-- <button id="run_B" type="button" class="btn btn-primary" onclick="startTravel()">4、行驶</button>--> <span style="margin-left:20px;"><label>当前状态:</label><input id="curStatus" value="断网" disabled="disabled" class="form-control" style="font-weight: bold;width:85px;color:red;border-width: 1px; border-style: solid; border-color: darkgray; border-radius: 10px;"></span>
<!-- <button id="stopRun_B" type="button" class="btn btn-primary" onclick="stopTravel()">5、停止行驶</button>--> <span style="width:80px;padding-left:10px;"><label style="width:70px"><input type="checkbox" id="ignition" onclick="isLogShow(this)"/>隐藏日志</label> </span>
<!-- <button id="unFire_B" type="button" class="btn btn-primary" onclick="unFire()">6、熄火</button>--> </div>
<!-- <button id="unConnect_B" type="button" class="btn btn-primary" onclick="stopConnect()">7、断网</button>-->
<!-- <button id="unConnectAll_B" type="button" class="btn btn-danger" onclick="reset()">复位</button>-->
<!-- <button id="clear_B" type="button" class="btn btn-warning" onclick="clearlog()">清空日志</button>-->
<!-- <span style="margin-left:20px;"><label>当前状态:</label><input id="curStatus" value="断网" disabled="disabled" class="form-control" style="font-weight: bold;width:85px;color:red;border-width: 1px; border-style: solid; border-color: darkgray; border-radius: 10px;"></span>-->
<!-- <span style="width:80px;padding-left:10px;"><label style="width:70px"><input type="checkbox" id="ignition" onclick="isLogShow(this)"/>隐藏日志</label> </span>-->
<!-- </div>-->
<!-- <div style="display: block; width: 100%; border-width: 1px; border-style: solid; border-color: darkgray; border-radius: 10px; padding: 2px; margin-top: 5px;">--> <!-- <div style="display: block; width: 100%; border-width: 1px; border-style: solid; border-color: darkgray; border-radius: 10px; padding: 2px; margin-top: 5px;">-->
<!-- <h5><b>事件发送:</b>--> <!-- <h5><b>事件发送:</b>-->
<!-- <span style="border-width:1px;border-style:solid;border-color:darkgray;border-radius:10px;padding:1px 10px;">--> <!-- <span style="border-width:1px;border-style:solid;border-color:darkgray;border-radius:10px;padding:1px 10px;">-->
...@@ -151,30 +145,21 @@ ...@@ -151,30 +145,21 @@
<!-- </div>--> <!-- </div>-->
<!-- </div>--> <!-- </div>-->
<!-- </div>--> <!-- </div>-->
<!-- <div style="display: block; width: 100%; border-width: 1px; border-style: solid; border-color: darkgray; border-radius: 10px; padding: 2px; margin-top: 5px;">--> <div style="display: block; width: 100%; border-width: 1px; border-style: solid; border-color: darkgray; border-radius: 10px; padding: 2px; margin-top: 5px;">
<!-- <h5><b>实时控制:</b>--> <h5><b>实时控制:</b>
<!-- <span style="border-width:1px;border-style:solid;border-color:darkgray;border-radius:10px;padding:1px 10px;">--> <span style="border-width:1px;border-style:solid;border-color:darkgray;border-radius:10px;padding:1px 10px;">
<!-- <label><input name="realtime" type="radio" value="0" checked="checked" onclick="isShowRealTimeCtrArea(this)"/>隐藏</label>--> <label><input name="realtime" type="radio" value="0" checked="checked" onclick="isShowRealTimeCtrArea(this)"/>隐藏</label>
<!-- <label style="margin-left:10px;"><input name="realtime" type="radio" value="1" onclick="isShowRealTimeCtrArea(this)"/>显示</label>--> <label style="margin-left:10px;"><input name="realtime" type="radio" value="1" onclick="isShowRealTimeCtrArea(this)"/>显示</label>
<!-- </span>--> </span>
<!-- </h5>--> </h5>
<!-- <div id="realTimeCtl_area" style="display:none;">--> <div id="realTimeCtl_area" style="display:none;">
<!-- <div style="padding:10px;">--> <div style="padding:10px;">
<!-- <span style="margin-left:10px"><label>车速度(Km/h):</label><input style="width:80px;margin-right:5px;" id="change_speed" type="text" class="form-control" value="60"><button type="button" class="btn btn-primary" onclick="changeSpeed()">改变车速</button></span>--> <span style="margin-left:10px"><label>车速度(Km/h):</label><input style="width:80px;margin-right:5px;" id="change_speed" type="text" class="form-control" value="60"><button type="button" class="btn btn-primary" onclick="changeSpeed()">改变车速</button></span>
<!-- <span style="margin-left:10px"><label>油耗(Km/L):</label><input style="width:80px;margin-right:5px;" id="change_oilExpend" type="text" class="form-control" value="10"><button type="button" class="btn btn-primary" onclick="changeOilExpend()">改变油耗</button></span>--> <span style="margin-left:10px"><label>油耗(Km/L):</label><input style="width:80px;margin-right:5px;" id="change_oilExpend" type="text" class="form-control" value="10"><button type="button" class="btn btn-primary" onclick="changeOilExpend()">改变油耗</button></span>
<!-- <span style="margin-left:10px"><label>上报间隔(秒):</label><input style="width:80px;margin-right:5px;" id="change_durTime" type="text" class="form-control" value="5"><button type="button" class="btn btn-primary" onclick="changeDurTime()">改变上报间隔</button></span>--> <span style="margin-left:10px"><label>上报间隔(秒):</label><input style="width:80px;margin-right:5px;" id="change_durTime" type="text" class="form-control" value="5"><button type="button" class="btn btn-primary" onclick="changeDurTime()">改变上报间隔</button></span>
<!-- <span style="margin-left:10px;"><button title="点击后,将会把上报的消息存到本地,不上报消息;用来模拟车机无信号的情况" type="button" class="btn btn-primary" onclick="storeMsg()" id="storeMsgBut">存储上报消息</button><label style="color:red;" id="storeMsgLab">未存储...</label></span>--> </div>
<!-- <span style="margin-top:10px;display:inline-block;border-width:1px;border-style:solid;border-color:darkgray;border-radius:10px;padding:1px 10px;margin-left:10px;">--> </div>
<!-- <label><input name="GPSValie" value="1" type="radio" onclick="changeGPSValid(this)" checked="checked">GPS有效</label>--> </div>
<!-- <label style="margin-left:10px;color:red;"><input name="GPSValie" value="0" type="radio" onclick="changeGPSValid(this)">GPS无效</label>-->
<!-- </span>-->
<!-- <span style="margin-top:10px;display:inline-block;border-width:1px;border-style:solid;border-color:darkgray;border-radius:10px;padding:1px 10px;margin-left:10px;">-->
<!-- <label><input name="lngLatIsOk" value="1" type="radio" onclick="changeLngLatIsOk(this)" checked="checked">经纬度正常</label>-->
<!-- <label style="margin-left:10px;color:red;"><input name="lngLatIsOk" value="0" type="radio" onclick="changeLngLatIsOk(this)">经纬度为0</label>-->
<!-- </span>-->
<!-- </div>-->
<!-- </div>-->
<!-- </div>-->
<div style="width:100%;padding-bottom:60px;border-bottom: 1px solid #eee;"> <div style="width:100%;padding-bottom:60px;border-bottom: 1px solid #eee;">
<h3>日志:</h3> <h3>日志:</h3>
<textarea id="showFeedback" style="width:100%;padding:5px;padding-bottom:60px;" rows="10"></textarea> <textarea id="showFeedback" style="width:100%;padding:5px;padding-bottom:60px;" rows="10"></textarea>
...@@ -195,11 +180,9 @@ ...@@ -195,11 +180,9 @@
function getPageData(){ function getPageData(){
var data = {}; var data = {};
var carId = $("#carId").val() var carId = $("#carId").val()
var WATER_CODE = $("#WATER_CODE").val()
var durTime = $("#durTime").val() var durTime = $("#durTime").val()
var timeout = $("#timeout").val() var timeout = $("#timeout").val()
data["carId"] = carId data["carId"] = carId
data["WATER_CODE"] = WATER_CODE
data["durTime"] = durTime data["durTime"] = durTime
data["timeout"] = timeout data["timeout"] = timeout
//会话session数据 //会话session数据
...@@ -208,50 +191,27 @@ function getPageData(){ ...@@ -208,50 +191,27 @@ function getPageData(){
data["session"]["sessionId"] = sessionId data["session"]["sessionId"] = sessionId
//登录数据 //登录数据
data["login"] = {} data["login"] = {}
var cpuId = $("#cpuId").val()
var imsi = $("#imsi").val()
var ccid = $("#ccid").val()
var imei = $("#imei").val()
data["login"]["cpuId"] = cpuId
data["login"]["imsi"] = imsi
data["login"]["ccid"] = ccid
data["login"]["imei"] = imei
//版本数据 //版本数据
data["version"] = {} data["version"] = getVersionData()
var verInfo = $("#verInfo").val()
var compileDate = $("#compileDate").val()
var GSM = $("#GSM").val()
data["version"]["verInfo"] = verInfo
data["version"]["compileDate"] = compileDate
data["version"]["GSM"] = GSM
//GPS轨迹数据 //GPS轨迹数据
var gpsLine = $("#selectGPSLine").val() var gpsLine = $("#selectGPSLine").val()
data["gpsLine"] = gpsLine data["gpsLine"] = gpsLine
//行驶参数数据 //行驶参数数据
data["travelData"] = {} data["travelData"] = getTravelData()
var carSpeed = $("#carSpeed").val()
var oilExpend = $("#oilExpend").val()
var travelLoop = $("#travelLoop").val()
data["travelData"]["carSpeed"] = carSpeed
data["travelData"]["oilExpend"] = oilExpend
data["travelData"]["travelLoop"] = travelLoop
return data; return data;
} }
//连接 //连接
function connect(){ function connect(){
var data = getPageData() var data = getPageData()
url = "/protocolTools/M_carSimulater_process/createConect";
var host = window.location.host; var host = window.location.host;
$.ajax({ $.ajax({
//url:"http://" + host + "/protocolTools/M_carSimulater_process/porcessSocketSetting", url:"http://" + host + "/m300Tools/M_m300Simulater_process/porcessConnect",
url:"http://" + host + url,
type:"post", type:"post",
data:JSON.stringify(data), data:JSON.stringify(data),
contentType:"application/json", contentType:"application/json",
dataType:"json", dataType:"json",
success:function(data){ success:function(data){
if(data.status == 200){ if(data.status == 200){
//window.location.reload()
var curTime = getCurTime(); var curTime = getCurTime();
var txt = $("#showFeedback").val() var txt = $("#showFeedback").val()
txt = txt + "[" + curTime + "] " + data.message + "\n" txt = txt + "[" + curTime + "] " + data.message + "\n"
...@@ -274,45 +234,43 @@ function connect(){ ...@@ -274,45 +234,43 @@ function connect(){
function login(){ function login(){
var data = getPageData() var data = getPageData()
$("#curStatus").val("登录") $("#curStatus").val("登录")
url = "/protocolTools/M_carSimulater_process/login"; url = "/m300Tools/M_m300Simulater_process/porcessLogin",
sendjson(data,url); sendjson(data,url);
} }
//点火 //点火
function fire(){ function fire(){
var data = getPageData() var data = getPageData()
url = "/protocolTools/M_carSimulater_process/fire"; url = "/m300Tools/M_m300Simulater_process/porcessFireOn",
sendjson(data,url); sendjson(data,url);
$("#curStatus").val("点火") $("#curStatus").val("点火")
} }
//行驶 //行驶
function startTravel(){ function startTravel(){
var data = getPageData() var data = getPageData()
url = "/protocolTools/M_carSimulater_process/startTravel"; url = "/m300Tools/M_m300Simulater_process/porcessStartTravel",
sendjson(data,url); sendjson(data,url);
$("#curStatus").val("行驶") $("#curStatus").val("行驶")
} }
//停止行驶 //停止行驶
function stopTravel(){ function stopTravel(){
var data = getPageData(); var data = getPageData();
url = "/protocolTools/M_carSimulater_process/stopTravel"; url = "/m300Tools/M_m300Simulater_process/porcessStopTravel",
sendjson(data,url); sendjson(data,url);
$("#curStatus").val("点火") $("#curStatus").val("点火")
} }
//熄火 //熄火
function unFire(){ function unFire(){
var data = getPageData() var data = getPageData()
url = "/protocolTools/M_carSimulater_process/unFire"; url = "/m300Tools/M_m300Simulater_process/porcessFireOff",
sendjson(data,url); sendjson(data,url);
$("#curStatus").val("熄火") $("#curStatus").val("熄火")
} }
//断开连接 //断开连接
function stopConnect(){ function stopConnect(){
var data = getPageData(); var data = getPageData();
url = "/protocolTools/M_carSimulater_process/closeConect";
var host = window.location.host; var host = window.location.host;
$.ajax({ $.ajax({
//url:"http://" + host + "/protocolTools/M_carSimulater_process/porcessSocketSetting", url:"http://" + host + "/m300Tools/M_m300Simulater_process/porcessDisconnect",
url:"http://" + host + url,
type:"post", type:"post",
data:JSON.stringify(data), data:JSON.stringify(data),
contentType:"application/json", contentType:"application/json",
...@@ -344,7 +302,7 @@ function reset(){ ...@@ -344,7 +302,7 @@ function reset(){
res=confirm("复位后会影响其他在线用户的使用,你确定复位吗?"); res=confirm("复位后会影响其他在线用户的使用,你确定复位吗?");
if(res == true){ if(res == true){
var data = getPageData(); var data = getPageData();
url = "/protocolTools/M_carSimulater_process/reset"; url = "/m300Tools/M_m300Simulater_process/reset",
sendjson(data,url); sendjson(data,url);
$("#showFeedback").val("") $("#showFeedback").val("")
//endService() //endService()
...@@ -357,11 +315,40 @@ function reset(){ ...@@ -357,11 +315,40 @@ function reset(){
function clearlog(){ function clearlog(){
$("#showFeedback").val("") $("#showFeedback").val("")
} }
//获取版本数据
function getVersionData(){
var SWVersion = $("#SWVersion").val();
var SWDate = $("#SWDate").val();
var HWVersion = $("#HWVersion").val();
var GSMType = $("#GSMType").val();
var carType = $("#carType").val();
var engineCode = $("#engineCode").val();
var VINCode = $("#VINCode").val();
var data = {};
data["SWVersion"] = SWVersion;
data["SWDate"] = SWDate;
data["HWVersion"] = HWVersion;
data["GSMType"] = GSMType;
data["carType"] = carType;
data["engineCode"] = engineCode;
data["VINCode"] = VINCode;
return data
}
//获取行驶参数数据
function getTravelData(){
var data = {}
var carSpeed = $("#carSpeed").val()
var oilExpend = $("#oilExpend").val()
var travelLoop = $("#travelLoop").val()
data["carSpeed"] = carSpeed
data["oilExpend"] = oilExpend
data["travelLoop"] = travelLoop
return data
}
//非json方式发送数据 //非json方式发送数据
function send(data,url){ function send(data,url){
var host = window.location.host; var host = window.location.host;
$.ajax({ $.ajax({
//url:"http://" + host + "/protocolTools/M_carSimulater_process/porcessSocketSetting",
url:"http://" + host + url, url:"http://" + host + url,
type:"post", type:"post",
data:data, data:data,
...@@ -387,7 +374,6 @@ function send(data,url){ ...@@ -387,7 +374,6 @@ function send(data,url){
function sendjson(data,url){ function sendjson(data,url){
var host = window.location.host; var host = window.location.host;
$.ajax({ $.ajax({
//url:"http://" + host + "/protocolTools/M_carSimulater_process/porcessSocketSetting",
url:"http://" + host + url, url:"http://" + host + url,
type:"post", type:"post",
data:JSON.stringify(data), data:JSON.stringify(data),
...@@ -498,7 +484,7 @@ function uploadFile(){ ...@@ -498,7 +484,7 @@ function uploadFile(){
var form = new FormData(document.getElementById("form")); var form = new FormData(document.getElementById("form"));
var host = window.location.host; var host = window.location.host;
$.ajax({ $.ajax({
url:"http://" + host + "/protocolTools/M_carSimulater_process/fileUplad", url:"http://" + host + "/m300Tools/M_m300Simulater_process/fileUplad",
type:"post", type:"post",
data:form, data:form,
cache: false, cache: false,
...@@ -523,7 +509,7 @@ function uploadFile(){ ...@@ -523,7 +509,7 @@ function uploadFile(){
function download_sample(){ function download_sample(){
var host = window.location.host; var host = window.location.host;
window.location.href = "http://" + host + "/protocolTools/M_carSimulater_process/sampleDowload" window.location.href = "http://" + host + "/m300Tools/M_m300Simulater_process/sampleDowload";
} }
//查询车机今日行驶数据 //查询车机今日行驶数据
...@@ -534,7 +520,7 @@ $("#searchCarData").click(function(){ ...@@ -534,7 +520,7 @@ $("#searchCarData").click(function(){
var host = window.location.host; var host = window.location.host;
$.ajax({ $.ajax({
url:"http://" + host + "/protocolTools/M_carSimulater_process/searchCarsimulaterData", url:"http://" + host + "/m300Tools/M_m300Simulater_process/searchCarsimulaterData",
type:"post", type:"post",
data:data, data:data,
dataType:"json", dataType:"json",
...@@ -590,7 +576,7 @@ function getAllUsers(){ ...@@ -590,7 +576,7 @@ function getAllUsers(){
var data = {}; var data = {};
var host = window.location.host; var host = window.location.host;
$.ajax({ $.ajax({
url:"http://" + host + "/protocolTools/M_carSimulater_process/getConnects", url:"http://" + host + "/m300Tools/M_m300Simulater_process/getConnects",
type:"post", type:"post",
data:data, data:data,
dataType:"json", dataType:"json",
...@@ -792,7 +778,7 @@ function changeSpeed(){ ...@@ -792,7 +778,7 @@ function changeSpeed(){
data["session"] = {} data["session"] = {}
var sessionId = $("#curSession").val() var sessionId = $("#curSession").val()
data["session"]["sessionId"] = sessionId data["session"]["sessionId"] = sessionId
url = "/protocolTools/M_carSimulater_process/changeCarSpeed"; url = "/m300Tools/M_m300Simulater_process/changeCarSpeed",
$("#carSpeed").val(speed) $("#carSpeed").val(speed)
sendjson(data,url); sendjson(data,url);
} }
...@@ -807,7 +793,7 @@ function changeOilExpend(){ ...@@ -807,7 +793,7 @@ function changeOilExpend(){
data["session"] = {} data["session"] = {}
var sessionId = $("#curSession").val() var sessionId = $("#curSession").val()
data["session"]["sessionId"] = sessionId data["session"]["sessionId"] = sessionId
url = "/protocolTools/M_carSimulater_process/changeOilExpend"; url = "/m300Tools/M_m300Simulater_process/changeOilExpend",
$("#oilExpend").val(oilExpend) $("#oilExpend").val(oilExpend)
sendjson(data,url); sendjson(data,url);
} }
...@@ -823,112 +809,7 @@ function changeDurTime(){ ...@@ -823,112 +809,7 @@ function changeDurTime(){
var sessionId = $("#curSession").val() var sessionId = $("#curSession").val()
data["session"]["sessionId"] = sessionId data["session"]["sessionId"] = sessionId
$("#durTime").val(durTime) $("#durTime").val(durTime)
url = "/protocolTools/M_carSimulater_process/changeDurTime"; url = "/m300Tools/M_m300Simulater_process/changeDurTime",
sendjson(data,url);
}
//控制发送数据是否保存到本地
function storeMsg(){
var butTxt = $("#storeMsgBut").text()
if(butTxt == "存储上报消息"){
var data = {}
var carId = $("#carId").val()
data["carId"] = carId
data["sendType"] = 1
//会话session数据
data["session"] = {}
var sessionId = $("#curSession").val()
data["session"]["sessionId"] = sessionId
url = "/protocolTools/M_carSimulater_process/controlStoreMsg";
var host = window.location.host;
$.ajax({
//url:"http://" + host + "/protocolTools/M_carSimulater_process/porcessSocketSetting",
url:"http://" + host + url,
type:"post",
data:JSON.stringify(data),
contentType:"application/json",
dataType:"json",
success:function(data){
if(data.status == 200){
$("#storeMsgBut").text("取消存储上报消息")
$("#storeMsgLab").text("存储中...")
var curTime = getCurTime();
var txt = $("#showFeedback").val()
txt = txt + "[" + curTime + "] " + data.message + "\n"
$("#showFeedback").val(txt)
}else{
var curTime = getCurTime();
var txt = $("#showFeedback").val()
txt = txt + "[" + curTime + "] " + data.message + "\n"
$("#showFeedback").val(txt)
alert(data.message);
}
}
});
}else{
var data = {}
var carId = $("#carId").val()
data["carId"] = carId
data["sendType"] = 0
//会话session数据
data["session"] = {}
var sessionId = $("#curSession").val()
data["session"]["sessionId"] = sessionId
url = "/protocolTools/M_carSimulater_process/controlStoreMsg";
var host = window.location.host;
$.ajax({
//url:"http://" + host + "/protocolTools/M_carSimulater_process/porcessSocketSetting",
url:"http://" + host + url,
type:"post",
data:JSON.stringify(data),
contentType:"application/json",
dataType:"json",
success:function(data){
if(data.status == 200){
$("#storeMsgBut").text("存储上报消息")
$("#storeMsgLab").text("未存储...")
//window.location.reload()
var curTime = getCurTime();
var txt = $("#showFeedback").val()
txt = txt + "[" + curTime + "] " + data.message + "\n"
$("#showFeedback").val(txt)
}else{
var curTime = getCurTime();
var txt = $("#showFeedback").val()
txt = txt + "[" + curTime + "] " + data.message + "\n"
$("#showFeedback").val(txt)
alert(data.message);
}
}
});
}
}
//控制GPS是否有效
function changeGPSValid(e){
var data = {}
var carId = $("#carId").val()
var GPSValid = $(e).val()
data["carId"] = carId
data["GPSValid"] = GPSValid
//会话session数据
data["session"] = {}
var sessionId = $("#curSession").val()
data["session"]["sessionId"] = sessionId
url = "/protocolTools/M_carSimulater_process/controlGPSValid";
sendjson(data,url);
}
//控制经纬度为0还是正常
function changeLngLatIsOk(e){
var data = {}
var carId = $("#carId").val()
var lngLatIsOk = $(e).val()
data["carId"] = carId
data["lngLatIsOk"] = lngLatIsOk
//会话session数据
data["session"] = {}
var sessionId = $("#curSession").val()
data["session"]["sessionId"] = sessionId
url = "/protocolTools/M_carSimulater_process/controlLngLatIsOk";
sendjson(data,url); sendjson(data,url);
} }
</script> </script>
......
#coding:utf-8 #coding:utf-8
import os
import time
from flask import Blueprint ,Response,request from flask import Blueprint ,Response,request,send_from_directory
from configparser import ConfigParser from configparser import ConfigParser
import json import json
import traceback import traceback
from lib.socket.ClientSocket import ClientSocket
from lib.socket.service.M300SimulaterService import M300SimulaterService
from lib.util import fileUtil
M_m300Simulater_process = Blueprint('M_m300Simulater_process', __name__) M_m300Simulater_process = Blueprint('M_m300Simulater_process', __name__)
connects = {} #用来保存连接的信息s connects = {} #用来保存连接的信息s
...@@ -42,3 +48,407 @@ def porcessSocketSetting(): ...@@ -42,3 +48,407 @@ def porcessSocketSetting():
data["status"] = "4003" data["status"] = "4003"
data["message"] = "Error: 处理失败!" data["message"] = "Error: 处理失败!"
return Response(json.dumps(data), mimetype='application/json') return Response(json.dumps(data), mimetype='application/json')
##########################################
# 【接口类型】联网
##########################################
@M_m300Simulater_process.route("/porcessConnect",methods=['POST'])
def porcessConnect():
params = request.get_data()
params = json.loads(params.decode("utf-8"))
sessionId = params["session"]["sessionId"]
data = {}
try:
conf_R = ConfigParser()
conf_R.read("config/m300Tools/m300Simulater.conf")
if not sessionId in connects.keys():
cliSocket = ClientSocket(conf_R.get("socket", "host"), conf_R.getint("socket", "port"))
cliSocket.connect()
connect = {}
connects[sessionId] = connect
socketName = "socket_" + str(len(connects) + 1)
connect["name"] = socketName
service = M300SimulaterService()
global websocket
if websocket == None:
service.startWebsocketService() # 如果没有创建websocket服务,则启动新的websocket服务
websocket = service.getWebsocket()
else:
service.setWebsocket(websocket) # 给新服务设置websocket服务对象
service.addNewWebsocket() # 创建一个新的websocket连接
service.setSocket(cliSocket)
service.setTimeout(int(params["timeout"]))
service.setCarId(params["carId"])
service.setSendDur(int(params["durTime"]))
service.setData(params) #传入页面传过来的数据
service.startWebsocketService() #启动websocket服务
service.startReciveService() #接收消息的服务
service.setGpsLine(params["gpsLine"])
connect["service"] = connect
connects[sessionId]["service"] = service
timeArray = time.localtime(int(time.time()))
curTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
connects[sessionId]["time"] = curTime
ip = request.remote_addr
connects[sessionId]["ip"] = ip
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')
##########################################
# 【接口类型】车机登录
##########################################
@M_m300Simulater_process.route("/porcessLogin",methods=['POST'])
def porcessLogin():
params = request.get_data()
params = json.loads(params.decode("utf-8"))
sessionId = params["session"]["sessionId"]
data = {}
try:
connects[sessionId]["service"].carLogin()
data["status"] = "200"
data["message"] = "登录成功!"
except BaseException as e:
# 打印异常信息
traceback.print_exc()
data["status"] = "4003"
data["message"] = "Error: 登录失败!"
return Response(json.dumps(data), mimetype='application/json')
##########################################
# 【接口类型】车机点火
##########################################
@M_m300Simulater_process.route("/porcessFireOn",methods=['POST'])
def porcessFireOn():
params = request.get_data()
params = json.loads(params.decode("utf-8"))
sessionId = params["session"]["sessionId"]
data = {}
try:
connects[sessionId]["service"].fireOn()
data["status"] = "200"
data["message"] = "点火成功!"
except BaseException as e:
# 打印异常信息
traceback.print_exc()
data["status"] = "4003"
data["message"] = "Error: 点火失败!"
return Response(json.dumps(data), mimetype='application/json')
##########################################
# 【接口类型】车机开始行驶
##########################################
@M_m300Simulater_process.route("/porcessStartTravel",methods=['POST'])
def porcessStartTravel():
params = request.get_data()
params = json.loads(params.decode("utf-8"))
sessionId = params["session"]["sessionId"]
data = {}
try:
service = connects[sessionId]["service"]
service.startService()
service.startTravel()
data["status"] = "200"
data["message"] = "开始行驶成功!"
except BaseException as e:
# 打印异常信息
traceback.print_exc()
data["status"] = "4003"
data["message"] = "Error: 开始行驶失败!"
return Response(json.dumps(data), mimetype='application/json')
##########################################
# 【接口类型】车机停止行驶
##########################################
@M_m300Simulater_process.route("/porcessStopTravel",methods=['POST'])
def porcessStopTravel():
params = request.get_data()
params = json.loads(params.decode("utf-8"))
sessionId = params["session"]["sessionId"]
data = {}
try:
connects[sessionId]["service"].stopTravel()
data["status"] = "200"
data["message"] = "停止行驶成功!"
except BaseException as e:
# 打印异常信息
traceback.print_exc()
data["status"] = "4003"
data["message"] = "Error: 停止行驶失败!"
return Response(json.dumps(data), mimetype='application/json')
##########################################
# 【接口类型】车机熄火
##########################################
@M_m300Simulater_process.route("/porcessFireOff",methods=['POST'])
def porcessFireOff():
params = request.get_data()
params = json.loads(params.decode("utf-8"))
sessionId = params["session"]["sessionId"]
data = {}
try:
service = connects[sessionId]["service"]
service.fireOff()
service.stopTravel()
service.stopService()
data["status"] = "200"
data["message"] = "熄火成功!"
except BaseException as e:
# 打印异常信息
traceback.print_exc()
data["status"] = "4003"
data["message"] = "Error: 熄火失败!"
return Response(json.dumps(data), mimetype='application/json')
##########################################
# 【接口类型】车机断网
##########################################
@M_m300Simulater_process.route("/porcessDisconnect",methods=['POST'])
def porcessDisconnect():
params = request.get_data()
params = json.loads(params.decode("utf-8"))
sessionId = params["session"]["sessionId"]
data = {}
try:
service = connects[sessionId]["service"]
service.stopTravel()
service.stopService()
service.socket.close()
connects.pop(sessionId)
data["status"] = "200"
data["message"] = "断开连接成功!"
except BaseException as e:
# 打印异常信息
traceback.print_exc()
data["status"] = "4003"
data["message"] = "Error: 断开连接失败!"
return Response(json.dumps(data), mimetype='application/json')
##########################################
# 【接口类型】车机复位
##########################################
@M_m300Simulater_process.route("/reset",methods=['POST'])
def reset():
params = request.get_data()
params = json.loads(params.decode("utf-8"))
sessionId = params["session"]["sessionId"]
data = {}
global connects
global websocket
try:
for key in connects:
service = connects[key]["service"]
service.stopTravel()
try:
pass
# service.fireOff()
except BaseException as e1:
pass
service.stopTravel()
service.stopService()
service.socket.close()
websocket.close()
websocket = None
connects = {}
data["status"] = "200"
data["message"] = "复位成功!"
except BaseException as e:
# 打印异常信息
traceback.print_exc()
data["status"] = "4003"
data["message"] = "Error: 复位失败!"
return Response(json.dumps(data), mimetype='application/json')
##########################################
# 【接口类型】文件上传操作
##########################################
@M_m300Simulater_process.route("/fileUplad",methods=['POST'])
def fileUplad():
# 获取前端传输的文件(对象)
f = request.files.get('file')
file_content = f.read()
try:
file_content = file_content.decode("utf-8").replace("\n","")
except BaseException as e:
pass
try:
file_content = file_content.decode("gbk").replace("\n","")
except BaseException as e:
pass
maxPrefix = int(fileUtil.getMaxPrefixFilePre("data/m300Tools/GPSLines"))
filenameOrg = f.filename
filename = str(maxPrefix + 1) + "_" + filenameOrg
fileData = {}
fileData["filename"] = fileUtil.removeSuffix(filenameOrg)
fileData["filenameOri"] = filename
# 验证文件格式(简单设定几个格式)
types = ['json','txt']
data = {}
if filename.split('.')[-1] in types:
# 保存图片
with open("data/m300Tools/GPSLines/" + filename,"w",encoding="utf-8") as fi:
fi.write(file_content)
# 返回给前端结果
data["status"] = "200"
data["message"] = "文件上传成功"
data["file"] = fileData
else:
data["status"] = "4003"
data["message"] = "文件上传失败"
return Response(json.dumps(data), mimetype='application/json')
@M_m300Simulater_process.route("/sampleDowload")
def sampleDowload():
return send_from_directory(r"data/m300Tools/GPSLines",filename="1_sample.json",as_attachment=True)
##########################################
# 【接口类型】查询车机行驶数据
##########################################
@M_m300Simulater_process.route("/searchCarsimulaterData",methods=['POST'])
def searchCarsimulaterData():
carId = request.form.get("carId")
data = {}
carFile = "data/m300Tools/carData/" + carId + ".json"
if not os.path.exists(carFile):
data["status"] = "200"
data["message"] = "该车机无行驶数据!"
return Response(json.dumps(data), mimetype='application/json')
else:
try:
with open(carFile, "r", encoding="utf-8") as fi:
content = fi.read()
conJson = json.loads(content)
data["status"] = "200"
data["message"] = "日期:" + conJson["time"]["date"] + "\n今日行驶总里程:" + str(conJson["curDayTravel"]["todayTotalMilleage"]) + "(米)" \
+ "\n今日行驶总油耗:" + str(conJson["curDayTravel"]["todayTotalOil"]) + "(ml)" + "\n今日行驶总时间:" + str(conJson["curDayTravel"]["todayTotalTime"]) + "(秒)" \
+ "\n------------------\n本次行驶里程:" + str(conJson["curDayTravel"]["theMilleage"]) + "(米)" \
+ "\n本次行驶油耗:" + str(conJson["curDayTravel"]["theOil"]) + "(ml)" + "\n本次行驶总时间:" + str(conJson["curDayTravel"]["theTime"]) + "(秒)"
except BaseException as e:
# 打印异常信息
traceback.print_exc()
data["status"] = "4003"
data["message"] = "Error: 查询车机数据失败失败!"
return Response(json.dumps(data), mimetype='application/json')
##########################################
# 【接口类型】查询当前连接数,和连接对象
##########################################
@M_m300Simulater_process.route("/getConnects",methods=['POST'])
def getConnects():
data = {}
try:
data["status"] = "200"
data["userCounts"] = len(connects)
data["result"] = str(connects)
return Response(json.dumps(data), mimetype='application/json')
except BaseException as e:
# 打印异常信息
traceback.print_exc()
data["status"] = "4003"
data["message"] = "Error: 获取在线人数失败失败!"
return Response(json.dumps(data), mimetype='application/json')
#--------------------------------------- 实时控制逻辑 ---------------------------------------
##########################################
# 【接口类型】改变车速
##########################################
@M_m300Simulater_process.route("/changeCarSpeed",methods=['POST'])
def changeCarSpeed():
params = request.get_data()
params = json.loads(params.decode("utf-8"))
sessionId = params["session"]["sessionId"]
data = {}
if not sessionId in connects.keys():
data["status"] = "4003"
data["message"] = "Error: 未启动服务,不可改变车速!"
return Response(json.dumps(data), mimetype='application/json')
service = connects[sessionId]["service"]
travelStatus = service.getTravelStatus() #获取汽车行驶状态
if travelStatus == 0 or travelStatus == 2:
data["status"] = "4003"
data["message"] = "Error: 汽车还未行驶,不可改变车速!"
elif travelStatus == 1:
try:
service.setCarSpeed(params["speed"])
data["status"] = "200"
data["message"] = "改变车速成功!"
except BaseException as e:
# 打印异常信息
traceback.print_exc()
data["status"] = "4003"
data["message"] = "Error: 改变车速失败!"
return Response(json.dumps(data), mimetype='application/json')
##########################################
# 【接口类型】改变油耗
##########################################
@M_m300Simulater_process.route("/changeOilExpend",methods=['POST'])
def changeOilExpend():
params = request.get_data()
params = json.loads(params.decode("utf-8"))
sessionId = params["session"]["sessionId"]
data = {}
if not sessionId in connects.keys():
data["status"] = "4003"
data["message"] = "Error: 未启动服务,不可改变油耗!"
return Response(json.dumps(data), mimetype='application/json')
service = connects[sessionId]["service"]
travelStatus = service.getTravelStatus() #获取汽车行驶状态
if travelStatus == 0 or travelStatus == 2:
data["status"] = "4003"
data["message"] = "Error: 汽车还未行驶,不可改变油耗!"
elif travelStatus == 1:
try:
service.setOilExpend(params["oilExpend"])
data["status"] = "200"
data["message"] = "改变油耗成功!"
except BaseException as e:
# 打印异常信息
traceback.print_exc()
data["status"] = "4003"
data["message"] = "Error: 改变油耗失败!"
return Response(json.dumps(data), mimetype='application/json')
##########################################
# 【接口类型】改变发送间隔
##########################################
@M_m300Simulater_process.route("/changeDurTime",methods=['POST'])
def changeDurTime():
params = request.get_data()
params = json.loads(params.decode("utf-8"))
sessionId = params["session"]["sessionId"]
data = {}
if not sessionId in connects.keys():
data["status"] = "4003"
data["message"] = "Error: 未启动服务,不可改变发送间隔!"
return Response(json.dumps(data), mimetype='application/json')
service = connects[sessionId]["service"]
travelStatus = service.getTravelStatus() #获取汽车行驶状态
if travelStatus == 0 or travelStatus == 2:
data["status"] = "4003"
data["message"] = "Error: 汽车还未行驶,不可改变发送间隔!"
elif travelStatus == 1:
try:
service.setSendDur(int(params["durTime"]))
data["status"] = "200"
data["message"] = "改变发送间隔成功!"
except BaseException as e:
# 打印异常信息
traceback.print_exc()
data["status"] = "4003"
data["message"] = "Error: 改变发送间隔失败!"
return Response(json.dumps(data), mimetype='application/json')
\ No newline at end of file
...@@ -278,11 +278,11 @@ def fileUplad(): ...@@ -278,11 +278,11 @@ def fileUplad():
f = request.files.get('file') f = request.files.get('file')
file_content = f.read() file_content = f.read()
try: try:
file_content = file_content.decode("utf-8") file_content = file_content.decode("utf-8").replace("\n","")
except BaseException as e: except BaseException as e:
pass pass
try: try:
file_content = file_content.decode("gbk") file_content = file_content.decode("gbk").replace("\n","")
except BaseException as e: except BaseException as e:
pass pass
maxPrefix = int(fileUtil.getMaxPrefixFilePre("data/messageTools/GPSLines")) maxPrefix = int(fileUtil.getMaxPrefixFilePre("data/messageTools/GPSLines"))
......
...@@ -307,11 +307,11 @@ def fileUplad(): ...@@ -307,11 +307,11 @@ def fileUplad():
f = request.files.get('file') f = request.files.get('file')
file_content = f.read() file_content = f.read()
try: try:
file_content = file_content.decode("utf-8") file_content = file_content.decode("utf-8").replace("\n","")
except BaseException as e: except BaseException as e:
pass pass
try: try:
file_content = file_content.decode("gbk") file_content = file_content.decode("gbk").replace("\n","")
except BaseException as e: except BaseException as e:
pass pass
maxPrefix = int(fileUtil.getMaxPrefixFilePre("data/protocolTools/GPSLines")) maxPrefix = int(fileUtil.getMaxPrefixFilePre("data/protocolTools/GPSLines"))
......
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