Commit 11cac106 authored by liyuanhong's avatar liyuanhong

模拟器回复平台功能完成

parent ddaf3a31
[socket]
host = 10.100.12.32
host = 10.100.5.251
port = 9008
#encoding:utf-8
import datetime
import random
import time
from lib.protocol.Base import Base
'''
定义消息协议类的基类
'''
class M300Base(Base):
def __init__(self):
self.IDENTIFY = "7e" #标识位
#######################################################
# 生成一条完整的消息
#######################################################
def generateMsg(self):
msg = ""
funId = self.getMsgHeader()
msgBody = self.getMsgBody()
checkCode = self.getCheckCode(msgHeader + msgBody)
msg = msg + self.IDENTIFY
info = msgHeader + msgBody + checkCode
info = self.replace7e7d(info)
msg = msg + info
msg = msg + self.IDENTIFY
return msg
#######################################################
# 获取消息头
#######################################################
def getMsgHeader(self):
msgID = self.int2hexStringByBytes(102,2) #消息id
subPkg = 0
msgBodyProperty = self.getMsgBodyProperty(subPkg=subPkg) #消息体属性
phoneNum = self.int2BCD(13146201118) #终端手机号
msgWaterCode = self.int2hexStringByBytes(1) #消息流水号
if subPkg != 8192:
subPkgContent = "" #消息包封装项
else:
subPkgContent = self.getMsgPackage()
data = msgID + msgBodyProperty + phoneNum + msgWaterCode + subPkgContent
return data
#获取消息头,针对图形界面,可传递参数
def getMsgHeader_GUI(self,msgID,phoneNum,msgWaterCode,encryptionType,subPkg): #消息id
msgID = msgID
subPkg = subPkg
msgBodyProperty = self.getMsgBodyProperty_GUI(msgBodyLen=int(len(self.getMsgBody()) / 2),encryptionType=encryptionType,subPkg=subPkg) #消息体属性
phoneNum = self.int2BCD(phoneNum) #终端手机号
msgWaterCode = self.int2hexStringByBytes(msgWaterCode,2) #消息流水号
if subPkg != 8192:
subPkgContent = "" #消息包封装项
else:
subPkgContent = self.getMsgPackage()
data = msgID + msgBodyProperty + phoneNum + msgWaterCode + subPkgContent
return data
#获取消息体属性
def getMsgBodyProperty(self,msgBodyLen=128,encryptionType=0,subPkg=0):
if msgBodyLen >= 512:
raise RuntimeError('消息体长度超长!')
msgBodyLen = msgBodyLen #消息体长度
encryptionType = encryptionType #加密方式
subPkg = subPkg #分包
retain = 0 #保留位
data = msgBodyLen + encryptionType + subPkg + retain
dataHex = self.int2hexStringByBytes(data,2)
return dataHex
#获取消息体属性,针对图形界面,可传递参数
def getMsgBodyProperty_GUI(self,msgBodyLen=128,encryptionType=0,subPkg=0):
if msgBodyLen >= 512:
raise RuntimeError('消息体长度超长!')
msgBodyLen = msgBodyLen #消息体长度
encryptionType = encryptionType #加密方式
subPkg = subPkg #分包
retain = 0 #保留位
data = msgBodyLen + encryptionType + subPkg + retain
dataHex = self.int2hexStringByBytes(data,2)
return dataHex
#获取消息封装项
def getMsgPackage(self):
pkgCounts = 2 #消息报包总数
pkgCountsHex = self.int2hexStringByBytes(2,2)
pkgNumsHex = ""
for i in range(0,pkgCounts):
pkgNum = i
dataHex = self.int2hexStringByBytes(pkgNum,2)
pkgNumsHex = pkgNumsHex + dataHex
msgPackage = pkgCountsHex + pkgNumsHex
return msgPackage
#######################################################
# 获取消息体
#######################################################
def getMsgBody(self):
return ""
#######################################################
# 获取校验码
#######################################################
def getCheckCode(self,data="aa"):
if len(data) % 2 == 1:
raise RuntimeError('数据段错误!')
start = data[0:2]
tmp = int(start,16)
for i in range(2,len(data),2):
tmp = tmp ^ int(data[i:i + 2],16)
dataHex = self.int2hexStringByBytes(tmp)
return dataHex
#######################################################
# 替换消息中的7e7d字符
#######################################################
def replace7e7d(self,data):
# data = data.replace("7d","7d01")
# data = data.replace("7e","7d02")
tmpR = data
tmp = tmpR[0:2]
tmpA = tmpR[0:2]
tmpR = tmpR[2:]
data = ""
while tmpA != "":
if tmp == "7d":
tmp = "7d01"
elif tmp == "7e":
tmp = "7d02"
data = data + tmp
tmp = tmpR[0:2]
tmpA = tmpR[0:2]
tmpR = tmpR[2:]
return data
#######################################################
# 字符串转16进制
#######################################################
def str2Hex(self,data):
dataHex = ""
tem = ""
for i in data:
tem = ord(i)
dataHex += hex(tem)[2:]
return dataHex
#######################################################
# 16进制转字符串
#######################################################
def hex2Str(self,data):
theStr = ""
while data != "":
tmp = data[:2]
data = data[2:]
theStr = theStr + chr(int(tmp,16))
return theStr
#####################################################
# 将字符串转换为对应的ascii值数组
#####################################################
def str2Ascsii(self,data):
asciiArr = []
for i in range(0, len(data)):
asciiValue = ord(data[i])
asciiArr.append(asciiValue)
return asciiArr
####################################################
# 将整数转换为有符号的整数
#####################################################
def num2signedNum(self,num):
return num & 0xff
#####################################################
# 数字转换为16进制字符串,通过传入字节数可自动补0
# 传入数据格式所占字节数
#####################################################
def int2hexStringByBytes(self, num,bytescount=1):
hexStr = hex(num)[2:]
while len(hexStr) < (bytescount * 2):
hexStr = "0" + hexStr
return hexStr
####################################################
# 将10进制转换位8421码
#####################################################
def int2BCD(self,data,bytescount=6):
data = str(data)
while len(data) < bytescount * 2:
data = "0" + data
return data
#######################################################
# 获取UTC时间转换位BCD格式
#######################################################
def getBCDTime(self,data="2020-02-04 18:57:04"):
now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
data = data
data = data.replace("-","")
data = data.replace(" ","")
data = data.replace(":","")
data = data[2:]
data = self.int2BCD(int(data))
return data
#######################################################
# 字符串转换为GBK的16进制
#######################################################
def GBKString2Hex(self,data):
data = str(data.encode("gbk"))
dataHex = self.str2Hex(data[2:len(data) - 1])
return dataHex
#######################################################
# 16进制转换为GBK字符串
#######################################################
def hex2GBKString(self,dataHex):
dataStr = self.hex2Str(dataHex)
data = bytes(map(ord,str(dataStr)))
data = data.decode("gbk")
return data
#######################################################
# 获取一个随机数,也可以指定获取数组中的随机字符串
#######################################################
def getRandomNum(self,s=1,e=1,intArr=[],mult=0):
if intArr == []:
data = random.randint(s, e)
else:
if mult == 0:
if type(intArr[0]) == int:
data = int(random.choice(intArr))
elif type(intArr[0]) == str:
data = random.choice(intArr)
else:
if type(intArr[0]) == int:
if len(intArr) < mult:
raise RuntimeError('个数超过数组长度!')
temp = []
data = 0
for i in range(0,mult):
num = int(random.choice(intArr))
if num in temp:
# num = int(random.choice(intArr))
num = 0
temp.append(num)
data = data + num
elif type(intArr[0]) == str:
if len(intArr) < mult:
raise RuntimeError('个数超过数组长度!')
temp = []
data = ""
for i in range(0,mult):
num = random.choice(intArr)
if num in temp:
# num = int(random.choice(intArr))
num = "0"
temp.append(num)
data = data + num
return data
#######################################################
# 获取一个随机字符串
#######################################################
def getRandomStr(self,counts,strs=""):
if strs == "":
data = random.sample("0123456789abcdefghijkmlnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-", counts)
else:
data = []
for s in range(0,counts):
data.append(random.choice(strs))
temp = ""
for ch in data:
temp = temp +ch
return temp
#######################################################
# 获取随机时间
# type:0、获取年月日时分秒 1、获取年月日 2、获取时分秒
#######################################################
def getRandomDate(self,s=631123200,e=1577808000,type=0):
timeStamp = random.randint(s, e)
timeArray = time.localtime(timeStamp)
if type == 0:
theTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
elif type == 1:
theTime = time.strftime("%Y-%m-%d", timeArray)
elif type == 2:
theTime = time.strftime("%H:%M:%S", timeArray)
return theTime
if __name__ == "__main__":
pass
#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):
self.cpuId = cpuId #设置默认cupId值
self.imsi = imsi #设置默认imsi值
self.ccid = ccid #设置默认ccid值
self.imei = imei #设置默认imei值
......
......@@ -194,8 +194,8 @@ if __name__ == "__main__":
# print(ProtocolBase().str2Hex("a"))
# print(ProtocolBase().int2hexStringByBytes(1,6))
# 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("14020a07122b"))
print(ProtocolBase().crc16("4040007000064d20191201000200120114030503202d26d7fffff0000000000505000000143c00000bb80100000fa00000000a0000000000005e60723b723b39331e100055320000001312001007d0001e0000000000000096000000280096ffff3e0001f40000003e0000000000000000000000"))
print(ProtocolBase().myCrc16("4040007000064d20191201000200120114030503202d26d7fffff0000000000505000000143c00000bb80100000fa00000000a0000000000005e60723b723b39331e100055320000001312001007d0001e0000000000000096000000280096ffff3e0001f40000003e0000000000000000000000"))
# print(ProtocolBase().crc16("4040007000064d20191201000200120114030503202d26d7fffff0000000000505000000143c00000bb80100000fa00000000a0000000000005e60723b723b39331e100055320000001312001007d0001e0000000000000096000000280096ffff3e0001f40000003e0000000000000000000000"))
# print(ProtocolBase().myCrc16("4040007000064d20191201000200120114030503202d26d7fffff0000000000505000000143c00000bb80100000fa00000000a0000000000005e60723b723b39331e100055320000001312001007d0001e0000000000000096000000280096ffff3e0001f40000003e0000000000000000000000"))
......@@ -26,7 +26,7 @@ class SleepReport_protocol(ProtocolBase):
HEADER = "4040" #消息头
WATER_CODE = self.getWaterCode(self.WATER_CODE) #消息流水号
DEV_ID = self.devid2hexString(self.DEV_ID) #设备id
FUN_ID = "0005" # 功能id
FUN_ID = "00FF" # 功能id
data = "" #数据段
for i in range(0,self.msgCount):
data += self.generateSleepPkg(self.generateSleepData())
......
......@@ -27,7 +27,7 @@ class VersionReport_protocol(ProtocolBase):
HEADER = "4040" #消息头
WATER_CODE = self.getWaterCode(self.WATER_CODE) #消息流水号
DEV_ID = self.devid2hexString(self.DEV_ID) #设备id
FUN_ID = "00FF" # 功能id
FUN_ID = "0005" # 功能id
data = "" #数据段
for i in range(0,self.msgCount):
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
import binascii
import time
from lib.protocol.Base import Base
......@@ -84,7 +85,30 @@ class ResponseBase(Base):
else:
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
import binascii
import socket
from lib.protocol.report.CommonReport_protocol import CommonReport_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
......@@ -25,15 +27,15 @@ port = 9008
# msg = GPSReport_protocol().generateGpsMsg() #GPS消息数据
# msg = OBDReport_protocol().generateOBDReportMsg() #OBD终端上报数据
# msg = OBDReport_CAN_protocol().generateOBDReportCANMsg() #OBD终端上报CAN数据
# msg = HeartBeatReport_protocol().generateHeartBeatMsg() #终端上报心跳协议
msg = HeartBeatReport_protocol().generateHeartBeatMsg() #终端上报心跳协议
# msg = LoginReport_protocol().generateLoginMsg() #终端上报登录协议
# msg = SecurityStatusReport_protocol().generateSecurityStatusMsg() #终端上报安防状态协议
# msg = BaseStationReport_protocol().generateBaseStationMsg() #终端上报基站定位协议
# msg = TroubleReport_protocol().generateTroubleMsg() #终端上报故障码数据包
# msg = EventReport_protocol().generateEventMsg()
# msg = VersionReport_protocol().generateVersionMsg() #终端上报版本信息数据包
msg = SleepReport_protocol().generateSleepMsg() #终端休眠数据包
# msg = SleepReport_protocol().generateSleepMsg() #终端休眠数据包
msg = CommonReport_protocol().generateCommonMsg() #通用应答消息
print(msg)
BUF_SIZE = 1024
......@@ -41,6 +43,7 @@ client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) # 在客户端开启心跳
client.connect((host, port))
client.send(binascii.a2b_hex(msg))
# client.send(bytes.fromhex(msg))
data = client.recv(BUF_SIZE)
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 @@
<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="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 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>
......
......@@ -38,38 +38,143 @@
{% 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%;padding-bottom:10px;border-bottom: 1px solid #eee;">
<label>车机Id:</label><input id="carId" type="text" class="form-control" value="M121501010001">
<span><label>车机Id:</label><input id="carId" type="text" class="form-control" value="M121501010001"></span>
<span><label>消息流水号:</label><input id="WATER_CODE" style="width:60px;" type="text" class="form-control" value="1"></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>
</div>
<div style="width:100%;padding-bottom:10px;border-bottom: 1px solid #eee;">
<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;">
<h5><b>登录报文数据:</b></h5>
<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 style="word-break:break-all;font-size:12px;">SIM卡IMSI号:</label><input id="imsi" type="text" class="form-control" value="IMSI13145678902"></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 style="word-break:break-all;font-size:10px;">GSM模块IMEI码:</label><input id="imei" type="text" class="form-control" value="IMEI12233445566"></li>
</ul>
<h5><b>版本报文数据:</b></h5>
<ul class="protocol_content" style="padding:0px;">
<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>
<li><label>编译日期:</label><input id="compileDate" type="text" class="form-control" value="2020-03-23"></li>
<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>
</ul>
</div>
</div>
<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="login_B" type="button" class="btn btn-primary">2、车机登录</button>
<button id="fire_B" type="button" class="btn btn-primary">3、点火</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="run_B" type="button" class="btn btn-primary">4、行驶</button>
<button id="stopRun_B" type="button" class="btn btn-primary">5、停止行驶</button>
<button id="unFire_B" type="button" class="btn btn-primary">6、熄火</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="unConnectAll_B" type="button" class="btn btn-danger">8、复位</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:10px;border-bottom: 1px solid #eee;">
<div style="width:100%;padding-bottom:60px;border-bottom: 1px solid #eee;">
<h3>日志:</h3>
<textarea id="showFeedback" style="width:100%;padding:5px;" rows="10"></textarea>
<textarea id="showFeedback" style="width:100%;padding:5px;padding-bottom:60px;" rows="6"></textarea>
</div>
</div>
<script>
//连接
function connect(){
var carId = $("#carId").val()
var WATER_CODE = $("#WATER_CODE").val()
var durTime = $("#durTime").val()
var timeout = $("#timeout").val()
data = {};
data["carId"] = carId
data["WATER_CODE"] = WATER_CODE
data["durTime"] = durTime
data["timeout"] = timeout
url = "/protocolTools/M_carSimulater_process/createConect";
send(data,url);
//setTimeout(function(){
// WebSocketTest()
//},1000); //1秒之后启动websocket连接
WebSocketTest()
$("#curStatus").val("连网")
}
//登录
function login(){
var data = {};
var carId = $("#carId").val()
var WATER_CODE = $("#WATER_CODE").val()
var durTime = $("#durTime").val()
//登录数据
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"] = {}
var verInfo = $("#verInfo").val()
var compileDate = $("#compileDate").val()
var GSM = $("#GSM").val()
data["version"]["verInfo"] = verInfo
data["version"]["compileDate"] = compileDate
$("#curStatus").val("登录")
data["version"]["GSM"] = GSM
data["carId"] = carId
data["WATER_CODE"] = WATER_CODE
data["durTime"] = durTime
url = "/protocolTools/M_carSimulater_process/login";
sendjson(data,url);
}
//点火
function fire(){
var carId = $("#carId").val()
var WATER_CODE = $("#WATER_CODE").val()
var durTime = $("#durTime").val()
var data = {};
data["carId"] = carId
data["WATER_CODE"] = WATER_CODE
data["durTime"] = durTime
url = "/protocolTools/M_carSimulater_process/fire";
send(data,url);
$("#curStatus").val("点火")
}
//熄火
function unFire(){
var data = {};
url = "/protocolTools/M_carSimulater_process/unFire";
send(data,url);
$("#curStatus").val("熄火")
}
//断开连接
function stopConnect(){
data = {};
var data = {};
url = "/protocolTools/M_carSimulater_process/closeConect";
send(data,url);
endService()
$("#curStatus").val("断网")
}
//复位
function reset(){
var data = {};
url = "/protocolTools/M_carSimulater_process/reset";
send(data,url);
$("#showFeedback").val("")
endService()
$("#curStatus").val("断网")
}
//清空日志
function clearlog(){
$("#showFeedback").val("")
}
//非json方式发送数据
function send(data,url){
var host = window.location.host;
$.ajax({
......@@ -81,13 +186,117 @@ function send(data,url){
success:function(data){
if(data.status == 200){
//window.location.reload()
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);
}
}
});
}
//json方式发送数据
function sendjson(data,url){
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){
//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);
}
}
});
}
///////////////////////////////// websocket 代码开始 /////////////////////////////////
client = "0"
ws = null;
i = 1;
(function(){
ws = null;
i = 1;
})()
function WebSocketTest(){
if ("WebSocket" in window){
console.log("您的浏览器支持 WebSocket!");
ws = new WebSocket("ws://127.0.0.1:5005");
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 %}
</div>
......
......@@ -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>
<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>
</div>
<H3 style="border-bottom: 1px solid #eee;">输入消息内容:</H3>
......
......@@ -33,7 +33,10 @@
<!-- <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="">-->
<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>
</div>
</div>
......@@ -41,6 +44,7 @@
<script>
client = "0"
ws = null;
i = 1;
(function(){
......@@ -56,13 +60,16 @@
console.log("socket 已经连接上!")
};
ws.onmessage = function (evt) {
var received_msg = evt.data;
console.log(evt.data)
var received_msg = JSON.parse(evt.data)
var curTime = getCurTime();
if(received_msg["code"] == "0001"){ //0001代表连接消息通信
client = received_msg["client"]
}
var text = $("#revMsg").val()
if(text == ""){
text = text + evt.data;
text = text + "[" + curTime + "] " + received_msg["msg"];
}else{
text = evt.data + "\n" + text;
text = text + "\n" + "[" + curTime + "] " + received_msg["msg"];
}
$("#revMsg").val(text)
};
......@@ -76,17 +83,39 @@
function sendMsg(){
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(){
ws.send("_end");
ws.close()
console.log("执行了断开连接...")
var data = {};
data["code"] = "0000"; //0000代表关闭服务器套接字程序
data["client"] = client;
data["msg"] = "";
data = JSON.stringify(data);
ws.send(data);
ws.close();
console.log("执行了socket服务的关闭操作...");
}
$("#connect").click(WebSocketTest)
$("#send").click(sendMsg)
$("#connect").click(WebSocketTest);
$("#send").click(sendMsg);
$("#close").click(sendClose);
$("#end").click(myclose);
</script>
{% endblock %}
</div>
......
......@@ -3,25 +3,17 @@
from flask import Blueprint ,Response,request
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.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.reportPlateform.Common_res import Common_res
from lib.protocol.reportPlateform.Login_res import Login_res
from lib.protocol.report.VersionReport_protocol import VersionReport_protocol
from lib.socket.ClientSocket import ClientSocket
import json
import traceback
import binascii
from lib.socket.service.ProtocolSimulaterService import ProtocolSimulaterService
M_carSimulater_process = Blueprint('M_carSimulater_process', __name__)
#用来保存连接的信息
connects = []
#用来保存车机线程
threads = []
connects = [] #用来保存连接的信息
##########################################
# 【接口类型】设置socket信息
......@@ -60,18 +52,25 @@ def porcessSocketSetting():
##########################################
@M_carSimulater_process.route("/createConect",methods=['POST'])
def createConect():
timeout = int(request.form.get("timeout"))
data = {}
try:
conf_R = ConfigParser()
conf_R.read("config/protocolTools/carSimulater.conf")
if len(connects) < 1:
cliSocket = ClientSocket(conf_R.get("socket", "host"), conf_R.getint("socket", "port"))
cliSocket.setTimeOut(timeout)
cliSocket.connect()
connect = {}
socketName = "socket_" + str(len(connects) + 1)
connect["name"] = socketName
connect["obj"] = cliSocket
connects.append(connect)
service = ProtocolSimulaterService()
service.setSocket(cliSocket)
service.setTimeout(timeout)
service.startWebsocketService()
connects[0]["service"] = service
data["status"] = "200"
data["message"] = "创建连接成功!"
else:
......@@ -81,9 +80,77 @@ def createConect():
# 打印异常信息
traceback.print_exc()
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')
##########################################
# 【接口类型】熄火
##########################################
@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():
try:
if len(connects) < 1:
data["status"] = "4003"
data["message"] = "没有关闭的连接!"
data["message"] = "没有关闭的连接!"
else:
connects[0]["obj"].close()
connects[0]["service"].stopWebsocketService()
connects[0]["service"].closeSocket()
connects.pop(0)
data["status"] = "200"
data["message"] = "关闭连接成功!"
......@@ -104,5 +172,26 @@ def closeConect():
# 打印异常信息
traceback.print_exc()
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')
\ 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