Commit 309013ba authored by liyuanhong's avatar liyuanhong

完成M500 电瓶采样类以及界面的开发

parent d57114d3
#coding:utf-8
'''
定义一个上报电瓶采样协议的类
'''
from lib.protocol.report.ProtocolBase import ProtocolBase
class VoltageDataReport_protocol(ProtocolBase):
def __init__(self,WATER_CODE = "0002",DEV_ID = "M121501010001",sampleNums=1,sampleData=[{"sampleTime":"2020-04-09 16:20:22","voltage":12}]):
super().__init__()
self.WATER_CODE = int(WATER_CODE); # 设置默认消息流水号
self.DEV_ID = DEV_ID # 设置默认设备id
self.sampleNums = sampleNums #采样个数
self.sampleData = sampleData #采样数据
#####################################################
# 生成终端登录消息
#####################################################
def generateMsg(self):
self.getProtocalHeader()
info = ""
HEADER = "4040" # 消息头
WATER_CODE = self.getWaterCode(self.WATER_CODE) # 消息流水号
DEV_ID = self.devid2hexString(self.DEV_ID) # 设备id
FUN_ID = "000A" # 功能id(终端登录功能id)
data = self.generateData() # 数据段
LENGTH = self.getMsgLength(int(len(WATER_CODE + DEV_ID + FUN_ID + data) / 2)) # 消息长度
info += HEADER
info += LENGTH
info += WATER_CODE
info += DEV_ID
info += FUN_ID
info += data
CHECK_CODE = self.getCheckCode(info) # 校验字段
info += CHECK_CODE
return info
#####################################################
# 创建终端登录数据段
#####################################################
def generateData(self):
data = ""
sampleNums = self.int2hexStringByBytes(self.sampleNums)
data = data + sampleNums
for i in range(0,self.sampleNums):
sampleData = self.getUTCTimeHex(self.sampleData[i]["sampleTime"]) + self.int2hexStringByBytes(int(self.sampleData[i]["voltage"]),2)
data = data + sampleData
return data
if __name__ == "__main__":
print(VoltageDataReport_protocol().generateMsg())
\ No newline at end of file
......@@ -4,6 +4,8 @@ import os
import socket
import sys
from lib.protocol.report.VoltageDataReport_protocol import VoltageDataReport_protocol
curdir = os.getcwd()
cpath = curdir + "\\..\\..\\"
sys.path.append(cpath)
......@@ -38,10 +40,11 @@ port = 9008
# msg = SecurityStatusReport_protocol().generateSecurityStatusMsg() #终端上报安防状态协议
# msg = BaseStationReport_protocol().generateBaseStationMsg() #终端上报基站定位协议
# msg = TroubleReport_protocol().generateTroubleMsg() #终端上报故障码数据包
msg = EventReport_protocol().generateEventMsg() #终端上报事件数据包
# msg = EventReport_protocol().generateEventMsg() #终端上报事件数据包
# msg = VersionReport_protocol().generateVersionMsg() #终端上报版本信息数据包
# msg = SleepReport_protocol().generateSleepMsg() #终端休眠数据包
# msg = CommonReport_protocol().generateCommonMsg() #通用应答消息
msg = VoltageDataReport_protocol().generateMsg() #终端上报电瓶电压采样数据
print(msg)
BUF_SIZE = 1024
......
#coding:utf-8
##################################################
# 定义M500 车机行驶过程中产生的数据类
##################################################
import datetime
import json
import time
class ProtocolSimulaterDataService():
def __init__(self):
self.data = {}
self.path = "/data/protocolTools/carData/" #保持车机数据文件地址
####################################################
# 生成一个默认数据模板
####################################################
def genDataTemplate(self):
data = {}
timeStamp = time.time()
timeArray = time.localtime(timeStamp)
data["time"] = {} #定义时间数据项
data["time"]["dateTime"] = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
data["time"]["date"] = time.strftime("%Y-%m-%d", timeArray)
data["time"]["time"] = time.strftime("%H:%M:%S", timeArray)
data["curDayTravel"] = {} #定义当天行驶数据项
data["curDayTravel"]["todayTotalMilleage"] = 0 #今日行驶总里程
data["curDayTravel"]["todayTotalOil"] = 0 #今日行驶总油耗
data["curDayTravel"]["todayTotalTime"] = 0 #今日行驶总时间
data["travelData"] = {} #定义所有行驶数据
data["travelData"]["totallMilleage"] = 0 #行驶总里程
data["travelData"]["totalOil"] = 0 #行驶总油耗
data["travelData"]["totalTime"] = 0 #行驶总时间
return data
####################################################
# 将数据写入文件
####################################################
def writeToFile(self,path,data):
with open(path,"w",encoding="utf-8") as fi:
data = json.dumps(data)
fi.write(data)
####################################################
# 从文件读取数据
####################################################
def readFromFile(self,path):
with open(path, "r", encoding="utf-8") as fi:
content = fi.read()
conJson = json.loads(content)
timeStamp = time.time()
timeArray = time.localtime(timeStamp)
dateTimeM = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
dateM = time.strftime("%Y-%m-%d", timeArray)
timeM = time.strftime("%H:%M:%S", timeArray)
if dateM == conJson["time"]["date"]:
pass
else:
conJson["time"]["dateTime"] = dateTimeM
conJson["time"]["date"] = dateM
conJson["time"]["time"] = timeM
self.data = conJson
if __name__ == "__main__":
print(ProtocolSimulaterDataService().genDataTemplate())
data = ProtocolSimulaterDataService().genDataTemplate()
ProtocolSimulaterDataService().writeToFile("../../../data/protocolTools/carData/M202003060520.json",data)
\ No newline at end of file
......@@ -16,6 +16,8 @@ function protocolManTab(e){
$(location).attr('href', "http://" + window.location.host + "/protocolTools/protocolReport_view/OBD_CAN_protocol_page");
}else if(id == "securityStatus_protocol"){
$(location).attr('href', "http://" + window.location.host + "/protocolTools/protocolReport_view/securityStatus_protocol_page");
}else if(id == "voltageData_protocol"){
$(location).attr('href', "http://" + window.location.host + "/protocolTools/protocolReport_view/voltageData_protocol_page");
}else{
alert(id)
}
......
......@@ -32,4 +32,38 @@ function getCutTimestamp(){
timestamp = String(timestamp);
timestamp = timestamp.slice(0,10);
return timestamp;
}
//时间格式转换为时间搓(返回的时间搓为毫秒格式)
function DateToTimestamp(string) {
var f = string.split(' ', 2);
var d = (f[0] ? f[0] : '').split('-', 3);
var t = (f[1] ? f[1] : '').split(':', 3);
var time = (new Date(
parseInt(d[0], 10) || null,
(parseInt(d[1], 10) || 1) - 1,
parseInt(d[2], 10) || null,
parseInt(t[0], 10) || null,
parseInt(t[1], 10) || null,
parseInt(t[2], 10) || null
//)).getTime() / 1000
)).getTime()
return time;
}
//时间戳转换为时间(时间戳为毫秒格式)
function formatDate(timeStamp) {
var d = new Date(timeStamp);
var year=d.getFullYear(); //取得4位数的年份
var month=d.getMonth()+1; //取得日期中的月份,其中0表示1月,11表示12月
if(month < 10){ month = "0" + month;}
var date=d.getDate(); //返回日期月份中的天数(1到31)
if(date < 10){ date = "0" + date;}
var hour=d.getHours(); //返回日期中的小时数(0到23)
if(hour < 10){ hour = "0" + hour;}
var minute=d.getMinutes(); //返回日期中的分钟数(0到59)
if(minute < 10){ minute = "0" + minute;}
var second=d.getSeconds(); //返回日期中的秒数(0到59)
if(second < 10){ second = "0" + second;}
return year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second;
}
\ No newline at end of file
......@@ -37,7 +37,7 @@
<li role="presentation"><a id="GPS_protocol" {% if arg.path[2]=="GPS_protocol_page" %} class="link-tab" {% endif %} onclick="protocolManTab(this)">GPS报文</b></a></li>
<li role="presentation"><a id="OBD_CAN_protocol" {% if arg.path[2]=="OBD_CAN_protocol_page" %} class="link-tab" {% endif %} onclick="protocolManTab(this)">OBD-CAN报文</b></a></li>
<li role="presentation"><a id="securityStatus_protocol" {% if arg.path[2]=="securityStatus_protocol_page" %} class="link-tab" {% endif %} onclick="protocolManTab(this)">安防状态报文</b></a></li>
<li role="presentation"><a id="style_index2" {% if arg.path[2]=="2" %} class="link-tab" {% endif %} onclick="protocolManTab(this)">其他报文</b></a></li>
<li role="presentation"><a id="voltageData_protocol" {% if arg.path[2]=="voltageData_protocol_page" %} class="link-tab" {% endif %} onclick="protocolManTab(this)">电瓶电压采样报文</b></a></li>
</ul>
{% endblock %}
{% block content_1 %}
......@@ -91,8 +91,8 @@
<li><label>发动机转速:</label><input id="engineSpeed" type="text" class="form-control" value="3000"></li>
<li><label>累计里程:</label><input id="GPSTotalMileage" type="text" class="form-control" value="12800"></li>
<li><label>累计油耗:</label><input id="totalOil" type="text" class="form-control" value="100000"></li>
<li><label style="font-size:12px;">累计行驶时间:</label><input id="totalTime" type="text" class="form-control" value="2020002"></li>
<li><label style="font-size:12px;">GPS信息时间戳:</label><input id="GPSTimestamp" type="text" class="form-control"></li>
<li><label style="font-size:10px;">累计行驶时间:</label><input id="totalTime" type="text" class="form-control" value="2020002"></li>
<li><label style="font-size:10px;">GPS信息时间戳:</label><input id="GPSTimestamp" type="text" class="form-control"></li>
</ul>
<H3 style="border-bottom: 1px solid #eee;">控制:</H3>
<div style="width:100%;padding:5px;margin-top:10px;">
......
{% extends "protocolTools/report/GPS_protocol_page.html" %}
{% block title %}VoltageData_protocol{% endblock %}
{% 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 style="width:100%;_background:green;padding:5px;padding-top:0px;">
<h3 style="border-bottom: 1px solid #eee;">设置协议头:</h3>
<label>消息流水号:</label><input id="WATER_CODE" type="text" class="form-control" value="0003" style="width:100px;">
<label style="margin-left:10px;">车机号:</label><input id="DEV_ID" type="text" class="form-control" value="M121501010001">
</div>
<H3 style="border-bottom: 1px solid #eee;">设置心跳消息内容:</H3>
<ul class="protocol_content" style="padding:0px;">
<li style="width:170px"><label>采样个数:</label><input style="width:80px;" id="sampleNums" type="text" class="form-control" value="2"></li>
<li><label style="font-size:10px;">采样开始时间:</label><input id="curTime" type="text" class="form-control" value=""></li>
<li><label style="font-size:10px;">采样间隔时间(秒):</label><input id="durTime" type="text" class="form-control" value="60"></li>
<li style="width:500px"><label style="font-size:10px;">采样值,多个用空格隔开:</label><input style="width:400px;" id="sampleVals" type="text" class="form-control" value="12 14"></li>
</ul>
<H3 style="border-bottom: 1px solid #eee;">控制:</H3>
<div style="width:100%;padding:5px;margin-top:10px;">
<button type="button" class="btn btn-primary" id="sendMsgBtn">发送消息</button>
</div>
<H3 style="border-bottom: 1px solid #eee;">返回信息:</H3>
<div style="width:100%;padding:5px;margin-top:10px;">
<textarea id="showFeedback" style="width:100%;padding:5px;" rows="8"></textarea>
</div>
</div>
<script>
//发送电瓶采样数据包
$("#sendMsgBtn").click(function(){
var WATER_CODE = $("#WATER_CODE").val();
var DEV_ID = $("#DEV_ID").val();
var sampleNums = parseInt($("#sampleNums").val());
var curTime = $("#curTime").val();
var durTime = parseInt($("#durTime").val());
var sampleVals = $("#sampleVals").val();
var sampleValsArr = sampleVals.split(" ")
var data = {};
data["WATER_CODE"] = WATER_CODE;
data["DEV_ID"] = DEV_ID;
data["sampleNums"] = sampleNums;
var sampleData = [];
data["sampleData"] = sampleData;
for(var i = 0;i < sampleNums;i++){
var d = {}
if(i == 0){
d["sampleTime"] = curTime;
d["voltage"] = sampleValsArr[i]
}else{
ts = DateToTimestamp(curTime) + durTime * 1000;
d["sampleTime"] = formatDate(ts)
d["voltage"] = sampleValsArr[i]
}
sampleData.push(d)
}
if(sampleValsArr.length < sampleNums){
alert("采样值不足" + sampleNums + "")
}else{
var host = window.location.host;
$("#showFeedback").val("")
$.ajax({
url:"http://" + host + "/protocolTools/protocolReport_process/porcessVoltageDataMsg",
type:"post",
data:JSON.stringify(data),
contentType:"application/json",
dataType:"json",
success:function(data){
if(data.status == 200){
//window.location.reload()
msg = "发送消息:" + data.msgSend + "\n"
msg = msg + "收到消息:" + data.result + "\n"
msg = msg + "收到消息16进制:" + data.rev + "\n"
msg = msg + "收到消息解析结果:" + JSON.stringify(data.orgRev) + "\n"
$("#showFeedback").val(msg)
}else{
$("#showFeedback").val(data.message)
alert(data.message);
}
}
});
}
});
//设置当前时间到UTC时间输入框
(function(){
var curTime = getCurTime();
$("#curTime").val(curTime);
})();
</script>
{% endblock %}
\ No newline at end of file
......@@ -8,6 +8,7 @@ from lib.protocol.report.LoginReport_protocol import LoginReport_protocol
from lib.protocol.report.GPSReport_protocol import GPSReport_protocol
from lib.protocol.report.OBDReport_CAN_protocol import OBDReport_CAN_protocol
from lib.protocol.report.SecurityStatusReport_protocol import SecurityStatusReport_protocol
from lib.protocol.report.VoltageDataReport_protocol import VoltageDataReport_protocol
from lib.protocol.reportPlateform.Common_res import Common_res
from lib.protocol.reportPlateform.Login_res import Login_res
......@@ -16,6 +17,8 @@ import json
import traceback
import binascii
from lib.util.jsonUtil import hasJsonDataIsNone
protocolReport_process = Blueprint('protocolReport_process', __name__)
##########################################
......@@ -334,6 +337,43 @@ def porcessSecurityStatusMsg():
return Response(json.dumps(data), mimetype='application/json')
##########################################
# 【接口类型】处理发送的电瓶采样上报报文
##########################################
@protocolReport_process.route("/porcessVoltageDataMsg",methods=['POST'])
def porcessVoltageDataMsg():
params = request.get_data()
params = json.loads(params.decode("utf-8"))
data = {}
if (hasJsonDataIsNone(params)):
data["status"] = "4003"
data["message"] = "Info: 请检查是否传入了空数据!"
return Response(json.dumps(data), mimetype='application/json')
else:
try:
conf_R = ConfigParser()
conf_R.read("config/protocolTools/protocolTools.conf")
cliSocket = ClientSocket(conf_R.get("socket", "host"),conf_R.getint("socket", "port"))
cliSocket.connect()
protocolObj = VoltageDataReport_protocol(WATER_CODE=params["WATER_CODE"],DEV_ID=params["DEV_ID"], \
sampleNums=params["sampleNums"],sampleData=params["sampleData"])
msg = protocolObj.generateMsg()
cliSocket.send(msg)
socRecv = cliSocket.receive()
socRecvo = str(socRecv)
cliSocket.close()
data["status"] = "200"
data["message"] = "Sucess: "
data["msgSend"] = msg
data["result"] = socRecvo
data["rev"] = str(binascii.b2a_hex(socRecv))[2:][:-1]
data["orgRev"] = data["orgRev"] = json.loads(Common_res(data["rev"]).getMsg())
except BaseException as e:
# 打印异常信息
traceback.print_exc()
data["status"] = "4003"
data["message"] = "Error: 处理失败!"
return Response(json.dumps(data), mimetype='application/json')
......
......@@ -90,4 +90,19 @@ def securityStatus_protocol_page():
arg = {}
path = "protocolTools/report/securityStatus_protocol_page.html"
arg["path"] = reqPath.split("/")
return render_template(path,arg=arg)
\ No newline at end of file
return render_template(path,arg=arg)
##########################################
# 【视图类型】访问终端上报安防状态协议报文发送页面
##########################################
@protocolReport_view.route('/voltageData_protocol_page')
def voltageData_protocol_page():
#获取请求的路劲
url = request.url
reqPath = re.findall("http://(.*)$",url)[0]
reqPath = re.findall("/(.*)$", reqPath)[0]
arg = {}
path = "protocolTools/report/voltageData_protocol_page.html"
arg["path"] = reqPath.split("/")
return render_template(path,arg=arg)
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