834 lines
43 KiB
Python
834 lines
43 KiB
Python
# -*- coding:utf-8 -*-
|
||
import datetime
|
||
import hashlib
|
||
import json
|
||
import os
|
||
import random
|
||
import threading
|
||
import time
|
||
import traceback
|
||
|
||
import redis
|
||
import config
|
||
import send_sms
|
||
from mysql_obj import mysql_obj
|
||
from shapely.geometry import Point
|
||
from shapely.geometry.polygon import Polygon
|
||
import asyncio
|
||
import cart_distance
|
||
|
||
|
||
class RedisSub():
|
||
redis_obj = None
|
||
mqtt_obj = None
|
||
is_debug = False
|
||
version = None
|
||
|
||
# 数据写入此队列,将数据推送到mqtt的状态
|
||
redis_name_mqtt_pub_status = "console:cxaibc:mqtt:pub:status:"
|
||
|
||
"""
|
||
1.gps超出门店范围
|
||
2.gps超出安全范围
|
||
3.硬件链路异常
|
||
4.低电量告警
|
||
5.倾倒告警
|
||
"""
|
||
# 1.gps超出
|
||
redis_name_warn_status = "api:cxaibc:mqtt:warn_status:"
|
||
|
||
"""
|
||
连接redis
|
||
"""
|
||
def redis_connect(self):
|
||
try:
|
||
print('链接redis')
|
||
self.redis_obj = redis.Redis(host=config.redis_server, port=config.redis_port, db=config.redis_database, decode_responses=True)
|
||
self.redis_obj.ping()
|
||
except redis.ConnectionError as e:
|
||
if os.path.exists('./redis_error') is False:
|
||
os.mkdir('./redis_error')
|
||
path_name = './redis_error/{}'.format(datetime.date.today().strftime('%Y_%m_%d'))
|
||
if os.path.exists(path_name) is False:
|
||
os.mkdir(path_name)
|
||
file_obj = open('{}/redis_error.txt'.format(path_name), 'a+')
|
||
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), file=file_obj)
|
||
traceback.print_exc(file=file_obj)
|
||
file_obj.close()
|
||
print('重新链接redis')
|
||
time.sleep(1)
|
||
return self.redis_connect()
|
||
pass
|
||
|
||
def run(self):
|
||
self.version = time.time()
|
||
while True:
|
||
try:
|
||
self.is_debug = config.is_debug
|
||
self.redis_connect()
|
||
while True:
|
||
data = self.redis_obj.rpop(config.redis_name_mqtt_sub_list)
|
||
if data is None:
|
||
time.sleep(1)
|
||
continue
|
||
self.printf(data)
|
||
res_data = json.loads(data)
|
||
status = 0
|
||
if res_data['data']['status'] is True:
|
||
status = 1
|
||
with mysql_obj() as db:
|
||
sql = """
|
||
INSERT INTO `cx_qc_data` ( `union`, `data`, `created_at`, `data_time`, `type`, `status`) VALUES ( '{}', '{}', {}, {}, '{}', {});
|
||
""".format(res_data['id'], res_data['data']['data'], int(time.time()), int(time.time()), res_data['type'], status)
|
||
db.cursor.execute(sql)
|
||
db.conn.commit()
|
||
if res_data['type'] == 'GPS': # gps范围
|
||
json_de = json.loads(res_data['data']['data'])
|
||
self.analysisGPS(res_data['id'], json_de['LON'], json_de['LAT'])
|
||
pass
|
||
if res_data['type'] == 'Warn': # warn告警
|
||
self.analysisWarn(res_data)
|
||
pass
|
||
if res_data['type'] == 'Detail': # 常规信息
|
||
self.analysisDetail(res_data)
|
||
pass
|
||
if res_data['type'] == 'sendAudio': # 常规信息
|
||
self.analysisSendAudio(res_data)
|
||
pass
|
||
time.sleep(0.5)
|
||
pass
|
||
time.sleep(1)
|
||
except BaseException as e:
|
||
if os.path.exists('./redis_error') is False:
|
||
os.mkdir('./redis_error')
|
||
path_name = './redis_error/{}'.format(datetime.date.today().strftime('%Y_%m_%d'))
|
||
if os.path.exists(path_name) is False:
|
||
os.mkdir(path_name)
|
||
file_obj = open('{}/redis_error.txt'.format(path_name), 'a+')
|
||
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), file=file_obj)
|
||
traceback.print_exc(file=file_obj)
|
||
file_obj.close()
|
||
self.printf(e)
|
||
self.printf(e.__traceback__.tb_frame.f_globals["__file__"]) # 发生异常所在的文件
|
||
self.printf(e.__traceback__.tb_lineno)
|
||
time.sleep(1)
|
||
pass
|
||
pass
|
||
|
||
"""
|
||
常规信息 - 计算每辆车的时长
|
||
"""
|
||
def analysisDetail(self, res_data):
|
||
try:
|
||
json_de = json.loads(res_data['data']['data'])
|
||
redis_name = "api:cxaibc:sendOpen:{}".format(res_data['id'])
|
||
get = self.redis_obj.get(redis_name)
|
||
if get is None or get == 0:
|
||
self.printf("车辆未开启,不计算时长")
|
||
return False
|
||
if "ELEC_PERCENT" not in json_de.keys():
|
||
return False
|
||
redis_name = "api:cxaibc:ddl_number:send" # 车辆剩余电量推送短信
|
||
get = self.redis_obj.get(redis_name)
|
||
if get is not None:
|
||
if int(get) > int(json_de['ELEC_PERCENT']):
|
||
# 发送短信
|
||
self.sendDdlSms(res_data['id'])
|
||
pass
|
||
|
||
# 计算可用时长
|
||
avg = self.redis_obj.get("api:cxaibc:analysisDetail:avg:{}".format(res_data['id']))
|
||
if avg is None or avg == 0:
|
||
avg = self.redis_obj.get("api:cxaibc:analysisDetail:avg:all")
|
||
if avg is None or avg == 0:
|
||
avg = 1
|
||
pass
|
||
self.redis_obj.hset("api:cxaibc:qc_service_time:hash", res_data['id'], int(json_de['ELEC_PERCENT'])/avg)
|
||
|
||
# 存储数据
|
||
if self.redis_obj.setnx("api:cxaibc:analysisDetail:setnx:{}".format(res_data['id']), 1) == 0:
|
||
if self.redis_obj.ttl("api:cxaibc:analysisDetail:setnx:{}".format(res_data['id'])) == -1:
|
||
self.redis_obj.expire("api:cxaibc:analysisDetail:setnx:{}".format(res_data['id']), 60*60)
|
||
return False
|
||
self.redis_obj.expire("api:cxaibc:analysisDetail:setnx:{}".format(res_data['id']), 60*60)
|
||
get_up_data = self.redis_obj.get("api:cxaibc:analysisDetail:up_data:{}".format(res_data['id']))
|
||
self.redis_obj.setex("api:cxaibc:analysisDetail:up_data:{}".format(res_data['id']), 60 * 80,
|
||
json_de['ELEC_PERCENT'])
|
||
|
||
if get_up_data is None or get_up_data is False:
|
||
self.printf("开启第一个小时,只做存储操作")
|
||
return False
|
||
if int(get_up_data) < int(json_de['ELEC_PERCENT']):
|
||
self.printf("正在充电,不进行计算")
|
||
return False
|
||
# 1小时的耗电量
|
||
res_ttl = int(json_de['ELEC_PERCENT']) - int(get_up_data)
|
||
if res_ttl == 0:
|
||
self.printf("电量没有发生变化")
|
||
return False
|
||
# 存储表
|
||
self.redis_obj.lpush("api:cxaibc:analysisDetail:lpush:{}".format(res_data['id']), json_de['ELEC_PERCENT'])
|
||
len_max = 50
|
||
len_data = self.redis_obj.llen("api:cxaibc:analysisDetail:lpush:{}".format(res_data['id']))
|
||
if len_data > len_max:
|
||
for v in range(len_data-len_max):
|
||
self.redis_obj.rpop("api:cxaibc:analysisDetail:lpush:{}".format(res_data['id']))
|
||
pass
|
||
pass
|
||
# 计算当前球车数据
|
||
data = self.redis_obj.lrange("api:cxaibc:analysisDetail:lpush:{}".format(res_data['id']), 0, 999)
|
||
len_data = len(data)
|
||
all_data = sum([int(v) for v in data])
|
||
avg = all_data/len_data
|
||
self.redis_obj.set("api:cxaibc:analysisDetail:avg:{}".format(res_data['id']), avg)
|
||
|
||
# 存储表
|
||
self.redis_obj.lpush("api:cxaibc:analysisDetail:lpush:all", json_de['ELEC_PERCENT'])
|
||
len_max = 500
|
||
len_data = self.redis_obj.llen("api:cxaibc:analysisDetail:lpush:all")
|
||
if len_data > len_max:
|
||
for v in range(len_data-len_max):
|
||
self.redis_obj.rpop("api:cxaibc:analysisDetail:lpush:all")
|
||
pass
|
||
pass
|
||
# 计算当前球车数据
|
||
data = self.redis_obj.lrange("api:cxaibc:analysisDetail:lpush:all", 0, 999)
|
||
len_data = len(data)
|
||
all_data = sum([int(v) for v in data])
|
||
avg = all_data/len_data
|
||
self.redis_obj.set("api:cxaibc:analysisDetail:avg:all", avg)
|
||
except BaseException as e:
|
||
if os.path.exists('./redis_error') is False:
|
||
os.mkdir('./redis_error')
|
||
path_name = './redis_error/{}'.format(datetime.date.today().strftime('%Y_%m_%d'))
|
||
if os.path.exists(path_name) is False:
|
||
os.mkdir(path_name)
|
||
file_obj = open('{}/redis_error.txt'.format(path_name), 'a+')
|
||
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), file=file_obj)
|
||
traceback.print_exc(file=file_obj)
|
||
file_obj.close()
|
||
self.printf(e)
|
||
self.printf(e.__traceback__.tb_frame.f_globals["__file__"]) # 发生异常所在的文件
|
||
self.printf(e.__traceback__.tb_lineno)
|
||
pass
|
||
|
||
"""
|
||
告警信息
|
||
"""
|
||
def analysisWarn(self, res_data):
|
||
try:
|
||
json_de = json.loads(res_data['data']['data'])
|
||
get_data = self.redis_obj.get("{}{}".format(self.redis_name_warn_status, res_data['id']))
|
||
if get_data is None or get_data == '':
|
||
get_data = {}
|
||
else:
|
||
get_data = json.loads(get_data)
|
||
|
||
# 链路异常警告
|
||
if 'WARN_HARDWARE' not in get_data.keys() and 'WARN_HARDWARE' in json_de.keys():
|
||
self.sendOtherSms(res_data['id'], "发出链路异常告警")
|
||
# if str(json_de['WARN_HARDWARE']) == '0':
|
||
# get_data['WARN_HARDWARE'] = 0
|
||
# else:
|
||
# get_data['WARN_HARDWARE'] = int(time.time())
|
||
# self.sendOtherSms(res_data['id'], "发出链路异常告警")
|
||
pass
|
||
else:
|
||
if get_data['WARN_HARDWARE'] == 0 and 'WARN_HARDWARE' in json_de.keys():
|
||
self.sendOtherSms(res_data['id'], "发出链路异常告警")
|
||
# if str(json_de['WARN_HARDWARE']) == '0':
|
||
# get_data['WARN_HARDWARE'] = 0
|
||
# else:
|
||
# get_data['WARN_HARDWARE'] = int(time.time())
|
||
# self.sendOtherSms(res_data['id'], "发出链路异常告警")
|
||
if 'WARN_HARDWARE' in json_de.keys():
|
||
if str(json_de['WARN_HARDWARE']) == '0':
|
||
get_data['WARN_HARDWARE'] = 0
|
||
pass
|
||
pass
|
||
|
||
# 低电量警告
|
||
# if 'WARN_LOW_POWER' not in get_data.keys() and 'WARN_LOW_POWER' in json_de.keys():
|
||
# if str(json_de['WARN_LOW_POWER']) == '0':
|
||
# get_data['WARN_LOW_POWER'] = 0
|
||
# else:
|
||
# get_data['WARN_LOW_POWER'] = int(time.time())
|
||
# self.sendDdlSms(res_data['id'])
|
||
# pass
|
||
# else:
|
||
# if get_data['WARN_LOW_POWER'] == 0 and 'WARN_LOW_POWER' in json_de.keys():
|
||
# if str(json_de['WARN_LOW_POWER']) == '0':
|
||
# get_data['WARN_LOW_POWER'] = 0
|
||
# else:
|
||
# get_data['WARN_LOW_POWER'] = int(time.time())
|
||
# self.sendDdlSms(res_data['id'])
|
||
# if 'WARN_LOW_POWER' in json_de.keys():
|
||
# if str(json_de['WARN_LOW_POWER']) == '0':
|
||
# get_data['WARN_LOW_POWER'] = 0
|
||
# pass
|
||
# pass
|
||
|
||
# 倾倒告警
|
||
if 'WARN_FALLDOWN' not in get_data.keys() and 'WARN_FALLDOWN' in json_de.keys():
|
||
self.sendOtherSms(res_data['id'], "发出倾倒告警")
|
||
# if str(json_de['WARN_FALLDOWN']) == '0':
|
||
# get_data['WARN_FALLDOWN'] = 0
|
||
# else:
|
||
# get_data['WARN_FALLDOWN'] = int(time.time())
|
||
# self.sendOtherSms(res_data['id'], "发出倾倒告警")
|
||
# pass
|
||
else:
|
||
if get_data['WARN_FALLDOWN'] == 0 and 'WARN_FALLDOWN' in json_de.keys():
|
||
self.sendOtherSms(res_data['id'], "发出倾倒告警")
|
||
# if str(json_de['WARN_FALLDOWN']) == '0':
|
||
# get_data['WARN_FALLDOWN'] = 0
|
||
# else:
|
||
# get_data['WARN_FALLDOWN'] = int(time.time())
|
||
# self.sendOtherSms(res_data['id'], "发出倾倒告警")
|
||
if 'WARN_FALLDOWN' in json_de.keys():
|
||
if str(json_de['WARN_FALLDOWN']) == '0':
|
||
get_data['WARN_FALLDOWN'] = 0
|
||
pass
|
||
pass
|
||
|
||
self.redis_obj.set("{}{}".format(self.redis_name_warn_status, res_data['id']), json.dumps(get_data))
|
||
except BaseException as e:
|
||
if os.path.exists('./redis_error') is False:
|
||
os.mkdir('./redis_error')
|
||
path_name = './redis_error/{}'.format(datetime.date.today().strftime('%Y_%m_%d'))
|
||
if os.path.exists(path_name) is False:
|
||
os.mkdir(path_name)
|
||
file_obj = open('{}/redis_error.txt'.format(path_name), 'a+')
|
||
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), file=file_obj)
|
||
traceback.print_exc(file=file_obj)
|
||
file_obj.close()
|
||
self.printf(e)
|
||
self.printf(e.__traceback__.tb_frame.f_globals["__file__"]) # 发生异常所在的文件
|
||
self.printf(e.__traceback__.tb_lineno)
|
||
pass
|
||
pass
|
||
|
||
# 当前位置是否在门店范围内
|
||
def analysisGPS(self, number, lon, lat):
|
||
try:
|
||
print('执行经纬度计算')
|
||
# 协程函数执行结束时会抛出一个StopIteration 异常,标志着协程函数执行结束,返回值在value中
|
||
pass
|
||
if lon == 0 and lat == 0:
|
||
self.printf("经纬度为0,0 不进行判断")
|
||
return False
|
||
try:
|
||
t = threading.Thread(target=cart_distance.CartDistance(number, self.version).run)
|
||
t.start()
|
||
except threading.ThreadError as e:
|
||
print(e)
|
||
temp_data = None
|
||
with mysql_obj() as db:
|
||
sql = """
|
||
select s.* from cx_ball_cart as c inner join cx_store as s on c.store_id = s.id where c.ball_number = '{}' and c.is_delete = 0 and s.is_delete = 0
|
||
""".format(number)
|
||
db.cursor.execute(sql)
|
||
res = db.cursor.fetchall()
|
||
if len(res) != 0:
|
||
temp_data = res[0]
|
||
if temp_data is None:
|
||
return False
|
||
if 'area' not in temp_data.keys():
|
||
return False
|
||
if temp_data['area'] is None or temp_data['area'] == '':
|
||
return False
|
||
get_data = self.redis_obj.get("{}{}".format(self.redis_name_warn_status, number))
|
||
if get_data is None or get_data == '':
|
||
get_data = {}
|
||
else:
|
||
get_data = json.loads(get_data)
|
||
json_de = json.loads(temp_data['area'])
|
||
point = Point(lon, lat)
|
||
if 'call' in json_de.keys():
|
||
polygon_data = []
|
||
for v in json_de['call']['paths']:
|
||
polygon_data.append([v['lng'], v['lat']])
|
||
polygon = Polygon(polygon_data)
|
||
if polygon.contains(point) is False:
|
||
self.printf('不在安全范围内')
|
||
self.sendOtherSms(number, "超出安全范围")
|
||
# 不在安全范围内
|
||
# if 'GPS_CALL' not in get_data.keys():
|
||
# get_data['GPS_CALL'] = int(time.time())
|
||
# self.sendOtherSms(number, "超出安全范围")
|
||
# else:
|
||
# if get_data['GPS_CALL'] == 0:
|
||
# get_data['GPS_CALL'] = int(time.time())
|
||
# self.sendOtherSms(number, "超出安全范围")
|
||
# pass
|
||
# pass
|
||
else:
|
||
if 'store' in json_de.keys():
|
||
polygon_data = []
|
||
for v in json_de['store']['paths']:
|
||
polygon_data.append([v['lng'], v['lat']])
|
||
polygon = Polygon(polygon_data)
|
||
if polygon.contains(point) is False:
|
||
self.printf('不在门店范围内')
|
||
self.sendOtherSms(number, "超出门店范围")
|
||
# 不在门店范围内
|
||
# if 'GPS_STORE' not in get_data.keys():
|
||
# get_data['GPS_STORE'] = int(time.time())
|
||
# self.sendOtherSms(number, "超出门店范围")
|
||
# else:
|
||
# if get_data['GPS_STORE'] == 0:
|
||
# get_data['GPS_STORE'] = int(time.time())
|
||
# self.sendOtherSms(number, "超出门店范围")
|
||
# pass
|
||
# pass
|
||
else:
|
||
get_data['GPS_STORE'] = 0
|
||
get_data['GPS_CALL'] = 0
|
||
else:
|
||
get_data['GPS_CALL'] = 0
|
||
|
||
pass
|
||
elif 'store' in json_de.keys():
|
||
polygon_data = []
|
||
for v in json_de['store']['paths']:
|
||
polygon_data.append([v['lng'], v['lat']])
|
||
polygon = Polygon(polygon_data)
|
||
if polygon.contains(point) is False:
|
||
self.printf('不在门店范围内')
|
||
self.sendOtherSms(number, "超出门店范围")
|
||
# 不在门店范围内
|
||
# if 'GPS_STORE' not in get_data.keys():
|
||
# get_data['GPS_STORE'] = int(time.time())
|
||
# self.sendOtherSms(number, "超出门店范围")
|
||
# else:
|
||
# if get_data['GPS_STORE'] == 0:
|
||
# get_data['GPS_STORE'] = int(time.time())
|
||
# self.sendOtherSms(number, "超出门店范围")
|
||
# pass
|
||
# pass
|
||
else:
|
||
get_data['GPS_STORE'] = 0
|
||
get_data['GPS_CALL'] = 0
|
||
pass
|
||
self.redis_obj.set("{}{}".format(self.redis_name_warn_status, number), json.dumps(get_data))
|
||
except BaseException as e:
|
||
if os.path.exists('./redis_error') is False:
|
||
os.mkdir('./redis_error')
|
||
path_name = './redis_error/{}'.format(datetime.date.today().strftime('%Y_%m_%d'))
|
||
if os.path.exists(path_name) is False:
|
||
os.mkdir(path_name)
|
||
file_obj = open('{}/redis_error.txt'.format(path_name), 'a+')
|
||
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), file=file_obj)
|
||
traceback.print_exc(file=file_obj)
|
||
file_obj.close()
|
||
self.printf(e)
|
||
self.printf(e.__traceback__.tb_frame.f_globals["__file__"]) # 发生异常所在的文件
|
||
self.printf(e.__traceback__.tb_lineno)
|
||
pass
|
||
|
||
# 解析并发送音频内容
|
||
def analysisSendAudio(self, res_data):
|
||
try:
|
||
json_de = json.loads(res_data['data']['data'])
|
||
if 'DATA' not in json_de.keys():
|
||
return False
|
||
try:
|
||
t = threading.Thread(target=cart_distance.CartDistance().sendAudio, args=(res_data['id'], json_de['DATA'], ))
|
||
t.start()
|
||
except threading.ThreadError as e:
|
||
print(e)
|
||
pass
|
||
except BaseException as e:
|
||
if os.path.exists('./redis_error') is False:
|
||
os.mkdir('./redis_error')
|
||
path_name = './redis_error/{}'.format(datetime.date.today().strftime('%Y_%m_%d'))
|
||
if os.path.exists(path_name) is False:
|
||
os.mkdir(path_name)
|
||
file_obj = open('{}/redis_error.txt'.format(path_name), 'a+')
|
||
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), file=file_obj)
|
||
traceback.print_exc(file=file_obj)
|
||
file_obj.close()
|
||
self.printf(e)
|
||
self.printf(e.__traceback__.tb_frame.f_globals["__file__"]) # 发生异常所在的文件
|
||
self.printf(e.__traceback__.tb_lineno)
|
||
pass
|
||
pass
|
||
|
||
|
||
"""
|
||
发送低电量警告短信
|
||
"""
|
||
def sendDdlSms(self, qc_code):
|
||
self.printf("发送低电量警告短信")
|
||
try:
|
||
if self.redis_obj is None:
|
||
self.redis_connect()
|
||
redis_name = "api:cxaibc:send_sms:lock:{}".format(hashlib.md5("{}低电量".format(qc_code).encode()).hexdigest())
|
||
if self.redis_obj.setnx(redis_name, 1) is False:
|
||
if self.redis_obj.ttl(redis_name) == -1:
|
||
self.redis_obj.expire(redis_name, 60 * 10)
|
||
self.printf("警告不能发出,还未过时长")
|
||
return False
|
||
|
||
# $redis_name = "api:cxaibc:bj_sms:send_sms_pl";
|
||
get_ttl = self.redis_obj.get("api:cxaibc:ddl_sms:send_sms_pl")
|
||
if get_ttl is None:
|
||
get_ttl = 10
|
||
self.redis_obj.setex(name=redis_name, time=int(get_ttl) * 60, value=1)
|
||
# 查找球车信息
|
||
temp_data = None
|
||
with mysql_obj() as db:
|
||
sql = """
|
||
select u.mobile_phone,u.real_name,s.user_type,b.status from cx_ball_cart as b
|
||
inner join cx_store_user as s on b.store_id = s.store_id
|
||
inner join cx_user as u on u.id = s.user_id
|
||
where b.ball_number = '{}' and s.user_type in (1,2) and u.is_delete = 0 and s.is_delete = 0 and s.status = 0 and b.is_delete = 0
|
||
""".format(qc_code)
|
||
db.cursor.execute(sql)
|
||
temp_data = db.cursor.fetchall()
|
||
if temp_data is None:
|
||
return False
|
||
if int(temp_data[0]['status']) != 0:
|
||
self.printf("车辆租赁中")
|
||
return False
|
||
|
||
redis_name_time = "api:cxaibc:send:send_time"
|
||
get = self.redis_obj.get(redis_name_time)
|
||
if get is None:
|
||
self.printf("警告不能发出,没有设置时间")
|
||
return False
|
||
pass
|
||
time_ = get.split(' - ')
|
||
if len(time_) != 2:
|
||
self.printf("警告不能发出,没有设置时间")
|
||
return False
|
||
time_tuple = time.localtime(time.time())
|
||
s_t = time.strptime("{}-{}-{} {}".format(time_tuple[0], time_tuple[1], time_tuple[2], time_[0]),
|
||
"%Y-%m-%d %H:%M:%S")
|
||
s_t_res = int(time.mktime(s_t))
|
||
e_t = time.strptime("{}-{}-{} {}".format(time_tuple[0], time_tuple[1], time_tuple[2], time_[1]),
|
||
"%Y-%m-%d %H:%M:%S")
|
||
e_t_res = int(time.mktime(e_t))
|
||
if s_t_res > time.time() or e_t_res < time.time():
|
||
self.printf("警告不能发出,没有在设置时间内")
|
||
return False
|
||
|
||
get_sms_option = self.getSmsSetting()
|
||
if get_sms_option is None:
|
||
self.printf("获取短信配置失败")
|
||
return False
|
||
phone_numbers = []
|
||
sign_name = []
|
||
template_param = []
|
||
arr_type = {
|
||
1: '场地管理员',
|
||
2: '场地服务员',
|
||
}
|
||
ELEC_PERCENT = 0
|
||
try:
|
||
qc_data = self.redis_obj.get("{}{}_{}".format("api:cxaibc:mqtt:data:", qc_code, "Detail"))
|
||
if qc_data is not None:
|
||
qc_data = json.loads(qc_data)
|
||
if 'data' in qc_data.keys():
|
||
qc_data = json.loads(qc_data['data'])
|
||
if 'ELEC_PERCENT' in qc_data.keys():
|
||
ELEC_PERCENT = qc_data['ELEC_PERCENT']
|
||
pass
|
||
pass
|
||
pass
|
||
except BaseException as e:
|
||
self.printf("数据解析失败", e)
|
||
return False
|
||
for v in temp_data:
|
||
sms_redis = self.redis_obj.get("{}{}".format("api:cxaibc:mqtt:send_sms:", v['mobile_phone']))
|
||
print(v)
|
||
if sms_redis is None or sms_redis == 'send':
|
||
phone_numbers.append(v['mobile_phone'])
|
||
sign_name.append(get_sms_option['sign_name'])
|
||
template_param.append({
|
||
"name": arr_type[v['user_type']],
|
||
"numbers": qc_code,
|
||
"rato": ELEC_PERCENT,
|
||
})
|
||
pass
|
||
try:
|
||
if len(phone_numbers) != 0:
|
||
send_sms.Sms(get_sms_option['access_key_id'], get_sms_option['access_secret']).main(
|
||
json.dumps(phone_numbers), json.dumps(sign_name), get_sms_option['ball_electric'],
|
||
json.dumps(template_param))
|
||
self.printf(phone_numbers)
|
||
except BaseException as e:
|
||
self.printf("发送短信失败", e)
|
||
pass
|
||
except BaseException as e:
|
||
if os.path.exists('./redis_error') is False:
|
||
os.mkdir('./redis_error')
|
||
path_name = './redis_error/{}'.format(datetime.date.today().strftime('%Y_%m_%d'))
|
||
if os.path.exists(path_name) is False:
|
||
os.mkdir(path_name)
|
||
file_obj = open('{}/redis_error.txt'.format(path_name), 'a+')
|
||
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), file=file_obj)
|
||
traceback.print_exc(file=file_obj)
|
||
file_obj.close()
|
||
self.printf(e)
|
||
self.printf(e.__traceback__.tb_frame.f_globals["__file__"]) # 发生异常所在的文件
|
||
self.printf(e.__traceback__.tb_lineno)
|
||
pass
|
||
|
||
|
||
"""
|
||
发送其他警告短信
|
||
"""
|
||
def sendOtherSms(self, qc_code, msg):
|
||
self.printf("发送其他警告短信")
|
||
try:
|
||
if self.redis_obj is None:
|
||
self.redis_connect()
|
||
redis_name = "api:cxaibc:send_sms:lock:{}".format(
|
||
hashlib.md5("{}{}".format(qc_code, msg).encode()).hexdigest())
|
||
if self.redis_obj.setnx(redis_name, 1) is False:
|
||
if self.redis_obj.ttl(redis_name) == -1:
|
||
self.redis_obj.expire(redis_name, 60 * 10)
|
||
self.printf("警告不能发出,还未过时长")
|
||
return False
|
||
get_ttl = self.redis_obj.get("api:cxaibc:ddl_sms:send_sms_pl")
|
||
if get_ttl is None:
|
||
get_ttl = 10
|
||
self.redis_obj.setex(redis_name, int(get_ttl) * 60, 1)
|
||
redis_name_time = "api:cxaibc:send:send_time"
|
||
get = self.redis_obj.get(redis_name_time)
|
||
if get is None:
|
||
self.printf("警告不能发出,没有设置时间")
|
||
return False
|
||
pass
|
||
time_ = get.split(' - ')
|
||
if len(time_) != 2:
|
||
self.printf("警告不能发出,没有设置时间")
|
||
return False
|
||
time_tuple = time.localtime(time.time())
|
||
s_t = time.strptime("{}-{}-{} {}".format(time_tuple[0], time_tuple[1], time_tuple[2], time_[0]),
|
||
"%Y-%m-%d %H:%M:%S")
|
||
s_t_res = int(time.mktime(s_t))
|
||
e_t = time.strptime("{}-{}-{} {}".format(time_tuple[0], time_tuple[1], time_tuple[2], time_[1]),
|
||
"%Y-%m-%d %H:%M:%S")
|
||
e_t_res = int(time.mktime(e_t))
|
||
if s_t_res > time.time() or e_t_res < time.time():
|
||
self.printf("警告不能发出,没有在设置时间内")
|
||
return False
|
||
get_ttl = self.redis_obj.get("api:cxaibc:bj_sms:send_sms_pl")
|
||
if get_ttl is None:
|
||
get_ttl = 10
|
||
self.redis_obj.setex(redis_name, int(get_ttl) * 60, 1)
|
||
# 查找球车信息
|
||
temp_data = None
|
||
with mysql_obj() as db:
|
||
sql = """
|
||
select u.mobile_phone,u.real_name,s.user_type,b.status from cx_ball_cart as b
|
||
inner join cx_store_user as s on b.store_id = s.store_id
|
||
inner join cx_user as u on u.id = s.user_id
|
||
where b.ball_number = '{}' and s.user_type in (1,2) and u.is_delete = 0 and s.is_delete = 0 and s.status = 0 and b.is_delete = 0
|
||
""".format(qc_code)
|
||
db.cursor.execute(sql)
|
||
temp_data = db.cursor.fetchall()
|
||
if temp_data is None:
|
||
return False
|
||
|
||
# if int(temp_data[0]['status']) != 1:
|
||
# self.printf("车辆不租赁中")
|
||
# return False
|
||
|
||
phone_numbers = []
|
||
sign_name = []
|
||
template_param = []
|
||
arr_type = {
|
||
1: '场地管理员',
|
||
2: '场地服务员',
|
||
}
|
||
get_sms_option = self.getSmsSetting()
|
||
if get_sms_option is None:
|
||
self.printf("获取短信配置失败")
|
||
return False
|
||
for v in temp_data:
|
||
sms_redis = self.redis_obj.get("{}{}".format("api:cxaibc:mqtt:send_sms:", v['mobile_phone']))
|
||
if sms_redis is None or sms_redis == 'send':
|
||
phone_numbers.append(v['mobile_phone'])
|
||
sign_name.append(get_sms_option['sign_name'])
|
||
template_param.append({
|
||
"name": arr_type[v['user_type']],
|
||
"numbers": qc_code,
|
||
"error": msg,
|
||
})
|
||
pass
|
||
try:
|
||
if len(phone_numbers) != 0:
|
||
send_sms.Sms(get_sms_option['access_key_id'], get_sms_option['access_secret']).main(
|
||
json.dumps(phone_numbers), json.dumps(sign_name), get_sms_option['ball_error'],
|
||
json.dumps(template_param))
|
||
print('短信发送成功')
|
||
except BaseException as e:
|
||
self.printf("发送短信失败", e)
|
||
pass
|
||
except BaseException as e:
|
||
if os.path.exists('./redis_error') is False:
|
||
os.mkdir('./redis_error')
|
||
path_name = './redis_error/{}'.format(datetime.date.today().strftime('%Y_%m_%d'))
|
||
if os.path.exists(path_name) is False:
|
||
os.mkdir(path_name)
|
||
file_obj = open('{}/redis_error.txt'.format(path_name), 'a+')
|
||
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), file=file_obj)
|
||
traceback.print_exc(file=file_obj)
|
||
file_obj.close()
|
||
self.printf(e)
|
||
self.printf(e.__traceback__.tb_frame.f_globals["__file__"]) # 发生异常所在的文件
|
||
self.printf(e.__traceback__.tb_lineno)
|
||
pass
|
||
|
||
|
||
"""
|
||
获取短信设置数据
|
||
"""
|
||
def getSmsSetting(self):
|
||
redis_name = "api:cxaibc:mqtt:send_setting_v3"
|
||
get = self.redis_obj.get(redis_name)
|
||
if get is not None:
|
||
data = json.loads(get)
|
||
return data
|
||
temp_data = {}
|
||
temp_data['access_key_id'] = ''
|
||
temp_data['access_secret'] = ''
|
||
temp_data['sign_name'] = ''
|
||
with mysql_obj() as db:
|
||
sql = """
|
||
select * from cx_sms_setting order by id desc limit 1
|
||
"""
|
||
db.cursor.execute(sql)
|
||
res = db.cursor.fetchall()
|
||
if len(res) != 0:
|
||
temp_data['access_key_id'] = res[0]['access_key_id']
|
||
temp_data['access_secret'] = res[0]['access_secret']
|
||
temp_data['sign_name'] = res[0]['sign_name']
|
||
pass
|
||
with mysql_obj() as db:
|
||
sql = """
|
||
select * from cx_sms_tpl where `key` = 'ball_error'
|
||
"""
|
||
db.cursor.execute(sql)
|
||
res = db.cursor.fetchall()
|
||
if len(res) != 0:
|
||
temp_data['ball_error'] = res[0]['tpl_code']
|
||
pass
|
||
with mysql_obj() as db:
|
||
sql = """
|
||
select * from cx_sms_tpl where `key` = 'ball_electric'
|
||
"""
|
||
db.cursor.execute(sql)
|
||
res = db.cursor.fetchall()
|
||
if len(res) != 0:
|
||
temp_data['ball_electric'] = res[0]['tpl_code']
|
||
pass
|
||
self.redis_obj.setex(redis_name, 60*10, json.dumps(temp_data, ensure_ascii=False))
|
||
return temp_data
|
||
pass
|
||
|
||
"""
|
||
打印信息
|
||
"""
|
||
def printf(self, *data):
|
||
if self.is_debug is True:
|
||
print(data, time.time())
|
||
pass
|
||
|
||
|
||
if __name__ == '__main__':
|
||
# python3 /var/www/xlqc/cart_mqtt_sub/redis_sub.py
|
||
# obj = RedisSub()
|
||
# obj.redis_connect()
|
||
# redis_name = "api:cxaibc:send:send_time"
|
||
# get = obj.redis_obj.get(redis_name)
|
||
# if get is None:
|
||
# pass
|
||
# time_ = get.split(' - ')
|
||
#
|
||
# time_tuple = time.localtime(time.time())
|
||
# s_t = time.strptime("{}-{}-{} {}".format(time_tuple[0], time_tuple[1], time_tuple[2], time_[0]),
|
||
# "%Y-%m-%d %H:%M:%S")
|
||
# s_t_res = int(time.mktime(s_t))
|
||
# e_t = time.strptime("{}-{}-{} {}".format(time_tuple[0], time_tuple[1], time_tuple[2], time_[1]),
|
||
# "%Y-%m-%d %H:%M:%S")
|
||
# e_t_res = int(time.mktime(e_t))
|
||
# if s_t_res > time.time() or e_t_res < time.time():
|
||
# print("警告不能发出,没有在设置时间内")
|
||
|
||
# res = obj.sendDdlSms("20221000999")
|
||
RedisSub().run()
|
||
# get_data = {}
|
||
# lon = 118.050146181
|
||
# lat = 24.523877029898
|
||
# json_de = json.loads('{"store":{"styleId":"default","paths":[{"lat":24.53396475482219,"lng":118.03349055688,"height":0},{"lat":24.534017031802232,"lng":118.03486972396968,"height":0},{"lat":24.53391247742138,"lng":118.03601902841581,"height":0},{"lat":24.532448712132755,"lng":118.03745565765735,"height":0},{"lat":24.531350877264686,"lng":118.03929454652553,"height":0},{"lat":24.530828094982756,"lng":118.04101850144013,"height":0},{"lat":24.530723538943473,"lng":118.04274245898637,"height":0},{"lat":24.531507711006046,"lng":118.04527092964486,"height":0},{"lat":24.531350877264686,"lng":118.04630530276904,"height":0},{"lat":24.531612268187843,"lng":118.04653516365829,"height":0},{"lat":24.531978213049605,"lng":118.0487763077665,"height":0},{"lat":24.532500990143173,"lng":118.04958082131748,"height":0},{"lat":24.53239643489861,"lng":118.05021293788548,"height":0},{"lat":24.53213504600724,"lng":118.05044279943263,"height":0},{"lat":24.53213504600724,"lng":118.05107491709725,"height":0},{"lat":24.53182137909801,"lng":118.0513622429894,"height":0},{"lat":24.53182137909801,"lng":118.05199436065402,"height":0},{"lat":24.531769101602627,"lng":118.0523966171005,"height":0},{"lat":24.53119404252936,"lng":118.05285633898859,"height":0},{"lat":24.530880373668047,"lng":118.05331606060247,"height":0},{"lat":24.530618981819547,"lng":118.05371831726825,"height":0},{"lat":24.530566703623986,"lng":118.05394817816943,"height":0},{"lat":24.530200754448273,"lng":118.05400564340039,"height":0},{"lat":24.529730246740858,"lng":118.05383324772652,"height":0},{"lat":24.52711628106854,"lng":118.05584453076756,"height":0},{"lat":24.526750321636595,"lng":118.05624678732363,"height":0},{"lat":24.52659348145376,"lng":118.05538480876976,"height":0},{"lat":24.526488921439217,"lng":118.05469522604744,"height":0},{"lat":24.526959441442592,"lng":118.0534309911568,"height":0},{"lat":24.52554787574422,"lng":118.05354592157391,"height":0},{"lat":24.524136294627546,"lng":118.05354592157391,"height":0},{"lat":24.524031732018347,"lng":118.05228168654628,"height":0},{"lat":24.524397699772074,"lng":118.05101745143634,"height":0},{"lat":24.525652437091058,"lng":118.04958082131748,"height":0},{"lat":24.526750321636595,"lng":118.04756953765968,"height":0},{"lat":24.527168560925254,"lng":118.04492613743378,"height":0},{"lat":24.527429959809115,"lng":118.039696802643,"height":0},{"lat":24.528893783287415,"lng":118.03917961344928,"height":0},{"lat":24.52913841918043,"lng":118.03898200556466,"height":0},{"lat":24.529849297005057,"lng":118.03600423559067,"height":0},{"lat":24.529887722560204,"lng":118.03541290522298,"height":0},{"lat":24.530503825178556,"lng":118.03351664816603,"height":0},{"lat":24.533953890827128,"lng":118.03356179630077,"height":0},{"lat":24.533953890827128,"lng":118.03351664816603,"height":0}],"id":"4821E6AE-BC13-4F36-89F9-BDE24F8EBE80","area_type":"store"},"call":{"styleId":"default","paths":[{"lat":24.53464449656417,"lng":118.03320913274763,"height":0},{"lat":24.53464449656417,"lng":118.03416629669232,"height":0},{"lat":24.53391247742138,"lng":118.03601902841581,"height":0},{"lat":24.532448712132755,"lng":118.03745565765735,"height":0},{"lat":24.531350877264686,"lng":118.03929454652553,"height":0},{"lat":24.530828094982756,"lng":118.04101850144013,"height":0},{"lat":24.530723538943473,"lng":118.04274245898637,"height":0},{"lat":24.531507711006046,"lng":118.04527092964486,"height":0},{"lat":24.531350877264686,"lng":118.04630530276904,"height":0},{"lat":24.531612268187843,"lng":118.04653516365829,"height":0},{"lat":24.531978213049605,"lng":118.0487763077665,"height":0},{"lat":24.532500990143173,"lng":118.04958082131748,"height":0},{"lat":24.53239643489861,"lng":118.05021293788548,"height":0},{"lat":24.53213504600724,"lng":118.05044279943263,"height":0},{"lat":24.53213504600724,"lng":118.05107491709725,"height":0},{"lat":24.53182137909801,"lng":118.0513622429894,"height":0},{"lat":24.531769101602627,"lng":118.0523966171005,"height":0},{"lat":24.53119404252936,"lng":118.05285633898859,"height":0},{"lat":24.530566703623986,"lng":118.05394817816943,"height":0},{"lat":24.530200754448273,"lng":118.05400564340039,"height":0},{"lat":24.529730246740858,"lng":118.05383324772652,"height":0},{"lat":24.526750321636595,"lng":118.05624678732363,"height":0},{"lat":24.524136294627546,"lng":118.05354592157391,"height":0},{"lat":24.52386483926673,"lng":118.0511642225515,"height":0},{"lat":24.525652437091058,"lng":118.04958082131748,"height":0},{"lat":24.526750321636595,"lng":118.04756953765968,"height":0},{"lat":24.527168560925254,"lng":118.04492613743378,"height":0},{"lat":24.527429959809115,"lng":118.039696802643,"height":0},{"lat":24.52913841918043,"lng":118.03898200556466,"height":0},{"lat":24.529887722560204,"lng":118.03541290522298,"height":0},{"lat":24.530503825178556,"lng":118.03351664816603,"height":0},{"lat":24.53467452239805,"lng":118.03324213792325,"height":0}],"id":"AA223BDA-DF98-4BEA-8D7F-764F76886114","area_type":"call"},"stop":{"styleId":"default","paths":[{"lat":24.527254213347913,"lng":118.04904485306122,"height":0},{"lat":24.52681061632031,"lng":118.04870032490044,"height":0},{"lat":24.52654764489498,"lng":118.04884339166438,"height":0},{"lat":24.526425456023883,"lng":118.04921127761588,"height":0},{"lat":24.527047024489168,"lng":118.0496463173913,"height":0},{"lat":24.52715327521774,"lng":118.04987405632801,"height":0},{"lat":24.527554792847575,"lng":118.04967568385439,"height":0},{"lat":24.527254635281558,"lng":118.0490421025479,"height":0}],"id":"5C3EC71B-4EF2-4012-99DE-3DA9DFDA4A9D","area_type":"stop"}}')
|
||
# point = Point(lon, lat)
|
||
# if 'call' in json_de.keys():
|
||
# polygon_data = []
|
||
# for v in json_de['call']['paths']:
|
||
# polygon_data.append([v['lng'], v['lat']])
|
||
# polygon = Polygon(polygon_data)
|
||
# if polygon.contains(point) is False:
|
||
# print('不在安全范围内')
|
||
# # 不在安全范围内
|
||
# if 'GPS_CALL' not in get_data.keys():
|
||
# get_data['GPS_CALL'] = int(time.time())
|
||
# print("超出安全范围")
|
||
# else:
|
||
# if get_data['GPS_CALL'] == 0:
|
||
# get_data['GPS_CALL'] = int(time.time())
|
||
# print("超出安全范围")
|
||
# pass
|
||
# pass
|
||
# else:
|
||
# if 'store' in json_de.keys():
|
||
# polygon_data = []
|
||
# for v in json_de['store']['paths']:
|
||
# polygon_data.append([v['lng'], v['lat']])
|
||
# polygon = Polygon(polygon_data)
|
||
# if polygon.contains(point) is False:
|
||
# print('不在门店范围内')
|
||
# # 不在门店范围内
|
||
# if 'GPS_STORE' not in get_data.keys():
|
||
# get_data['GPS_STORE'] = int(time.time())
|
||
# print("超出门店范围")
|
||
# else:
|
||
# if get_data['GPS_STORE'] == 0:
|
||
# get_data['GPS_STORE'] = int(time.time())
|
||
# print("超出门店范围")
|
||
# pass
|
||
# pass
|
||
# else:
|
||
# get_data['GPS_STORE'] = 0
|
||
# get_data['GPS_CALL'] = 0
|
||
# else:
|
||
# get_data['GPS_CALL'] = 0
|
||
#
|
||
# pass
|
||
# elif 'store' in json_de.keys():
|
||
# polygon_data = []
|
||
# for v in json_de['store']['paths']:
|
||
# polygon_data.append([v['lng'], v['lat']])
|
||
# polygon = Polygon(polygon_data)
|
||
# if polygon.contains(point) is False:
|
||
# print('不在门店范围内')
|
||
# # 不在门店范围内
|
||
# if 'GPS_STORE' not in get_data.keys():
|
||
# get_data['GPS_STORE'] = int(time.time())
|
||
# print("超出门店范围")
|
||
# else:
|
||
# if get_data['GPS_STORE'] == 0:
|
||
# get_data['GPS_STORE'] = int(time.time())
|
||
# print("超出门店范围")
|
||
# pass
|
||
# pass
|
||
# else:
|
||
# get_data['GPS_STORE'] = 0
|
||
# get_data['GPS_CALL'] = 0
|
||
# pass
|
||
# obj = RedisSub()
|
||
# obj.is_debug = True
|
||
# obj.sendDdlSms("20221000852") |