utils.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. import string
  2. import random
  3. import requests
  4. import json
  5. import logging
  6. import time
  7. import hashlib
  8. import math
  9. from captcha.image import ImageCaptcha
  10. from io import BytesIO
  11. import base64
  12. from datetime import datetime, timedelta
  13. import calendar
  14. from smartfarming.models.user import Role, UserPurview
  15. from kedong.tools import RedisPool
  16. from kedong import settings
  17. logger = logging.getLogger("other")
  18. redis_pool = RedisPool().get_redis_pool(settings.redis_db["jiankong"])
  19. config = settings.CONFIG
  20. def perms_pc_app(type_id=1000, perms_lst=[]):
  21. menu = "PC" if type_id == 1000 else "APP"
  22. parent_ids = []
  23. for p in perms_lst:
  24. # 先判断是否是父级菜单
  25. per_obj = UserPurview.objects.filter(id=int(p), menu=menu).first()
  26. if per_obj:
  27. if per_obj.parent_perm_id == 0:
  28. parent_ids.append(p)
  29. perm_lst = []
  30. for i in parent_ids:
  31. parent = UserPurview.objects.get(id=int(i), menu=menu)
  32. inner_parent = {
  33. "menu": parent.menu,
  34. "parent_perm_id": parent.parent_perm_id,
  35. "pur_id": parent.id,
  36. "purview_name": parent.purview_name,
  37. "url": parent.url
  38. }
  39. children_lst = []
  40. # 获取此父级菜单中所有的子菜单
  41. children = UserPurview.objects.filter(parent_perm_id=int(i), menu=menu)
  42. for child in children:
  43. if child.id in perms_lst:
  44. children_lst.append(
  45. {
  46. "menu": child.menu,
  47. "parent_perm_id": child.parent_perm_id,
  48. "pur_id": child.id,
  49. "purview_name": child.purview_name,
  50. "url": child.url
  51. }
  52. )
  53. if children_lst:
  54. inner_parent["children"] = children_lst
  55. perm_lst.append(inner_parent)
  56. return perm_lst
  57. def get_perm_list(device_user):
  58. id = device_user.role_id
  59. try:
  60. role = Role.objects.get(id=id)
  61. role_perm = role.role_perm
  62. perms_lst = [int(i) for i in role_perm.split(",")]
  63. pc_perm_lst = perms_pc_app(type_id=1000, perms_lst=perms_lst)
  64. app_perm_lst = perms_pc_app(type_id=2000, perms_lst=perms_lst)
  65. if pc_perm_lst and app_perm_lst:
  66. perm_lst = [
  67. {
  68. "menu": "",
  69. "parent_perm_id": 1000,
  70. "pur_id": 0,
  71. "purview_name": "登录PC端",
  72. "url": "",
  73. "children": pc_perm_lst
  74. },
  75. {
  76. "menu": "",
  77. "parent_perm_id": 2000,
  78. "pur_id": 0,
  79. "purview_name": "登录APP端",
  80. "url": "",
  81. "children": app_perm_lst
  82. }
  83. ]
  84. elif pc_perm_lst:
  85. perm_lst = [
  86. {
  87. "menu": "",
  88. "parent_perm_id": 1000,
  89. "pur_id": 0,
  90. "purview_name": "登录PC端",
  91. "url": "",
  92. "children": pc_perm_lst
  93. }
  94. ]
  95. elif app_perm_lst:
  96. perm_lst = [
  97. {
  98. "menu": "",
  99. "parent_perm_id": 2000,
  100. "pur_id": 0,
  101. "purview_name": "登录APP端",
  102. "url": "",
  103. "children": app_perm_lst
  104. }
  105. ]
  106. else:
  107. perm_lst = []
  108. mark = role.mark
  109. return perm_lst, mark
  110. except Exception as e:
  111. return [], ""
  112. def get_all_pers():
  113. role_perm = UserPurview.objects.all().values("id")
  114. perms_lst = []
  115. for i in role_perm:
  116. perms_lst.append(i.get("id"))
  117. pc_perm_lst = perms_pc_app(type_id=1000, perms_lst=perms_lst)
  118. app_perm_lst = perms_pc_app(type_id=2000, perms_lst=perms_lst)
  119. perm_lst = [
  120. {
  121. "menu": "",
  122. "parent_perm_id": 1000,
  123. "pur_id": 0,
  124. "purview_name": "登录PC端",
  125. "url": "",
  126. "children": pc_perm_lst
  127. },
  128. {
  129. "menu": "",
  130. "parent_perm_id": 2000,
  131. "pur_id": 0,
  132. "purview_name": "登录APP端",
  133. "url": "",
  134. "children": app_perm_lst
  135. }
  136. ]
  137. return perm_lst
  138. def get_captcha():
  139. """获取图片验证码
  140. return :
  141. 验证码字符串,验证码图片base64数据
  142. """
  143. chr_all = string.ascii_uppercase + string.digits
  144. chr_all = chr_all.replace('0', '').replace('1', '').replace('2', '').replace('O', '').replace('I', '')
  145. code_str = ''.join(random.sample(chr_all, 4))
  146. image = ImageCaptcha().generate_image(code_str)
  147. f = BytesIO()
  148. image.save(f, 'png')
  149. data = f.getvalue()
  150. f.close()
  151. encode_data = base64.b64encode(data)
  152. data = str(encode_data, encoding='utf-8')
  153. img_data = "data:image/jpeg;base64,{data}".format(data=data)
  154. return code_str, img_data
  155. def get_recent_month(num):
  156. # 获取最近N个月的时间戳
  157. end_time = datetime.now() # 结束时间,当前时间
  158. # 获取当前月份和年份
  159. current_month = end_time.month
  160. current_year = end_time.year
  161. # 计算开始时间
  162. start_month = current_month - num # 当前月份往前推N个月
  163. start_year = current_year
  164. if start_month <= 0: # 如果计算得到的月份为负数,则需要向前借位
  165. start_month += 12
  166. start_year -= 1
  167. # 获取开始时间所在月份的最后一天
  168. _, last_day = calendar.monthrange(start_year, start_month)
  169. start_time = datetime(start_year, start_month, last_day).timestamp()
  170. return start_time
  171. def get_addr_by_lag_lng(lat,lng):
  172. # 根据经纬度获取省市级
  173. is_success, province, city, district = False, "", "", ""
  174. try:
  175. # 使用腾讯接口
  176. url = "https://apis.map.qq.com/ws/geocoder/v1?location={},{}&get_poi=0&key=OA4BZ-FX43U-E5VV2-45M6S-C4HD3-NIFFI&output=json".format(lat,lng)
  177. requests.adapters.DEFAULT_RETRIES = 5 # 增加重连次数
  178. s = requests.session()
  179. s.keep_alive = False # 关闭多余连接
  180. ret = s.get(url)
  181. rest = json.loads(ret.text)
  182. province = rest["result"]["ad_info"]["province"]
  183. city = rest["result"]["ad_info"]["city"]
  184. district = rest["result"]["ad_info"]["district"]
  185. is_success = True
  186. except Exception as e:
  187. logger.error(f"获取腾讯地理位置接口失败 {e.args}")
  188. if not is_success:
  189. try:
  190. # 使用百度接口
  191. url = "http://api.map.baidu.com/geocoder?location=%s,%s&output=json"%(lat,lng)
  192. requests.adapters.DEFAULT_RETRIES = 5 # 增加重连次数
  193. s = requests.session()
  194. s.keep_alive = False # 关闭多余连接
  195. ret = s.get(url)
  196. addr = json.loads(ret.text)
  197. province = addr["result"]["addressComponent"]["province"]
  198. city = addr["result"]["addressComponent"]["city"]
  199. district = addr["result"]["addressComponent"]["district"]
  200. is_success = True
  201. except Exception as e:
  202. logger.error(f"获取百度地理位置接口失败 {e.args}")
  203. return is_success, province, city, district
  204. # 获取天气数据
  205. def get_address_by_lntlat(lng, lat):
  206. province, city, district = "", "", ""
  207. try:
  208. key = "78ce288400f4fc6d9458989875c833c2"
  209. adcode_url = "http://restapi.amap.com/v3/geocode/regeo?key={key}&location={lng},{lat}&poitype=&radius=&" \
  210. "extensions=all&batch=false&roadlevel=0".format(key=key, lng=lng, lat=lat)
  211. res = requests.get(adcode_url)
  212. rsp = res.json()
  213. address_info = rsp['regeocode']['addressComponent']
  214. adcode = address_info['adcode']
  215. if adcode != "900000":
  216. province, city, district = address_info['province'], address_info['city'], address_info['district']
  217. if (not city) and district:
  218. city = district
  219. except Exception as e:
  220. pass
  221. return province, city, district
  222. # 获取天气相关信息
  223. def get_weather_info(lng=None, lat=None):
  224. data = {}
  225. if lng and lat:
  226. try:
  227. url = "http://114.115.147.140:8080/weather"
  228. res = requests.post(url, {"lat": lat, "lng": lng})
  229. result = res.json()
  230. if result['status'] == 'true':
  231. data = result['data']
  232. except Exception as e:
  233. pass
  234. return data
  235. def expire_time(times):
  236. data_time = datetime.datetime.now()
  237. cultivate_time_expire = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(times))
  238. time1 = datetime.datetime.strptime(cultivate_time_expire,"%Y-%m-%d %H:%M:%S")
  239. num=(time1-data_time).days
  240. print("设备到期天数---",num)
  241. if int(num) <=7 and int(num) >= 0:
  242. print("即将到期")
  243. status = 2
  244. elif int(num) < 0:
  245. print("已到期")
  246. status = 1
  247. else:
  248. print("未到期")
  249. status = 0
  250. return status
  251. def get_center_lnglat(lnglats_list):
  252. x, y, z = 0, 0, 0
  253. length = len(lnglats_list)
  254. for n, a in lnglats_list:
  255. g, t = math.radians(float(n)), math.radians(float(a))
  256. x += math.cos(t) * math.cos(g)
  257. y += math.cos(t) * math.sin(g)
  258. z += math.sin(t)
  259. x = float(x / length)
  260. y = float(y / length)
  261. z = float(z / length)
  262. lng = round(math.degrees(math.atan2(y, x)), 4)
  263. lat = round(math.degrees(math.atan2(z, math.sqrt(x*x + y*y))), 4)
  264. return lng, lat
  265. def md5value(appSecret):
  266. """sign加密"""
  267. times = int(time.time())
  268. # 随机生成32位字符串
  269. nonce = ''.join(random.sample(string.ascii_letters + string.digits, 32))
  270. sign = "time:{},nonce:{},appSecret:{}".format(times, nonce, appSecret)
  271. input_name = hashlib.md5()
  272. input_name.update(sign.encode("utf-8"))
  273. sign = (input_name.hexdigest()).lower()
  274. return times,nonce,sign
  275. def deviceAccessToken(appId, appSecret):
  276. # 乐橙云账号秘钥
  277. # 先从redis 中获取token
  278. tokens = redis_pool.get(appId)
  279. if tokens and tokens !=None:
  280. redis_jk_data = eval(tokens)
  281. status = redis_jk_data.get("status",1)
  282. if status:
  283. # 查看到期时间
  284. expireTime = redis_pool.ttl(appId)
  285. # 设置到期时间 秒
  286. # redis_pool.expire('ttt', 10)
  287. redis_jk_data["result"]["data"]["expireTime"] = expireTime
  288. else:
  289. redis_jk_data = {"status":0}
  290. return redis_jk_data
  291. else:
  292. status = 0
  293. if not status:
  294. url = config.get("camera").get("lc_token")
  295. # 加密
  296. times,nonce,sign = md5value(appSecret)
  297. data = {
  298. "system":{"ver":"1.0","appId":appId,"sign":sign,"time":times,"nonce":nonce},
  299. "id":nonce,
  300. "params":{}
  301. }
  302. token_data = requests.post(url,json=data, timeout=5)
  303. if token_data.status_code == 200:
  304. try:
  305. token_json_data = json.loads(token_data.text)
  306. expireTime = token_json_data["result"]["data"]["expireTime"]
  307. # status 1 代表获取token 成功 0失败
  308. token_json_data["status"] = 1
  309. except Exception as e:
  310. token_json_data = {"status":0}
  311. expireTime = 5
  312. else:
  313. token_json_data = {"status":0}
  314. expireTime = 5
  315. redis_pool.set(appId,str(token_json_data),expireTime)
  316. return token_json_data
  317. def device_config(appId,appSecret):
  318. # 配置项
  319. time,nonce,sign = md5value(appSecret)
  320. token_data = deviceAccessToken(appId, appSecret)
  321. if token_data.get("status","0"):
  322. token = token_data["result"]["data"]["accessToken"]
  323. else:
  324. token = ""
  325. return time,nonce,sign,token
  326. def controlMove(appId,appSecret,deviceId,operation,channelId="0"):
  327. # 云台控制接口
  328. url = config.get("camera").get("lc_controler")
  329. time,nonce,sign,token = device_config(appId, appSecret)
  330. if not token:
  331. return {"msg":"控制失败"}
  332. data = {
  333. "system":{"ver":"1.0","appId":appId,"sign":sign,"time":time,"nonce":nonce},
  334. "id":nonce,
  335. "params":{"token":token,"deviceId":deviceId,"channelId":channelId,"operation":operation,"duration":"1000"}
  336. }
  337. control_Move = requests.post(url,json=data)
  338. return control_Move.json()
  339. def bindDeviceLive(appId,appSecret,deviceId,channelId="0"):
  340. # 获取直播地址
  341. url = config.get("camera").get("lc_addr")
  342. time,nonce,sign,token = device_config(appId, appSecret)
  343. data = {
  344. "system":{"ver":"1.0","appId":appId,"sign":sign,"time":time,"nonce":nonce},
  345. "params":{"streamId":1,"deviceId":deviceId,"channelId":channelId,"token":token},
  346. "id":nonce
  347. }
  348. device_live_data = requests.post(url,json=data)
  349. return device_live_data.json()
  350. def getLive(appId,appSecret,deviceId,channelId="0"):
  351. # 查询监控地址 用于设备直播地址创建后再次查询使用
  352. url = config.get("camera").get("lc_stream")
  353. time,nonce,sign,token = device_config(appId, appSecret)
  354. data = {
  355. "system":{"ver":"1.0","appId":appId,"sign":sign,"time":time,"nonce":nonce},
  356. "params":{"deviceId":deviceId, "channelId":channelId,"token":token},
  357. "id":nonce
  358. }
  359. live_data = requests.post(url,json=data)
  360. return live_data.json()
  361. def modify_live_time(appId,appSecret,liveToken,start_time,end_time,period="everyday"):
  362. # 开启,修改直播计划时间
  363. # period 直播周期,always:永久,once:指定某天, everyday:每天
  364. url = config.get("camera").get("lc_modify_live_plan")
  365. time,nonce,sign,token = device_config(appId, appSecret)
  366. if not token:
  367. return {'result': {'msg': '获取token失败。', 'code': '1'}, 'id': 'rWfBFgohj7VwkxsqbM5p4JKDOtQNU2XA'}
  368. data = {
  369. "system":{"ver":"1.0","appId":appId,"sign":sign,"time":time,"nonce":nonce},
  370. "id":nonce,
  371. "params":{"token":token,"period":period,"liveToken":liveToken,"beginTime":start_time,"endTime": end_time}
  372. }
  373. if period == "always":
  374. del data["params"]["beginTime"]
  375. del data["params"]["endTime"]
  376. device_live_data = requests.post(url,json=data).json()
  377. return device_live_data
  378. def off_on_live(appId,appSecret,liveToken,status):
  379. # 关闭、开启当前直播
  380. url = config.get("camera").get("lc_modify_live_plan_status")
  381. time,nonce,sign,token = device_config(appId, appSecret)
  382. if not token:
  383. return {'result': {'msg': '获取token失败。', 'code': '1'}, 'id': 'rWfBFgohj7VwkxsqbM5p4JKDOtQNU2XA'}
  384. data = {
  385. "system":{"ver":"1.0","appId":appId,"sign":sign,"time":time,"nonce":nonce},
  386. "params":{"token":token,"liveToken":liveToken,"status":status},
  387. "id":nonce
  388. }
  389. device_live_data = requests.post(url,json=data).json()
  390. return device_live_data
  391. def setDeviceSnap(appId,appSecret,deviceId,channelId="0"):
  392. # 抓图接口
  393. url = config.get("camera").get("lc_device_snap_enhanced")
  394. # url = config.get("camera").get("lc_device_snap")
  395. time,nonce,sign,token = device_config(appId, appSecret)
  396. if not token:
  397. return {"msg": "抓图失败"}
  398. data = {
  399. "system":{"ver":"1.0", "appId":appId,"sign":sign,"time":time,"nonce":nonce},
  400. "params":{"deviceId":deviceId,"channelId":channelId,"token":token},
  401. "id":nonce
  402. }
  403. img_data = requests.post(url,json=data)
  404. result = img_data.json()
  405. if result.get("result").get("code") == "0":
  406. return result.get("result").get("data").get("url")
  407. def get_weather(ip):
  408. # 获取天气
  409. res = requests.get("https://v0.yiketianqi.com/api?unescape=1&version=v91&appid=69334222&appsecret=2u4bHXHD&ext=")
  410. response = json.loads(res.text)
  411. return response.get("data")
  412. def getKitToken(appId,appSecret,deviceId,channelId="0"):
  413. # 获取录像回放所需要的token
  414. url = config.get("camera").get("lc_kit_token")
  415. time,nonce,sign,token = device_config(appId, appSecret)
  416. if not token:
  417. return {"result":{"code":"1"}}
  418. data = {
  419. "system":{"ver":"1.0","appId":appId,"sign":sign,"time":time,"nonce":nonce},
  420. "id":nonce,
  421. "params":{"type":0,"deviceId":deviceId,"channelId":channelId,"token":token}
  422. }
  423. like_token_data = requests.post(url,json=data)
  424. return like_token_data.json()
  425. def getRecord(appId,appSecret,deviceId,channelId="0"):
  426. url = config.get("camera").get("lc_local_record")
  427. time,nonce,sign,token = device_config(appId, appSecret)
  428. if not token:
  429. return {"result":{"code":"1"}}
  430. data = {
  431. "system":{"ver":"1.0","appId":appId,"sign":sign,"time":time,"nonce":nonce},
  432. "id":nonce,
  433. "params":{
  434. "deviceId":deviceId,
  435. "channelId":channelId,
  436. "token":token,
  437. "beginTime":"2023-07-19 00:00:00",
  438. "endTime": "2023-07-25 00:00:00",
  439. "type": "All",
  440. "count": 100
  441. }
  442. }
  443. record_token_data = requests.post(url,json=data)
  444. return record_token_data.json()
  445. if __name__ == "__main__":
  446. t = get_recent_month(1)
  447. print(t)