Commit 11cac106 authored by liyuanhong's avatar liyuanhong

模拟器回复平台功能完成

parent ddaf3a31
[socket] [socket]
host = 10.100.12.32 host = 10.100.5.251
port = 9008 port = 9008
This diff is collapsed.
#coding:utf-8
'''
定义一个通用应答数据包
'''
from lib.protocol.report.ProtocolBase import ProtocolBase
class CommonReport_protocol(ProtocolBase):
def __init__(self,msgCount = 1,WATER_CODE = 1000,DEV_ID = "M121501010001",resId="8205",status="00"):
super().__init__()
self.msgCount = int(msgCount)
self.WATER_CODE = int(WATER_CODE); # 设置默认消息流水号
self.DEV_ID = DEV_ID # 设置默认设备id
self.resId = resId #应答的功能ID
self.status = status #应答状态
def setResId(self,data):
self.resId = data
def setStatus(self,data):
self.status = data
#####################################################
# 生成 通用应答 消息
#####################################################
def generateCommonMsg(self):
self.getProtocalHeader()
info = ""
HEADER = "4040" #消息头
WATER_CODE = self.getWaterCode(self.WATER_CODE) #消息流水号
DEV_ID = self.devid2hexString(self.DEV_ID) #设备id
FUN_ID = "0000" # 功能id
data = "" #数据段
for i in range(0,self.msgCount):
data += self.generateCommonPkg(self.generateCommonData())
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 generateCommonPkg(self,data):
return data
#####################################################
# 创建 版本信息 数据段
#####################################################
def generateCommonData(self):
data = ""
resId = self.resId
status = self.status
data = resId + status
return data
if __name__ == "__main__":
print(CommonReport_protocol().generateCommonMsg())
\ No newline at end of file
...@@ -14,7 +14,6 @@ class LoginReport_protocol(ProtocolBase): ...@@ -14,7 +14,6 @@ class LoginReport_protocol(ProtocolBase):
self.cpuId = cpuId #设置默认cupId值 self.cpuId = cpuId #设置默认cupId值
self.imsi = imsi #设置默认imsi值 self.imsi = imsi #设置默认imsi值
self.ccid = ccid #设置默认ccid值 self.ccid = ccid #设置默认ccid值
self.imei = imei #设置默认imei值 self.imei = imei #设置默认imei值
......
...@@ -194,8 +194,8 @@ if __name__ == "__main__": ...@@ -194,8 +194,8 @@ if __name__ == "__main__":
# print(ProtocolBase().str2Hex("a")) # print(ProtocolBase().str2Hex("a"))
# print(ProtocolBase().int2hexStringByBytes(1,6)) # print(ProtocolBase().int2hexStringByBytes(1,6))
# print(ProtocolBase().num2signedNum(-5)) # print(ProtocolBase().num2signedNum(-5))
# print(ProtocolBase().getUTCTimeHex("2020-01-03 13:05:13")) print(ProtocolBase().getUTCTimeHex("2020-01-03 13:05:13"))
# print(ProtocolBase().hex2UTCTime("1401030d050d")) # print(ProtocolBase().hex2UTCTime("1401030d050d"))
# print(ProtocolBase().hex2UTCTime("14020a07122b")) # print(ProtocolBase().hex2UTCTime("14020a07122b"))
print(ProtocolBase().crc16("4040007000064d20191201000200120114030503202d26d7fffff0000000000505000000143c00000bb80100000fa00000000a0000000000005e60723b723b39331e100055320000001312001007d0001e0000000000000096000000280096ffff3e0001f40000003e0000000000000000000000")) # print(ProtocolBase().crc16("4040007000064d20191201000200120114030503202d26d7fffff0000000000505000000143c00000bb80100000fa00000000a0000000000005e60723b723b39331e100055320000001312001007d0001e0000000000000096000000280096ffff3e0001f40000003e0000000000000000000000"))
print(ProtocolBase().myCrc16("4040007000064d20191201000200120114030503202d26d7fffff0000000000505000000143c00000bb80100000fa00000000a0000000000005e60723b723b39331e100055320000001312001007d0001e0000000000000096000000280096ffff3e0001f40000003e0000000000000000000000")) # print(ProtocolBase().myCrc16("4040007000064d20191201000200120114030503202d26d7fffff0000000000505000000143c00000bb80100000fa00000000a0000000000005e60723b723b39331e100055320000001312001007d0001e0000000000000096000000280096ffff3e0001f40000003e0000000000000000000000"))
...@@ -26,7 +26,7 @@ class SleepReport_protocol(ProtocolBase): ...@@ -26,7 +26,7 @@ class SleepReport_protocol(ProtocolBase):
HEADER = "4040" #消息头 HEADER = "4040" #消息头
WATER_CODE = self.getWaterCode(self.WATER_CODE) #消息流水号 WATER_CODE = self.getWaterCode(self.WATER_CODE) #消息流水号
DEV_ID = self.devid2hexString(self.DEV_ID) #设备id DEV_ID = self.devid2hexString(self.DEV_ID) #设备id
FUN_ID = "0005" # 功能id FUN_ID = "00FF" # 功能id
data = "" #数据段 data = "" #数据段
for i in range(0,self.msgCount): for i in range(0,self.msgCount):
data += self.generateSleepPkg(self.generateSleepData()) data += self.generateSleepPkg(self.generateSleepData())
......
...@@ -27,7 +27,7 @@ class VersionReport_protocol(ProtocolBase): ...@@ -27,7 +27,7 @@ class VersionReport_protocol(ProtocolBase):
HEADER = "4040" #消息头 HEADER = "4040" #消息头
WATER_CODE = self.getWaterCode(self.WATER_CODE) #消息流水号 WATER_CODE = self.getWaterCode(self.WATER_CODE) #消息流水号
DEV_ID = self.devid2hexString(self.DEV_ID) #设备id DEV_ID = self.devid2hexString(self.DEV_ID) #设备id
FUN_ID = "00FF" # 功能id FUN_ID = "0005" # 功能id
data = "" #数据段 data = "" #数据段
for i in range(0,self.msgCount): for i in range(0,self.msgCount):
data += self.generateVersionPkg(self.generateVersionData()) data += self.generateVersionPkg(self.generateVersionData())
......
#coding:utf-8
'''
定义一个通用应答数据包
'''
from lib.protocol.report.ProtocolBase import ProtocolBase
class Common_response(ProtocolBase):
def __init__(self,msgCount = 1,WATER_CODE = 1000,DEV_ID = "M121501010001",resId="8205",status="00"):
super().__init__()
self.msgCount = int(msgCount)
self.WATER_CODE = int(WATER_CODE); # 设置默认消息流水号
self.DEV_ID = DEV_ID # 设置默认设备id
self.resId = resId #应答的功能ID
self.status = status #应答状态
def setResId(self,data):
self.resId = data
def setStatus(self,data):
self.status = data
#####################################################
# 生成 通用应答 消息
#####################################################
def generateCommonMsg(self):
self.getProtocalHeader()
info = ""
HEADER = "4040" #消息头
WATER_CODE = self.getWaterCode(self.WATER_CODE) #消息流水号
DEV_ID = self.devid2hexString(self.DEV_ID) #设备id
FUN_ID = "0000" # 功能id
data = "" #数据段
for i in range(0,self.msgCount):
data += self.generateCommonPkg(self.generateCommonData())
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 generateCommonPkg(self,data):
return data
#####################################################
# 创建 通用应答 数据段
#####################################################
def generateCommonData(self):
data = ""
resId = self.resId
status = self.status
data = resId + status
return data
if __name__ == "__main__":
print(Common_response().generateCommonMsg())
\ No newline at end of file
#coding:utf-8
'''
定义一个升级应答数据包
'''
from lib.protocol.report.ProtocolBase import ProtocolBase
class Update_response(ProtocolBase):
def __init__(self,msgCount = 1,WATER_CODE = 1000,DEV_ID = "M121501010001",status="00"):
super().__init__()
self.msgCount = int(msgCount)
self.WATER_CODE = int(WATER_CODE); # 设置默认消息流水号
self.DEV_ID = DEV_ID # 设置默认设备id
self.status = status #应答状态
def setStatus(self,data):
self.status = data
#####################################################
# 生成 升级应答 消息
#####################################################
def generateUpdateMsg(self):
self.getProtocalHeader()
info = ""
HEADER = "4040" #消息头
WATER_CODE = self.getWaterCode(self.WATER_CODE) #消息流水号
DEV_ID = self.devid2hexString(self.DEV_ID) #设备id
FUN_ID = "0300" # 功能id
data = "" #数据段
for i in range(0,self.msgCount):
data += self.generateUpdatePkg(self.generateUpdateData())
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 generateUpdatePkg(self,data):
return data
#####################################################
# 创建 升级应答 数据段
#####################################################
def generateUpdateData(self):
data = ""
status = self.status
data = status
return data
if __name__ == "__main__":
print(Update_response().generateUpdateMsg())
\ No newline at end of file
#encoding:utf-8 #encoding:utf-8
import binascii import binascii
import time
from lib.protocol.Base import Base from lib.protocol.Base import Base
...@@ -84,7 +85,30 @@ class ResponseBase(Base): ...@@ -84,7 +85,30 @@ class ResponseBase(Base):
else: else:
return inputStr return inputStr
#######################################################
# utc 时间格式的16进制字符串转时间
######################################################
def hexDate2date(self,hexData):
UTCTime = "20"
UTCTime = UTCTime + str(self.hexString2int(hexData[:2]))
UTCTime = UTCTime + "-" + str(self.hexString2int(hexData[2:4]))
UTCTime = UTCTime + "-" + str(self.hexString2int(hexData[4:6]))
UTCTime = UTCTime + " " + str(self.hexString2int(hexData[6:8]))
UTCTime = UTCTime + ":" + str(self.hexString2int(hexData[8:10]))
UTCTime = UTCTime + ":" + str(self.hexString2int(hexData[10:12]))
return UTCTime
#######################################################
# 时间戳的16进制字符串转时间
######################################################
def hexTimestamp2date(self,hexData):
timeStamp = self.hexString2int(hexData)
timeArray = time.localtime(timeStamp)
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
return otherStyleTime
if __name__ == "__main__":
print(ResponseBase().hexDate2date("01c329ed065"))
print(ResponseBase().hexTimestamp2date("5e60723b"))
#coding:utf-8 #coding:utf-8
import binascii import binascii
import socket import socket
from lib.protocol.report.CommonReport_protocol import CommonReport_protocol
from lib.protocol.report.GPSReport_protocol import GPSReport_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.OBDReport_CAN_protocol import OBDReport_CAN_protocol
from lib.protocol.report.OBDReport_CAN_protocol import OBDReport_CAN_protocol from lib.protocol.report.OBDReport_CAN_protocol import OBDReport_CAN_protocol
...@@ -25,15 +27,15 @@ port = 9008 ...@@ -25,15 +27,15 @@ port = 9008
# msg = GPSReport_protocol().generateGpsMsg() #GPS消息数据 # msg = GPSReport_protocol().generateGpsMsg() #GPS消息数据
# msg = OBDReport_protocol().generateOBDReportMsg() #OBD终端上报数据 # msg = OBDReport_protocol().generateOBDReportMsg() #OBD终端上报数据
# msg = OBDReport_CAN_protocol().generateOBDReportCANMsg() #OBD终端上报CAN数据 # msg = OBDReport_CAN_protocol().generateOBDReportCANMsg() #OBD终端上报CAN数据
# msg = HeartBeatReport_protocol().generateHeartBeatMsg() #终端上报心跳协议 msg = HeartBeatReport_protocol().generateHeartBeatMsg() #终端上报心跳协议
# msg = LoginReport_protocol().generateLoginMsg() #终端上报登录协议 # msg = LoginReport_protocol().generateLoginMsg() #终端上报登录协议
# msg = SecurityStatusReport_protocol().generateSecurityStatusMsg() #终端上报安防状态协议 # msg = SecurityStatusReport_protocol().generateSecurityStatusMsg() #终端上报安防状态协议
# msg = BaseStationReport_protocol().generateBaseStationMsg() #终端上报基站定位协议 # msg = BaseStationReport_protocol().generateBaseStationMsg() #终端上报基站定位协议
# msg = TroubleReport_protocol().generateTroubleMsg() #终端上报故障码数据包 # msg = TroubleReport_protocol().generateTroubleMsg() #终端上报故障码数据包
# msg = EventReport_protocol().generateEventMsg() # msg = EventReport_protocol().generateEventMsg()
# msg = VersionReport_protocol().generateVersionMsg() #终端上报版本信息数据包 # msg = VersionReport_protocol().generateVersionMsg() #终端上报版本信息数据包
msg = SleepReport_protocol().generateSleepMsg() #终端休眠数据包 # msg = SleepReport_protocol().generateSleepMsg() #终端休眠数据包
msg = CommonReport_protocol().generateCommonMsg() #通用应答消息
print(msg) print(msg)
BUF_SIZE = 1024 BUF_SIZE = 1024
...@@ -41,6 +43,7 @@ client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ...@@ -41,6 +43,7 @@ client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) # 在客户端开启心跳 client.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) # 在客户端开启心跳
client.connect((host, port)) client.connect((host, port))
client.send(binascii.a2b_hex(msg)) client.send(binascii.a2b_hex(msg))
# client.send(bytes.fromhex(msg)) # client.send(bytes.fromhex(msg))
data = client.recv(BUF_SIZE) data = client.recv(BUF_SIZE)
print(data) print(data)
......
#coding:utf-8
'''
M500车机模拟服务类
'''
import binascii
import threading
import traceback
from time import sleep
from lib.protocol.report.response.Common_response import Common_response
from lib.protocol.report.response.Update_response import Update_response
from lib.socket.service.websocket_service import Websocket_service
class ProtocolSimulaterService():
def __init__(self):
self.socket = None
self.sendDur = 5 #设置默认多久发一条消息
self.serviceStatus = 0 #服务状态,0表示未启动,1表示启动
self.websocket = None #网页与服务的通信socket
self.timeout = 1 #socket的超时时间
#设置套接字
def setSocket(self,data):
self.socket = data
def setSendDur(self,data):
self.sendDur = data
def setTimeout(self,data):
self.timeout = data
def getWebsocket(self):
return self.websocket
def sendMsg(self,msg):
self.socket.setTimeOut(self.timeout)
self.socket.send(msg)
def revMsg(self):
self.socket.setTimeOut(self.timeout)
return self.socket.receive()
#发送消息,可指定消息的描述类型
def serviceSendMsg(self,msg,type): #type字段目前废掉没有实际意义
self.sendMsg(msg)
type = self.getMsgFunId(msg)
self.websocket.send(">>>>" + type + ":" + msg)
# d = self.revMsg()
# d = str(binascii.b2a_hex(d))[2:][:-1]
# self.websocket.send("<<<<" + type +":" + d)
# info = "\n车机发送了" + type + "消息:" + msg + "\n车机收到了消息:" + d
# self.websocket.send(info)
def serviceSend(self):
while self.serviceStatus == 1:
msg = "4040000b00034d1215010100010003f50b"
self.sendMsg(msg)
type = self.getMsgFunId(msg)
info = type + ">>>>:" + msg
self.websocket.send(info)
sleep(self.sendDur)
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)
#停止与页面交互的websockt服务
def websocketService(self):
self.websocket = Websocket_service()
self.websocket.setHost("127.0.0.1")
self.websocket.setPort(5005)
self.websocket.startWebsocketServer()
#启动定时发送消息和接收消息的服务
def startService(self):
self.serviceStatus = 1
t1 = threading.Thread(target=self.serviceSend,args=())
# t2 = threading.Thread(target=self.serviceRev, args=())
# t2.start()
t1.start()
#启动与页面交互的websocket服务
def startWebsocketService(self):
if self.websocket == None:
t = threading.Thread(target=self.websocketService, args=())
t.start()
t2 = threading.Thread(target=self.serviceRev, args=())
t2.start()
#停止定时发送消息的服务
def stopService(self):
self.serviceStatus = 0
def closeSocket(self):
try:
self.socket.close()
except BaseException as e:
# 打印异常信息
traceback.print_exc()
def stopWebsocketService(self):
try:
self.websocket.close()
self.websocket = None
except BaseException as e:
# 打印异常信息
traceback.print_exc()
#获取收到消息的功能id
def getMsgFunId(self,msg):
funId = msg[26:30]
return funId
#收到 某些类型的消息后执行回复操作
def doResponse(self,msg):
msgFunId = self.getMsgFunId(msg)
if msgFunId == "8205":
msg = Common_response(resId="8205").generateCommonMsg()
self.sendMsg(msg)
type = self.getMsgFunId(msg)
self.websocket.send(type + ">>>>设置GPSR通信参数应答:" + msg)
elif msgFunId == "8206":
msg = Common_response(resId="8206").generateCommonMsg()
self.sendMsg(msg)
type = self.getMsgFunId(msg)
self.websocket.send(type + ">>>>设置车辆OBD适配信息应答:" + msg)
elif msgFunId == "8300":
msg = Update_response().generateUpdateMsg()
self.sendMsg(msg)
type = self.getMsgFunId(msg)
self.websocket.send(type + ">>>>升级_平台通知终端远程升级应答:" + msg)
#coding: utf-8
import json
import logging
import threading
import time
from time import sleep
from lib.socket.SocketBase import SocketBase
from lib.socket.websocket_server import WebsocketServer
class Websocket_service(SocketBase):
def __init__(self,host="127.0.0.1",port=5005):
self.host = host
self.port = port
self.server = None
self.clients = {}
self.currentClient = None
def setHost(self,data):
self.host = data
def setPort(self,data):
self.port = data
def startWebsocketServer(self):
server = WebsocketServer(self.port, host=self.host, loglevel=logging.INFO)
server.set_fn_new_client(self.new_client)
server.set_fn_message_received(self.doRev)
self.server = server
server.run_forever()
server.server_close()
#有客户端连接成功之后,回复一条消息
def new_client(self,client, server):
# server.send_message_to_all("连接成功......")
clientId = "client_" + str(len(self.clients))
data = {}
data["code"] = "0001" #收到连接请求
data["client"] = clientId
data["msg"] = "websocket连接成功......"
data = json.dumps(data)
self.currentClient = clientId
server.send_message(client, data)
self.clients[clientId] = client
self.connectTimeout = 1
#收到消息之后进行处理的方法
def doRev(self,client,server,msg):
# server.send_message(client,"message send ...")
data = json.loads(msg)
code = data["code"]
theMsg = data["msg"]
clientId = data["client"]
self.currentClient = clientId
if(code == "0002"): #收到一条普通消息
data = {}
data["code"] = "0002"
data["client"] = clientId
data["msg"] = "收到消息:" + theMsg
data = json.dumps(data)
server.send_message(client, data)
if(code == "0000"): #收到 0000 控制码的时候,关闭socket服务
server.server_close()
print("连接断开...")
if(code == "0003"): #断开与客户端的连接
self.clients.pop(clientId)
data = {}
data["code"] = "0003"
data["client"] = clientId
data["msg"] = "断开连接!"
data = json.dumps(data)
server.send_message(client, data)
raise Exception("客户端连接断开")
#断开服务端的socket服务
def close(self):
self.server.server_close()
#给当前连接的客户端发送消息
def send(self,msg):
data = {}
data["code"] = "0002"
data["client"] = self.currentClient
data["msg"] = "收到消息:" + msg
data = json.dumps(data)
self.server.send_message(self.clients[self.currentClient],data)
if __name__ == "__main__":
w = Websocket_service()
w.setHost("127.0.0.1")
w.setPort(5005)
w.startWebsocketServer()
\ No newline at end of file
#coding: utf-8
import logging
import threading
import time
from time import sleep
from lib.socket.SocketBase import SocketBase
from lib.socket.websocket_server import WebsocketServer
class Websocket_service(SocketBase):
def __init__(self,host="127.0.0.1",port=5005):
self.connectTimeout = 5 #设置socket服务启动之后的连接超时时间
self.connectTimeoutstatus = 0 #设置socket服务启动之后是否有连接,0为为收到连接,1:为已经收到了连接
self.msgTimeout = 12 #设置12秒没有收到任何消息之后,就关闭连接
self.host = host
self.port = port
self.connectNums = 0 #连接数
def setConnectTimeout(self,data):
self.connectTimeout = data
def setMsgTimeout(self,data):
self.msgTimeout = data
def setHost(self,data):
self.host = data
def setPort(self,data):
self.port = data
def startWebsocketServer(self):
server = WebsocketServer(self.port, host=self.host, loglevel=logging.INFO)
server.set_fn_new_client(self.new_client)
server.set_fn_message_received(self.mysend)
self.connectTimeoutThreading(server) #启动超时连接线程
self.msgTimeoutThreading(server) #启动接收消息超时连接线程
server.run_forever()
server.server_close()
#有客户端连接成功之后,回复一条消息
def new_client(self,client, server):
server.send_message_to_all("连接成功......")
self.connectTimeout = 1
#收到消息之后的恢复消息方法
def mysend(self,client,server,msg):
server.send_message(client,"message send ...")
if(msg == "_end"): #收到_end 控制码的时候,断开连接
server.server_close()
print("连接断开...")
###################################################
# 超过时间没有客户端连接,自动断开连接线程
###################################################
def connectTimeoutThreading(self,server):
t1 = threading.Thread(target=self.doConnectTomeout, args=(server,))
t1.start()
###################################################
# 超过时间没有客户端连接,自动断开连接方法
###################################################
def doConnectTomeout(self,server):
startTime = int(time.time())
endTime = int(time.time())
while endTime - startTime < self.connectTimeout:
self.connectTimeout -= 1
endTime = int(time.time())
sleep(0.1)
if self.connectTimeoutstatus == 0:
server.server_close()
print("连接断开...")
else:
pass
###################################################
# 超过时间没有收到任何消息,自动断开连接线程
###################################################
def msgTimeoutThreading(self, server):
t1 = threading.Thread(target=self.doMsgTimeout, args=(server,))
t1.start()
###################################################
# 超过时间没有收到任何消息,自动断开连接方法
###################################################
def doMsgTimeout(self, server):
while self.msgTimeout > 0:
self.msgTimeout -= 1
sleep(1)
if self.connectTimeout == 1:
server.server_close()
print("连接断开...")
if __name__ == "__main__":
w = Websocket_service()
w.setHost("127.0.0.1")
w.setPort(5005)
w.startWebsocketServer()
\ No newline at end of file
...@@ -38,7 +38,7 @@ ...@@ -38,7 +38,7 @@
<ul class="nav nav-sidebar"> <ul class="nav nav-sidebar">
<li id="setting" onclick="swichLeftTab(this)"><a {% if arg.path[1]=="setting_view" %} class="active_left_tab" {% endif %}><span class="glyphicon glyphicon-cog" aria-hidden="true"></span> 系统设置</a></li> <li id="setting" onclick="swichLeftTab(this)"><a {% if arg.path[1]=="setting_view" %} class="active_left_tab" {% endif %}><span class="glyphicon glyphicon-cog" aria-hidden="true"></span> 系统设置</a></li>
<li id="protocols_report" onclick="swichLeftTab(this)"><a {% if arg.path[1]=="protocolReport_view" %} class="active_left_tab" {% endif %}><span class="glyphicon glyphicon-list-alt" aria-hidden="true"></span> 终端上报报文<span class="sr-only"></span></a></li> <li id="protocols_report" onclick="swichLeftTab(this)"><a {% if arg.path[1]=="protocolReport_view" %} class="active_left_tab" {% endif %}><span class="glyphicon glyphicon-list-alt" aria-hidden="true"></span> 终端上报报文<span class="sr-only"></span></a></li>
<li id="protocols_query" onclick="swichLeftTab(this)"><a {% if arg.path[1]=="protocolQuery_view" %} class="active_left_tab" {% endif %}><span class="glyphicon glyphicon-list-alt" aria-hidden="true"></span> 远程查询报文<span class="sr-only"></span></a></li> <!-- <li id="protocols_query" onclick="swichLeftTab(this)"><a {% if arg.path[1]=="protocolQuery_view" %} class="active_left_tab" {% endif %}><span class="glyphicon glyphicon-list-alt" aria-hidden="true"></span> 远程查询报文<span class="sr-only"></span></a></li>-->
</ul> </ul>
<ul class="nav nav-sidebar" style="margin-top:20px;"> <ul class="nav nav-sidebar" style="margin-top:20px;">
<li id="car_simulater" onclick="swichLeftTab(this)"><a {% if arg.path[1]=="M_carSimulater_view" %} class="active_left_tab" {% endif %}><span class="glyphicon glyphicon-hand-right" aria-hidden="true"></span> 车辆行为模拟</a></li> <li id="car_simulater" onclick="swichLeftTab(this)"><a {% if arg.path[1]=="M_carSimulater_view" %} class="active_left_tab" {% endif %}><span class="glyphicon glyphicon-hand-right" aria-hidden="true"></span> 车辆行为模拟</a></li>
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
<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> <div>
<span> <span>
<label>超时时间(秒):</label><input id="timeout" type="text" class="form-control" style="width:100px;" value="10"> <label>超时时间(秒):</label><input id="timeout" type="text" class="form-control" style="width:100px;" value="1">
</span> </span>
</div> </div>
<H3 style="border-bottom: 1px solid #eee;">输入消息内容:</H3> <H3 style="border-bottom: 1px solid #eee;">输入消息内容:</H3>
......
...@@ -33,7 +33,10 @@ ...@@ -33,7 +33,10 @@
<!-- <label>主机地址:</label><input id="host" type="text" class="form-control" value="" style="width:100px;">--> <!-- <label>主机地址:</label><input id="host" type="text" class="form-control" value="" style="width:100px;">-->
<!-- <label style="margin-left:10px;">端口:</label><input id="port" type="text" class="form-control" value="">--> <!-- <label style="margin-left:10px;">端口:</label><input id="port" type="text" class="form-control" value="">-->
<button type="button" class="btn btn-sm btn-primary" id="connect">连接服务器</button> <button type="button" class="btn btn-sm btn-primary" id="connect">连接服务器</button>
<label style="margin-left:20px;">消息:</label><input id="sendMsg" type="text" class="form-control"><button id="send" type="button" style="margin-left:10px;" class="btn btn-sm btn-primary">发送</button> <label style="margin-left:20px;">消息:</label><input id="sendMsg" type="text" class="form-control">
<button id="send" type="button" style="margin-left:10px;" class="btn btn-sm btn-primary">发送</button>
<button id="close" type="button" style="margin-left:10px;" class="btn btn-sm btn-primary">断开</button>
<button id="end" type="button" style="margin-left:10px;" class="btn btn-sm btn-primary">关闭服务</button>
<H3>接收消息:</H3><textarea id="revMsg" style="width:500px;padding:5px;display:block;" rows="8"></textarea> <H3>接收消息:</H3><textarea id="revMsg" style="width:500px;padding:5px;display:block;" rows="8"></textarea>
</div> </div>
</div> </div>
...@@ -41,6 +44,7 @@ ...@@ -41,6 +44,7 @@
<script> <script>
client = "0"
ws = null; ws = null;
i = 1; i = 1;
(function(){ (function(){
...@@ -56,13 +60,16 @@ ...@@ -56,13 +60,16 @@
console.log("socket 已经连接上!") console.log("socket 已经连接上!")
}; };
ws.onmessage = function (evt) { ws.onmessage = function (evt) {
var received_msg = evt.data; var received_msg = JSON.parse(evt.data)
console.log(evt.data) var curTime = getCurTime();
if(received_msg["code"] == "0001"){ //0001代表连接消息通信
client = received_msg["client"]
}
var text = $("#revMsg").val() var text = $("#revMsg").val()
if(text == ""){ if(text == ""){
text = text + evt.data; text = text + "[" + curTime + "] " + received_msg["msg"];
}else{ }else{
text = evt.data + "\n" + text; text = text + "\n" + "[" + curTime + "] " + received_msg["msg"];
} }
$("#revMsg").val(text) $("#revMsg").val(text)
}; };
...@@ -76,17 +83,39 @@ ...@@ -76,17 +83,39 @@
function sendMsg(){ function sendMsg(){
var msg = $("#sendMsg").val() var msg = $("#sendMsg").val()
ws.send(msg); var data = {};
data["code"] = "0002"; //0002代表普通消息通信
data["client"] = client;
data["msg"] = msg;
data = JSON.stringify(data)
ws.send(data);
}
function sendClose(){
var msg = ""
var data = {};
data["code"] = "0003"; //0002代表普通消息通信
data["client"] = client;
data["msg"] = msg;
data = JSON.stringify(data)
ws.send(data);
} }
function myclose(){ function myclose(){
ws.send("_end"); var data = {};
ws.close() data["code"] = "0000"; //0000代表关闭服务器套接字程序
console.log("执行了断开连接...") data["client"] = client;
data["msg"] = "";
data = JSON.stringify(data);
ws.send(data);
ws.close();
console.log("执行了socket服务的关闭操作...");
} }
$("#connect").click(WebSocketTest) $("#connect").click(WebSocketTest);
$("#send").click(sendMsg) $("#send").click(sendMsg);
$("#close").click(sendClose);
$("#end").click(myclose);
</script> </script>
{% endblock %} {% endblock %}
</div> </div>
......
...@@ -3,25 +3,17 @@ ...@@ -3,25 +3,17 @@
from flask import Blueprint ,Response,request from flask import Blueprint ,Response,request
from configparser import ConfigParser from configparser import ConfigParser
from lib.protocol.report.HeartBeatReport_protocol import HeartBeatReport_protocol
from lib.protocol.report.LoginReport_protocol import LoginReport_protocol from lib.protocol.report.LoginReport_protocol import LoginReport_protocol
from lib.protocol.report.GPSReport_protocol import GPSReport_protocol from lib.protocol.report.VersionReport_protocol import VersionReport_protocol
from lib.protocol.report.OBDReport_CAN_protocol import OBDReport_CAN_protocol
from lib.protocol.report.SecurityStatusReport_protocol import SecurityStatusReport_protocol
from lib.protocol.reportPlateform.Common_res import Common_res
from lib.protocol.reportPlateform.Login_res import Login_res
from lib.socket.ClientSocket import ClientSocket from lib.socket.ClientSocket import ClientSocket
import json import json
import traceback import traceback
import binascii
from lib.socket.service.ProtocolSimulaterService import ProtocolSimulaterService
M_carSimulater_process = Blueprint('M_carSimulater_process', __name__) M_carSimulater_process = Blueprint('M_carSimulater_process', __name__)
#用来保存连接的信息 connects = [] #用来保存连接的信息
connects = []
#用来保存车机线程
threads = []
########################################## ##########################################
# 【接口类型】设置socket信息 # 【接口类型】设置socket信息
...@@ -60,18 +52,25 @@ def porcessSocketSetting(): ...@@ -60,18 +52,25 @@ def porcessSocketSetting():
########################################## ##########################################
@M_carSimulater_process.route("/createConect",methods=['POST']) @M_carSimulater_process.route("/createConect",methods=['POST'])
def createConect(): def createConect():
timeout = int(request.form.get("timeout"))
data = {} data = {}
try: try:
conf_R = ConfigParser() conf_R = ConfigParser()
conf_R.read("config/protocolTools/carSimulater.conf") conf_R.read("config/protocolTools/carSimulater.conf")
if len(connects) < 1: if len(connects) < 1:
cliSocket = ClientSocket(conf_R.get("socket", "host"), conf_R.getint("socket", "port")) cliSocket = ClientSocket(conf_R.get("socket", "host"), conf_R.getint("socket", "port"))
cliSocket.setTimeOut(timeout)
cliSocket.connect() cliSocket.connect()
connect = {} connect = {}
socketName = "socket_" + str(len(connects) + 1) socketName = "socket_" + str(len(connects) + 1)
connect["name"] = socketName connect["name"] = socketName
connect["obj"] = cliSocket connect["obj"] = cliSocket
connects.append(connect) connects.append(connect)
service = ProtocolSimulaterService()
service.setSocket(cliSocket)
service.setTimeout(timeout)
service.startWebsocketService()
connects[0]["service"] = service
data["status"] = "200" data["status"] = "200"
data["message"] = "创建连接成功!" data["message"] = "创建连接成功!"
else: else:
...@@ -81,9 +80,77 @@ def createConect(): ...@@ -81,9 +80,77 @@ def createConect():
# 打印异常信息 # 打印异常信息
traceback.print_exc() traceback.print_exc()
data["status"] = "4003" data["status"] = "4003"
data["message"] = "Error: 处理失败!" data["message"] = "Error: 连接失败!"
return Response(json.dumps(data), mimetype='application/json')
##########################################
# 【接口类型】登录
##########################################
@M_carSimulater_process.route("/login",methods=['POST'])
def login():
params = request.get_data()
params = json.loads(params.decode("utf-8"))
data = {}
try:
service = connects[0]["service"]
clientSocket = connects[0]["obj"]
service.setSocket(clientSocket)
loginObj = LoginReport_protocol(params["WATER_CODE"],params["carId"],params["login"]["cpuId"], \
params["login"]["imsi"],params["login"]["ccid"],params["login"]["imei"])
loginMsg = loginObj.generateLoginMsg()
service.serviceSendMsg(loginMsg,"登录")
versionObj = VersionReport_protocol(1,params["WATER_CODE"],params["carId"],params["version"]["verInfo"], \
params["version"]["compileDate"],params["version"]["GSM"])
versionMsg = versionObj.generateVersionMsg()
service.serviceSendMsg(versionMsg,"版本")
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_carSimulater_process.route("/fire",methods=['POST'])
def fire():
durTime = int(request.form.get("durTime"))
data = {}
try:
service = connects[0]["service"]
# clientSocket = connects[0]["obj"]
# service.setSocket(clientSocket)
service.setSendDur(durTime) #设置车机多久循环发送一次消息
service.startService()
connects[0]["service"] = service
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') return Response(json.dumps(data), mimetype='application/json')
##########################################
# 【接口类型】熄火
##########################################
@M_carSimulater_process.route("/unFire",methods=['POST'])
def unFire():
data = {}
try:
connects[0]["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')
########################################## ##########################################
# 【接口类型】关闭一个连接 # 【接口类型】关闭一个连接
...@@ -94,9 +161,10 @@ def closeConect(): ...@@ -94,9 +161,10 @@ def closeConect():
try: try:
if len(connects) < 1: if len(connects) < 1:
data["status"] = "4003" data["status"] = "4003"
data["message"] = "没有关闭的连接!" data["message"] = "没有关闭的连接!"
else: else:
connects[0]["obj"].close() connects[0]["service"].stopWebsocketService()
connects[0]["service"].closeSocket()
connects.pop(0) connects.pop(0)
data["status"] = "200" data["status"] = "200"
data["message"] = "关闭连接成功!" data["message"] = "关闭连接成功!"
...@@ -104,5 +172,26 @@ def closeConect(): ...@@ -104,5 +172,26 @@ def closeConect():
# 打印异常信息 # 打印异常信息
traceback.print_exc() traceback.print_exc()
data["status"] = "4003" data["status"] = "4003"
data["message"] = "Error: 处理失败!" data["message"] = "Error: 关闭连接失败!"
return Response(json.dumps(data), mimetype='application/json')
##########################################
# 【接口类型】复位
##########################################
@M_carSimulater_process.route("/reset",methods=['POST'])
def reset():
data = {}
try:
for t in connects:
t["service"].stopWebsocketService()
t["service"].stopService()
t["service"].closeSocket()
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') return Response(json.dumps(data), mimetype='application/json')
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment