utils.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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 md5value(appSecret):
  236. """sign加密"""
  237. times = int(time.time())
  238. # 随机生成32位字符串
  239. nonce = ''.join(random.sample(string.ascii_letters + string.digits, 32))
  240. sign = "time:{},nonce:{},appSecret:{}".format(times, nonce, appSecret)
  241. input_name = hashlib.md5()
  242. input_name.update(sign.encode("utf-8"))
  243. sign = (input_name.hexdigest()).lower()
  244. return times,nonce,sign
  245. def deviceAccessToken(appId, appSecret):
  246. """
  247. 乐橙云账号秘钥
  248. appSecret
  249. appId
  250. 使用乐橙云账号的appid和appSecret获取监控token
  251. 请求时数据格式
  252. {
  253. "id":"98a7a257-c4e4-4db3-a2d3-d97a3836b87c",
  254. "system":{
  255. "ver":"1.0",
  256. "appId":"lcdxxxxxxxxx",
  257. "sign":"b7e5bbcc6cc07941725d9ad318883d8e",
  258. "time":1599013514,
  259. "nonce":"fbf19fc6-17a1-4f73-a967-75eadbc805a2"},
  260. "params":{}
  261. }
  262. 签名原始串为:"time:1531401328,nonce:61f38836685b66f3201469543d8365f7,appSecret:12459ac547434b3ea83db5e6d56789"
  263. """
  264. # 先从redis 中获取token
  265. tokens = redis_pool.get(appId)
  266. if tokens and tokens !=None:
  267. redis_jk_data = eval(tokens)
  268. status = redis_jk_data.get("status",1)
  269. if status:
  270. # 查看到期时间
  271. expireTime = redis_pool.ttl(appId)
  272. # 设置到期时间 秒
  273. # redis_pool.expire('ttt', 10)
  274. redis_jk_data["result"]["data"]["expireTime"] = expireTime
  275. else:
  276. redis_jk_data = {"status":0}
  277. return redis_jk_data
  278. else:
  279. status = 0
  280. if not status:
  281. url = config.get("camera").get("lc_token")
  282. # 加密
  283. times,nonce,sign = md5value(appSecret)
  284. data = {
  285. "system":{
  286. "ver":"1.0",
  287. "appId":appId,
  288. "sign":sign,
  289. "time":times,
  290. "nonce":nonce
  291. },
  292. "id":nonce,
  293. "params":{
  294. }
  295. }
  296. token_data = requests.post(url,json=data, timeout=5)
  297. if token_data.status_code == 200:
  298. try:
  299. token_json_data = json.loads(token_data.text)
  300. expireTime = token_json_data["result"]["data"]["expireTime"]
  301. # status 1 代表获取token 成功 0失败
  302. token_json_data["status"] = 1
  303. except Exception as e:
  304. token_json_data = {"status":0}
  305. expireTime = 5
  306. else:
  307. token_json_data = {"status":0}
  308. expireTime = 5
  309. redis_pool.set(appId,token_json_data,expireTime)
  310. return token_json_data
  311. def device_config(appId,appSecret):
  312. """
  313. 配置项
  314. """
  315. time,nonce,sign = md5value(appSecret)
  316. token_data = deviceAccessToken(appId, appSecret)
  317. if token_data.get("status","0"):
  318. token = token_data["result"]["data"]["accessToken"]
  319. else:
  320. token = ""
  321. return time,nonce,sign,token
  322. def controlMove(appId,appSecret,deviceId,operation,channelId="0"):
  323. """
  324. 云台控制接口
  325. 请求样例:
  326. operation 0-上,1-下,2-左,3-右8-放大9-缩小10-停止
  327. {
  328. "id":"d5c287b4-5b2f-4f03-baf5-8032c5c354af",
  329. "system":{
  330. "ver":"1.0",
  331. "appId":"lcdxxxxxxxxx",
  332. "sign":"74bc756ebd53e9eef2836f8cf1730c10",
  333. "time":1599031074,
  334. "nonce":"8ec8a7bd1d1c95420de20d92422d457d"
  335. },
  336. "params":{
  337. "token":"At_00006acr3456d12312d3grf60147de7ec",
  338. "deviceId":"MEGREZ0000001842",
  339. "channelId":"0",
  340. "operation":"1",
  341. "duration":"1000" # 移动持续时间,单位毫秒
  342. }
  343. }
  344. """
  345. url = config.get("camera").get("lc_controler")
  346. time,nonce,sign,token = device_config(appId, appSecret)
  347. if not token:
  348. return {"msg":"控制失败"}
  349. data = {
  350. "system":{
  351. "ver":"1.0",
  352. "appId":appId,
  353. "sign":sign,
  354. "time":time,
  355. "nonce":nonce
  356. },
  357. "id":nonce,
  358. "params":{
  359. "token":token,
  360. "deviceId":deviceId,
  361. "channelId":channelId,
  362. "operation":operation,
  363. "duration":"1000"
  364. }
  365. }
  366. control_Move = requests.post(url,json=data)
  367. return control_Move.json()
  368. def expire_time(times):
  369. data_time = datetime.datetime.now()
  370. cultivate_time_expire = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(times))
  371. time1 = datetime.datetime.strptime(cultivate_time_expire,"%Y-%m-%d %H:%M:%S")
  372. num=(time1-data_time).days
  373. print("设备到期天数---",num)
  374. if int(num) <=7 and int(num) >= 0:
  375. print("即将到期")
  376. status = 2
  377. elif int(num) < 0:
  378. print("已到期")
  379. status = 1
  380. else:
  381. print("未到期")
  382. status = 0
  383. return status
  384. def get_center_lnglat(lnglats_list):
  385. x, y, z = 0, 0, 0
  386. length = len(lnglats_list)
  387. for n, a in lnglats_list:
  388. g, t = math.radians(float(n)), math.radians(float(a))
  389. x += math.cos(t) * math.cos(g)
  390. y += math.cos(t) * math.sin(g)
  391. z += math.sin(t)
  392. x = float(x / length)
  393. y = float(y / length)
  394. z = float(z / length)
  395. lng = round(math.degrees(math.atan2(y, x)), 4)
  396. lat = round(math.degrees(math.atan2(z, math.sqrt(x*x + y*y))), 4)
  397. return lng, lat
  398. def bindDeviceLive(appId,appSecret,deviceId,channelId="0"):
  399. """
  400. 获取直播地址
  401. """
  402. url = config.get("camera").get("lc_addr")
  403. time,nonce,sign,token = device_config(appId, appSecret)
  404. data = {
  405. "system":{
  406. "ver":"1.0",
  407. "appId":appId,
  408. "sign":sign,
  409. "time":time,
  410. "nonce":nonce
  411. },
  412. "id":nonce,
  413. "params":{
  414. "streamId":1,
  415. "deviceId":deviceId,
  416. "channelId":channelId,
  417. "token":token
  418. }
  419. }
  420. device_live_data = requests.post(url,json=data)
  421. return device_live_data.json()
  422. def getLive(appId,appSecret,deviceId,channelId="0"):
  423. """
  424. 查询监控地址 用于设备直播地址创建后再次查询使用
  425. """
  426. url = config.get("camera").get("lc_stream")
  427. time,nonce,sign,token = device_config(appId, appSecret)
  428. data = {
  429. "system":{
  430. "ver":"1.0",
  431. "appId":appId,
  432. "sign":sign,
  433. "time":time,
  434. "nonce":nonce
  435. },
  436. "id":nonce,
  437. "params":{
  438. "deviceId":deviceId,
  439. "channelId":channelId,
  440. "token":token
  441. }
  442. }
  443. live_data = requests.post(url,json=data)
  444. return live_data.json()
  445. if __name__ == "__main__":
  446. t = get_recent_month(1)
  447. print(t)