Commit 154ea00c authored by liyuanhong's avatar liyuanhong

首次提交

parents
Pipeline #187 failed with stages
.idea/*
venv/*
\ No newline at end of file
#coding: utf-8
import hashlib
import json
import threading
import time
import pymysql as pymysql
import requests
class BindUser():
def __init__(self):
self.SSL_VERIFY = True
self.mobile = 13300015000 # 将要累加的手机号 (累加方式)
self.carId = 202006115001 # 将要累加得车机 (累加方式)
self.mobileArr = ["13245670010","13245670011","13245670012"] # 将要累加的手机号 (数组方式)
self.carIdArr = ["202003060165","202003060166","202003060167"] # 将要累加得车机号 (数组方式)
self.count = 5000 # 累加次数
self.sn = 123 # 车机SN码
self.inviteCode = "123456" #绿卡邀请码
self.pad = 0 #车牌号累加起始
self.db = None
self.dbhost = "10.100.5.3"
self.dbuser = "root"
self.dbpassword = "root"
self.database = "appserver"
self.dbport = 13306
##############################################
# 获取短信验证码
##############################################
def getMsgCode(self,mobile):
url = "http://api-test.vandyo.com/user/authorize/authcode/get"
ts = int(time.time())
headers = {"Accept-Encoding": "gzip", "Content-Type": "application/json; charset=UTF-8"}
params = {}
params["reqtype"] = 1
params["ts"] = ts
params["mobile"] = mobile
cs = self.getSignature(params)
params["cs"] = cs
resObj = requests.get(url, headers=headers, params=params, verify=self.SSL_VERIFY)
print("\n请求地址:" + url)
print("-------------------------返回结果:-------------------------")
print(resObj.text)
##############################################
# 使用短信验证码登录
##############################################
def loginByMsgCode(self,mobile,msgCode):
url = "http://api-test.vandyo.com/user/authorize/authcode/login"
ts = int(time.time())
headers = {"Accept-Encoding": "gzip", "Content-Type": "application/json; charset=UTF-8"}
params = {}
params["ts"] = ts
postData = {}
postData["mobile"] = mobile
postData["verify"] = msgCode
resObj = requests.post(url, headers=headers, params=params, data=json.dumps(postData), verify=self.SSL_VERIFY)
print("\n请求地址:" + url)
print("-------------------------返回结果:-------------------------")
print(resObj.text)
resObj = json.loads(resObj.text)
uData = {}
uData["sid"] = resObj["result"]["sid"]
uData["uid"] = resObj["result"]["uid"]
return uData
##############################################
# 绑定车机
##############################################
def bindCar(self,uid,sid,din):
url = "http://api-test.vandyo.com/car/car_add"
ts = int(time.time())
headers = {"Accept-Encoding": "gzip", "Content-Type": "application/json; charset=UTF-8"}
params = {}
params["ts"] = ts
params["sid"] = sid
params["uid"] = uid
postData = {}
postData["din"] = din
postData["dsn"] = self.sn
postData["gasno"] = "95"
postData["mmile"] = ""
postData["plate"] = "渝Z" + str(10000 + self.pad)
self.pad = self.pad + 1
postData["tid"] = "129577"
cs = self.getSignature(params, json.dumps(postData))
params["cs"] = cs
params.pop("sid")
resObj = requests.post(url, headers=headers, params=params, data=json.dumps(postData), verify=self.SSL_VERIFY)
print("\n请求地址:" + url)
print("-------------------------返回结果:-------------------------")
print(resObj.text)
##############################################
# 绑定绿卡
##############################################
def bindGreenCard(self,uid,sid):
url = "http://api-test.vandyo.com/extenduser/card/activate"
ts = int(time.time())
headers = {"Accept-Encoding": "gzip", "Content-Type": "application/json; charset=UTF-8"}
params = {}
params["ts"] = ts
params["sid"] = sid
params["uid"] = uid
postData = {}
postData["area"] = "重庆市"
postData["convertCode"] = ""
postData["inviteCode"] = self.inviteCode
postData["lat"] = 29.573062
postData["lng"] = 106.59255
postData["type"] = 1
cs = self.getSignature(params, json.dumps(postData))
params["cs"] = cs
params.pop("sid")
resObj = requests.post(url, headers=headers, params=params, data=json.dumps(postData), verify=self.SSL_VERIFY)
print("\n请求地址:" + url)
print("-------------------------返回结果:-------------------------")
print(resObj.text)
#################################################
# 获取一个Md5的字符串
#################################################
def getMd5String(self,data):
m = hashlib.md5()
b = data.encode(encoding='utf-8')
m.update(b)
str_md5 = m.hexdigest()
return str_md5
#################################################
# 获取签名,传入一个map,
# (需要对传入的参数,按照key的升序排列)
#################################################
def getSignature(self,data,postData={}):
sMd5 = ""
if len(postData) == 0:
keys = sorted(data.keys())
s = ""
for key in keys:
s = s + key + "[" + str(data[key]) + "];"
sMd5 = self.getMd5String(s)
else:
data["Data"] = postData
keys = sorted(data.keys())
s = ""
for key in keys:
s = s + key + "[" + str(data[key]) + "];"
sMd5 = self.getMd5String(s)
return sMd5
#################################################
# 连接数据库
#################################################
def dbConnect(self):
self.db = pymysql.connect(host=self.dbhost, user=self.dbuser, password=self.dbpassword, database=self.database, port=self.dbport)
#################################################
# 关闭数据库
#################################################
def dbClose(self):
self.db.close()
#################################################
# 查询最新的验证码
#################################################
def getMsgCodeSql(self,mobile):
self.db = pymysql.connect(host=self.dbhost, user=self.dbuser, password=self.dbpassword, database=self.database,
port=self.dbport)
sql = 'select code from t_app_verify_mobile t where t.mobile=' + mobile + ' and t.status=1 order by t.insert_time desc'
cursor = self.db.cursor()
cursor.execute(sql)
self.db.close()
cursor.close()
res = cursor.fetchone()
code = res[0]
return code
#################################################
# 绑定车流程
#################################################
def doBindCar(self,mobile,din):
self.getMsgCode(mobile)
time.sleep(0.5)
msgCode = self.getMsgCodeSql(mobile)
loginInfo = self.loginByMsgCode(mobile,msgCode)
self.bindCar(loginInfo["uid"],loginInfo["sid"],din)
self.bindGreenCard(loginInfo["uid"],loginInfo["sid"])
#################################################
# 绑定多个车流程(累加方式)
#################################################
def doBindMultCar(self):
for i in range(0,self.count):
mobile = str(self.mobile + i)
carId = "M" + str(self.carId + i)
theThread = threading.Thread(target=self.doBindCar, args=(mobile, carId,))
theThread.start()
time.sleep(0.1)
#################################################
# 绑定多个车流程(数组方式)
#################################################
def doBindMultCarArr(self):
for i in range(0,len(self.mobileArr)):
mobile = self.mobileArr[i]
carId = "M" + str(self.carIdArr[i])
theThread = threading.Thread(target=self.doBindCar, args=(mobile, carId,))
theThread.start()
if __name__ == "__main__":
# BindUser().getMsgCode("1245670001")
# print(BindUser().loginByMsgCode("13245670001","141743"))
# BindUser().bindCar("c927f5598d984b08ba51a3facd9ce3ce","87401ea4a78144639cde8cf47ccb1da0")
# obj = BindUser()
# obj.dbConnect()
# res = obj.getMsgCodeSql("13245670001")
# print(res)
# obj.dbClose()
obj = BindUser()
# obj.dbConnect()
obj.doBindMultCar()
# obj = BindUser()
# obj.dbConnect()
# obj.doBindMultCarArr()
\ No newline at end of file
#coding: utf-8
import binascii
import json
import random
import socket
import threading
import time
import traceback
class SendObd():
def __init__(self):
self.host = "10.100.12.32"
self.port = 9008
self.timeOut = 2
self.BUF_SIZE = 1024
self.carId = 202006115001 #设置开始发送的车机号
self.totalCar = 5000 #设置将会累加的车机号
self.carIdArr = ["202003060165","202003060166"]
#获取要发送的OBD数据(M500车机)
def getOBDMsg_M500(self,carId,mileage):
timeStamp = time.time()
timeArray = time.localtime(int(timeStamp - 8 * 3600))
dateTimeM = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
timeHex = self.getUTCTime(dateTimeM)
totalMileage = self.int2hexStringByBytes(mileage,4)
# OBD_msg = "4040007000064d" + str(carId) + "001201" + timeHex + "26d7fffff0000000000505000000143c00000bb80100000fa00000000a0000000000005e60723b723b39331e100055320000001312001007d0001e0000000000000096000000280096ffff3e0001f40000003e00000000000000000000007213"
OBD_msg = "4040007000064d" + str(carId) + "001201" + timeHex + "ffffffffff000000000505000000143c00000bb801" + totalMileage + "0000000a0000000000005e60723b723b39331e100055320000001312001007d0001e0000000000000096000000280096ffff3e0001f40000003e00000000000000000000007213"
OBD_msg = OBD_msg[:-4] + self.crc16(OBD_msg[:-4])
msg = OBD_msg
return msg
############################################
# 发送一条消息
############################################
def sendMsg(self,msg):
msg = msg
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) # 在客户端开启心跳
client.settimeout(self.timeOut)
startTime = int(time.time() * 1000)
try:
client.connect((self.host, self.port))
client.send(binascii.a2b_hex(msg))
print("发送消息:" + msg)
except BaseException as e:
client.close()
print("连接超时,socket断开")
return
try:
data = client.recv(self.BUF_SIZE)
print("接收消息:" + str(data))
except BaseException as e:
traceback.print_exc()
client.close()
print('socket 接收消息超时!')
return
endTime = int(time.time() * 1000)
timeExpend = endTime - startTime
client.close()
####################################################
# 定义生成校验字段的函数(M500 校验方式)
# inputStr:需要传入一个已经转换为16进制的字符串
#####################################################
# add crc 16 check at the end of the string
def crc16(self,inputStr):
inputStrByte = bytes.fromhex(inputStr)
crc = 0xFFFF
for i in range(0, len(inputStrByte)):
for j in range(0, 8):
c15 = (crc >> 15) == 1
bit = ((inputStrByte[i] >> (7 - j)) & 1) == 1
crc <<= 1
crc &= 0xFFFF
if c15 ^ bit:
crc ^= 0x1021
crc = str(hex(crc))
crc = self.leftPad(crc[2:], 4)
# outputStr = inputStr + crc
outputStr = crc
return outputStr
# pad zero to the left of the string if not long enough
def leftPad(self,inputStr, strLen):
if (strLen > len(inputStr)):
outputStr = "0000000000000000000000000000000000000000" + inputStr
outputStr = outputStr[len(outputStr) - strLen:]
return outputStr
else:
return inputStr
# pad zero to the right of the string if not long enough
def rightPad(self,inputStr, strLen):
if (strLen > len(inputStr)):
outputStr = inputStr + "0000000000000000000000000000000000000000"
outputStr = outputStr[: strLen]
return outputStr
else:
return inputStr
#####################################################
# 将UTC时间转换为16进制,
# 例如:2020-01-02 20:30:00 (年取后面2字节)则将20,01,02,20,30,00 转换为对应的6个字节
# theTime:传入一个类似:2020-01-03 13:05:13的一个字符串
#####################################################
def getUTCTime(self,theTime):
# 获取当前时间,时间格式为:2020-01-03 13:05:13
# now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# 将2020-01-03 13:05:13时间格式转换为一个数组
# timeStr = "2020-01-03 13:05:13"
timeStr = theTime
timeArr = []
timeArr.append(timeStr[2:4])
timeArr.append(timeStr[5:7])
timeArr.append(timeStr[8:11])
timeArr.append(timeStr[11:13])
timeArr.append(timeStr[14:16])
timeArr.append(timeStr[17:19])
UTCTime = ""
for i in range(0, len(timeArr)):
UTCTime += self.int2hexString(int(timeArr[i]))
return UTCTime
#####################################################
# 数字转换为16进制字符串
#####################################################
def int2hexString(self, num):
hexStr = hex(num)[2:]
if (len(hexStr) % 2) == 1:
hexStr = "0" + hexStr
return hexStr
#####################################################
# 数字转换为16进制字符串,通过传入字节数可自动补0
# 传入数据格式所占字节数
#####################################################
def int2hexStringByBytes(self, num,bytescount=1):
hexStr = hex(num)[2:]
while len(hexStr) < (bytescount * 2):
hexStr = "0" + hexStr
return hexStr
#####################################################
# 发送两条总里程不一样的OBD数据
#####################################################
def sendTwoObdMsg(self,carId,mileage):
theMileage = mileage
msg = self.getOBDMsg_M500(carId,theMileage)
self.sendMsg(msg)
time.sleep(5)
theMileage = mileage + random.randint(2000,10000)
msg = self.getOBDMsg_M500(carId, theMileage)
self.sendMsg(msg)
#####################################################
# 使用多个车机号批量发送
#####################################################
def sendMultMsgService(self):
for i in range(0,self.totalCar):
carId = str(self.carId + i)
print(carId)
theThread = threading.Thread(target=self.sendTwoObdMsg, args=(carId,220000))
theThread.start()
time.sleep(0.01)
print(theThread.getName())
#####################################################
# 使用多个车机号批量发送(数组方式)
#####################################################
def sendMultMsgServiceArr(self):
for i in range(0,len(self.carIdArr)):
carId = str(self.carIdArr[i])
print(carId)
theThread = threading.Thread(target=self.sendTwoObdMsg, args=(carId,10000))
theThread.start()
# time.sleep(0.1)
print(theThread.getName())
if __name__ == "__main__":
obj = SendObd()
obj.sendMultMsgService()
# obj.sendMultMsgServiceArr()
\ 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