Commit dfa94919 authored by liyuanhong's avatar liyuanhong

完成了新硬件模拟器连网和登录功能

parent 44bb56da
......@@ -40,7 +40,7 @@ class MessageSimulaterDataService():
data["curDayTravel"]["theOil"] = 0 #本次行驶总油耗
data["curDayTravel"]["theTime"] = 0 #本次行驶总时间
data["travelData"] = {} #定义所有行驶数据
data["travelData"]["totallMilleage"] = 0 #行驶总里程
data["travelData"]["totalMilleage"] = 0 #行驶总里程
data["travelData"]["totalOil"] = 0 #行驶总油耗
data["travelData"]["totalTime"] = 0 #行驶总时间
return data
......@@ -71,6 +71,19 @@ class MessageSimulaterDataService():
self.data["curDayTravel"]["theTime"] = 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):
self.data["time"]["dateTime"] = data
......
......@@ -11,6 +11,9 @@ import time
import traceback
from time import sleep
from lib.protocol.message.Location_msg import Location_msg
from lib.protocol.message.TerminalRegister_msg import TerminalRegister_msg
from lib.protocol.message.TerminalVersionInfo_msg import TerminalVersionInfo_msg
from lib.socket.service.websocket_service import Websocket_service
......@@ -49,6 +52,7 @@ class MessageSimulaterService():
def getWebsocket(self):
return self.websocket
def sendMsg(self,msg):
self.socket.setTimeOut(self.timeout)
self.socket.send(msg)
......@@ -61,6 +65,65 @@ class MessageSimulaterService():
type = self.getMsgFunId(msg)
self.websocket.send(">>>>" + type + ":" + msg)
########################################################
#车机登录
########################################################
def carLogin(self):
loginObj = TerminalRegister_msg()
msg = loginObj.generateMsg_GUI(msgID="0100",phoneNum=int(self.data["phoneNum"]),msgWaterCode=self.sn,encryptionType=0,subPkg=0,provinceId=int(self.data["login"]["provinceId"]),\
countyId=int(self.data["login"]["countyId"]),manufacturerId=self.data["login"]["manufacturerId"],terminalType=self.data["login"]["terminalType"], \
terminalId=self.data["login"]["terminalId"],licencePlateColor=int(self.data["login"]["licencePlateColor"]),carSign=self.data["login"]["carSign"])
self.sendMsg(msg)
type = self.getMsgFunId(msg)
info = type + ">>>>:" + msg
self.websocket.send(info)
self.sn = self.sn + 1
verObj = TerminalVersionInfo_msg()
time.sleep(0.5)
msg = verObj.generateMsg_GUI(msgID="0205",phoneNum=int(self.data["phoneNum"]),msgWaterCode=self.sn,encryptionType=0,subPkg=0, \
softwareVersion=self.data["version"]["softwareVersion"], softwareVersionDate=self.data["version"]["softwareVersionDate"], CPUId=self.data["version"]["softwareVersionDate"], \
GMSType=self.data["version"]["GMSType"], GMS_IMEI=self.data["version"]["GMS_IMEI"], SIM_IMSI=self.data["version"]["SIM_IMSI"], \
SIM_ICCID=self.data["version"]["SIM_ICCID"],carType=int(self.data["version"]["carType"]), VIN=self.data["version"]["VIN"], \
totalMileage=int(self.data["version"]["totalMileage"]), totalOilExpend=int(self.data["version"]["totalOilExpend"]), \
displacement=int(self.data["version"]["displacement"]),oilDensity=int(self.data["version"]["oilDensity"]))
self.sendMsg(msg)
type = self.getMsgFunId(msg)
info = type + ">>>>:" + msg
self.websocket.send(info)
self.sn = self.sn + 1
########################################################
#车机点火
########################################################
def fireOn(self):
fireOnParams = {"msgID": "0200", "phoneNum": "13146201119", "msgWaterCode": "1", "encryptionType": "0", "subPkg": "0",
"pkgCounts": "0", "baseInfo": {"alarmFlag": 0, "status": 262402, "latitude": 29.40268, "longtitude": 106.54041,
"elevation": "521", "speed": "66", "directionAngle": "59",
"infoTime": "2020-04-21 18:03:49"}, "extraInfo": {"FA": {"ignition": "on"}}}
msgObj = Location_msg()
msg = msgObj.generateMsg_GUI(fireOnParams)
self.sendMsg(msg)
type = self.getMsgFunId(msg)
info = type + ">>>>:" + msg
self.websocket.send(info)
self.sn = self.sn + 1
########################################################
#车机熄火
########################################################
def fireOff(self):
fireOffParams = {"msgID": "0200", "phoneNum": "13146201119", "msgWaterCode": "1", "encryptionType": "0", "subPkg": "0",
"pkgCounts": "0", "baseInfo": {"alarmFlag": 0, "status": 262402, "latitude": 29.40268, "longtitude": 106.54041,
"elevation": "521", "speed": "66", "directionAngle": "59",
"infoTime": "2020-04-21 18:09:34"}, "extraInfo": {"FA": {"flameout": "on"}}}
msgObj = Location_msg()
msg = msgObj.generateMsg_GUI(fireOffParams)
self.sendMsg(msg)
type = self.getMsgFunId(msg)
info = type + ">>>>:" + msg
self.websocket.send(info)
self.sn = self.sn + 1
########################################################
#启动与页面交互的websockt服务
########################################################
......@@ -69,3 +132,77 @@ class MessageSimulaterService():
self.websocket.setHost("0.0.0.0")
self.websocket.setPort(5007)
self.websocket.startWebsocketServer()
########################################################
# 接收消息的服务
########################################################
def serviceRev(self):
self.serviceStatus = 2 #2代表只启动了接收消息的进程,1代表了接收和发送都启动了
while self.serviceStatus != 0:
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.send(info)
self.doResponse(d)
########################################################
#启动与页面交互的websocket服务
########################################################
def startWebsocketService(self):
if self.websocket == None:
t = threading.Thread(target=self.websocketService, args=())
t.start()
########################################################
#停止websocket服务
########################################################
def stopWebsocketService(self):
try:
self.websocket.close()
self.websocket = None
except BaseException as e:
# 打印异常信息
traceback.print_exc()
########################################################
#获取收到消息的功能id
########################################################
def getMsgFunId(self,msg):
funId = msg[2:6]
return funId
########################################################
#收到 某些类型的消息后执行回复操作
########################################################
def doResponse(self,msg):
# TODO 收到 某些类型的消息后执行回复操作
pass
# msgFunId = self.getMsgFunId(msg)
# if msgFunId == "8205":
# msg = Common_response(resId="8205").generateCommonMsg()
# self.sendMsg(msg)
# self.sn = self.sn + 1
# type = self.getMsgFunId(msg)
# self.websocket.send(type + ">>>>设置GPSR通信参数应答:" + msg)
# elif msgFunId == "8206":
# msg = Common_response(resId="8206").generateCommonMsg()
# self.sendMsg(msg)
# self.sn = self.sn + 1
# type = self.getMsgFunId(msg)
# self.websocket.send(type + ">>>>设置车辆OBD适配信息应答:" + msg)
# elif msgFunId == "8300":
# msg = Update_response().generateUpdateMsg()
# self.sendMsg(msg)
# self.sn = self.sn + 1
# type = self.getMsgFunId(msg)
# self.websocket.send(type + ">>>>升级_平台通知终端远程升级应答:" + msg)
########################################################
#启动接收消息的服务
########################################################
def startReciveService(self):
t2 = threading.Thread(target=self.serviceRev, args=())
t2.start()
......@@ -106,16 +106,26 @@
<div style="width:100%;padding-bottom:10px;border-bottom: 1px solid #eee;">
<h3>操作:</h3>
<button id="connect_B" type="button" class="btn btn-primary" onclick="connect()">1、连网</button>
<button id="fire_B" type="button" class="btn btn-primary" onclick="login()">2、登录</button>
<button id="login_B" type="button" class="btn btn-primary" onclick="fire()">3、点火</button>
<button id="fire_B" type="button" class="btn btn-primary" onclick="carLogin()">2、登录</button>
<button id="login_B" type="button" class="btn btn-primary" onclick="fireOn()">3、点火</button>
<button id="run_B" type="button" class="btn btn-primary" onclick="startTravel()">4、行驶</button>
<button id="stopRun_B" type="button" class="btn btn-primary" onclick="stopTravel()">5、停止行驶</button>
<button id="unFire_B" type="button" class="btn btn-primary" onclick="unFire()">6、熄火</button>
<button id="unConnect_B" type="button" class="btn btn-primary" onclick="stopConnect()">7、断网</button>
<button id="unFire_B" type="button" class="btn btn-primary" onclick="fireOff()">6、熄火</button>
<button id="unConnect_B" type="button" class="btn btn-primary" onclick="disConnect()">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>
</div>
<div style="width:100%;padding-bottom:60px;border-bottom: 1px solid #eee;">
<h3>日志:</h3>
<textarea id="showFeedback" style="width:100%;padding:5px;padding-bottom:60px;" rows="10"></textarea>
</div>
<div style="width:100%;padding-bottom:10px;border-bottom: 1px solid #eee;">
<h4>查询今日车机行驶数据</h4>
<span>
<button id="searchCarData" type="button" class="btn btn-primary" id="saveSetting">查询</button>
</span>
</div>
</div>
{% endblock %}
</div>
......@@ -125,16 +135,50 @@ function connect(){
var data = getPageData();
var host = window.location.host;
var url = "http://" + host + "/messageTools/M_simulater_process/porcessConnect";
sendMsg(data,url);
sendHttpMsg(data,url);
startWebSocket();
$("#curStatus").val("连网");
}
//登录
function carLogin(){
var data = getPageData();
var host = window.location.host;
var url = "http://" + host + "/messageTools/M_simulater_process/porcessLogin";
sendHttpMsg(data,url);
}
//点火
function fireOn(){
var data = getPageData();
var host = window.location.host;
var url = "http://" + host + "/messageTools/M_simulater_process/porcessFireOn";
sendHttpMsg(data,url);
}
//发送GPS数据
function sendMsg(data,url){
//熄火
function fireOff(){
var data = getPageData();
var host = window.location.host;
var url = "http://" + host + "/messageTools/M_simulater_process/porcessFireOff";
sendHttpMsg(data,url);
}
//断网
function disConnect(){
var data = getPageData();
var host = window.location.host;
var url = "http://" + host + "/messageTools/M_simulater_process/porcessDisconnect";
sendHttpMsg(data,url);
}
//清空日志
function clearlog(){
$("#showFeedback").val("")
}
//发送控制信息
function sendHttpMsg(data,url){
var data = data;
var url = url;
var host = window.location.host;
console.log(data);
$("#showFeedback").val("")
$.ajax({
url:url,
type:"post",
......@@ -144,13 +188,15 @@ function sendMsg(data,url){
success:function(data){
if(data.status == 200){
//window.location.reload()
var theShow = "原始数据: " + data.original + "\n";
theShow = theShow + "收到数据: " + data.result + "\n";
theShow = theShow + "收到数据16进制: " + data.resultH + "\n";
theShow = theShow + "解析数据: " + JSON.stringify(data.parse) + "\n";
$("#showFeedback").val(theShow);
var curTime = getCurTime();
var txt = $("#showFeedback").val()
txt = txt + "[" + curTime + "] " + data.message + "\n"
$("#showFeedback").val(txt)
}else{
$("#showFeedback").val(data.message);
var curTime = getCurTime();
var txt = $("#showFeedback").val()
txt = txt + "[" + curTime + "] " + data.message + "\n"
$("#showFeedback").val(txt)
alert(data.message);
}
}
......@@ -232,5 +278,77 @@ function isShowLoginArea(e){
$("#login_area").css("display","block")
}
}
///////////////////////////////// websocket 代码开始 /////////////////////////////////
client = "0"
ws = null;
i = 1;
(function(){
ws = null;
i = 1;
})()
function startWebSocket(){
if ("WebSocket" in window){
console.log("您的浏览器支持 WebSocket!");
var domain = document.domain;
ws = new WebSocket("ws://" + domain + ":5007");
ws.onopen = function(){
console.log("socket 已经连接上!")
};
ws.onmessage = function (evt) {
var received_msg = JSON.parse(evt.data)
var curTime = getCurTime();
if(received_msg["code"] == "0001"){ //0001代表连接消息通信
client = received_msg["client"]
}
var text = $("#showFeedback").val()
if(text == ""){
text = text + "[" + curTime + "] " + received_msg["msg"] + "\n";
}else{
text = text + "[" + curTime + "] " + received_msg["msg"] + "\n";
$('#showFeedback').scrollTop($('#showFeedback')[0].scrollHeight);
}
$("#showFeedback").val(text)
};
ws.onclose = function(){
alert("连接已关闭..."); // 关闭 websocket
};
}else{
alert("您的浏览器不支持 WebSocket!"); // 浏览器不支持 WebSocket
}
}
function sendMsg(){
var msg = $("#sendMsg").val()
var data = {};
data["code"] = "0002"; //0002代表普通消息通信
data["client"] = client;
data["msg"] = msg;
data = JSON.stringify(data)
ws.send(data);
}
function endService(){
var msg = ""
var data = {};
data["code"] = "0003"; //0002代表普通消息通信
data["client"] = client;
data["msg"] = msg;
data = JSON.stringify(data)
ws.send(data);
}
function myclose(){
var data = {};
data["code"] = "0000"; //0000代表关闭服务器套接字程序
data["client"] = client;
data["msg"] = "";
data = JSON.stringify(data);
ws.send(data);
ws.close();
console.log("执行了socket服务的关闭操作...");
}
///////////////////////////////// websocket 代码结束 /////////////////////////////////
</script>
{% endblock %}
\ No newline at end of file
......@@ -748,7 +748,8 @@ $("#sendMsgBtn").click(function(){
data["baseInfo"] = getBaseInfo();
data["extraInfo"] = getExtraInfo();
console.log(data)
//console.log(data)
//console.log(JSON.stringify(data))
var host = window.location.host;
$("#showFeedback").val("");
......
......@@ -53,14 +53,12 @@ def porcessSocketSetting():
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)
......@@ -68,10 +66,10 @@ def porcessConnect():
connects.append(connect)
service = MessageSimulaterService()
service.setSocket(cliSocket)
service.setTimeout(timeout)
service.setData(params)
service.setSocket(cliSocket)
service.startWebsocketService()
service.setTimeout(int(params["timeout"]))
service.setData(params) #传入页面传过来的数据
service.startWebsocketService() #启动websocket服务
service.startReciveService() #接收消息的服务
connects[0]["service"] = service
data["status"] = "200"
data["message"] = "创建连接成功!"
......@@ -84,3 +82,82 @@ def porcessConnect():
data["status"] = "4003"
data["message"] = "Error: 连接失败!"
return Response(json.dumps(data), mimetype='application/json')
##########################################
# 【接口类型】车机登录
##########################################
@M_simulater_process.route("/porcessLogin",methods=['POST'])
def porcessLogin():
params = request.get_data()
params = json.loads(params.decode("utf-8"))
data = {}
try:
connects[0]["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_simulater_process.route("/porcessFireOn",methods=['POST'])
def porcessFireOn():
params = request.get_data()
params = json.loads(params.decode("utf-8"))
data = {}
try:
connects[0]["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_simulater_process.route("/porcessFireOff",methods=['POST'])
def porcessFireOff():
params = request.get_data()
params = json.loads(params.decode("utf-8"))
data = {}
try:
connects[0]["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_simulater_process.route("/porcessDisconnect",methods=['POST'])
def porcessDisconnect():
params = request.get_data()
params = json.loads(params.decode("utf-8"))
data = {}
try:
connects[0]["service"].socket.close()
connects[0]["service"].stopWebsocketService()
connects.pop(0)
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
......@@ -73,7 +73,6 @@ def createConect():
service.setSocket(cliSocket)
service.setTimeout(timeout)
service.setData(params)
service.setSocket(cliSocket)
service.startWebsocketService()
connects[0]["service"] = service
data["status"] = "200"
......
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