utils.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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. def perms_pc_app(type_id=1000, perms_lst=[]):
  20. menu = "PC" if type_id == 1000 else "APP"
  21. parent_ids = []
  22. for p in perms_lst:
  23. # 先判断是否是父级菜单
  24. per_obj = UserPurview.objects.filter(id=int(p), menu=menu).first()
  25. if per_obj:
  26. if per_obj.parent_perm_id == 0:
  27. parent_ids.append(p)
  28. perm_lst = []
  29. for i in parent_ids:
  30. parent = UserPurview.objects.get(id=int(i), menu=menu)
  31. inner_parent = {
  32. "menu": parent.menu,
  33. "parent_perm_id": parent.parent_perm_id,
  34. "pur_id": parent.id,
  35. "purview_name": parent.purview_name,
  36. "url": parent.url
  37. }
  38. children_lst = []
  39. # 获取此父级菜单中所有的子菜单
  40. children = UserPurview.objects.filter(parent_perm_id=int(i), menu=menu)
  41. for child in children:
  42. if child.id in perms_lst:
  43. children_lst.append(
  44. {
  45. "menu": child.menu,
  46. "parent_perm_id": child.parent_perm_id,
  47. "pur_id": child.id,
  48. "purview_name": child.purview_name,
  49. "url": child.url
  50. }
  51. )
  52. if children_lst:
  53. inner_parent["children"] = children_lst
  54. perm_lst.append(inner_parent)
  55. return perm_lst
  56. def get_perm_list(device_user):
  57. id = device_user.role_id
  58. try:
  59. role = Role.objects.get(id=id)
  60. role_perm = role.role_perm
  61. perms_lst = [int(i) for i in role_perm.split(",")]
  62. pc_perm_lst = perms_pc_app(type_id=1000, perms_lst=perms_lst)
  63. app_perm_lst = perms_pc_app(type_id=2000, perms_lst=perms_lst)
  64. if pc_perm_lst and app_perm_lst:
  65. perm_lst = [
  66. {
  67. "menu": "",
  68. "parent_perm_id": 1000,
  69. "pur_id": 0,
  70. "purview_name": "登录PC端",
  71. "url": "",
  72. "children": pc_perm_lst
  73. },
  74. {
  75. "menu": "",
  76. "parent_perm_id": 2000,
  77. "pur_id": 0,
  78. "purview_name": "登录APP端",
  79. "url": "",
  80. "children": app_perm_lst
  81. }
  82. ]
  83. elif pc_perm_lst:
  84. perm_lst = [
  85. {
  86. "menu": "",
  87. "parent_perm_id": 1000,
  88. "pur_id": 0,
  89. "purview_name": "登录PC端",
  90. "url": "",
  91. "children": pc_perm_lst
  92. }
  93. ]
  94. elif app_perm_lst:
  95. perm_lst = [
  96. {
  97. "menu": "",
  98. "parent_perm_id": 2000,
  99. "pur_id": 0,
  100. "purview_name": "登录APP端",
  101. "url": "",
  102. "children": app_perm_lst
  103. }
  104. ]
  105. else:
  106. perm_lst = []
  107. mark = role.mark
  108. return perm_lst, mark
  109. except Exception as e:
  110. return [], ""
  111. def get_all_pers():
  112. role_perm = UserPurview.objects.all().values("id")
  113. perms_lst = []
  114. for i in role_perm:
  115. perms_lst.append(i.get("id"))
  116. pc_perm_lst = perms_pc_app(type_id=1000, perms_lst=perms_lst)
  117. app_perm_lst = perms_pc_app(type_id=2000, perms_lst=perms_lst)
  118. perm_lst = [
  119. {
  120. "menu": "",
  121. "parent_perm_id": 1000,
  122. "pur_id": 0,
  123. "purview_name": "登录PC端",
  124. "url": "",
  125. "children": pc_perm_lst
  126. },
  127. {
  128. "menu": "",
  129. "parent_perm_id": 2000,
  130. "pur_id": 0,
  131. "purview_name": "登录APP端",
  132. "url": "",
  133. "children": app_perm_lst
  134. }
  135. ]
  136. return perm_lst
  137. def get_captcha():
  138. """获取图片验证码
  139. return :
  140. 验证码字符串,验证码图片base64数据
  141. """
  142. chr_all = string.ascii_uppercase + string.digits
  143. chr_all = chr_all.replace('0', '').replace('1', '').replace('2', '').replace('O', '').replace('I', '')
  144. code_str = ''.join(random.sample(chr_all, 4))
  145. image = ImageCaptcha().generate_image(code_str)
  146. f = BytesIO()
  147. image.save(f, 'png')
  148. data = f.getvalue()
  149. f.close()
  150. encode_data = base64.b64encode(data)
  151. data = str(encode_data, encoding='utf-8')
  152. img_data = "data:image/jpeg;base64,{data}".format(data=data)
  153. return code_str, img_data
  154. def get_recent_month(num):
  155. # 获取最近N个月的时间戳
  156. end_time = datetime.now() # 结束时间,当前时间
  157. # 获取当前月份和年份
  158. current_month = end_time.month
  159. current_year = end_time.year
  160. # 计算开始时间
  161. start_month = current_month - num # 当前月份往前推N个月
  162. start_year = current_year
  163. if start_month <= 0: # 如果计算得到的月份为负数,则需要向前借位
  164. start_month += 12
  165. start_year -= 1
  166. # 获取开始时间所在月份的最后一天
  167. _, last_day = calendar.monthrange(start_year, start_month)
  168. start_time = datetime(start_year, start_month, last_day).timestamp()
  169. return start_time
  170. def get_addr_by_lag_lng(lat,lng):
  171. # 根据经纬度获取省市级
  172. is_success, province, city, district = False, "", "", ""
  173. try:
  174. # 使用腾讯接口
  175. 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)
  176. requests.adapters.DEFAULT_RETRIES = 5 # 增加重连次数
  177. s = requests.session()
  178. s.keep_alive = False # 关闭多余连接
  179. ret = s.get(url)
  180. rest = json.loads(ret.text)
  181. province = rest["result"]["ad_info"]["province"]
  182. city = rest["result"]["ad_info"]["city"]
  183. district = rest["result"]["ad_info"]["district"]
  184. is_success = True
  185. except Exception as e:
  186. logger.error(f"获取腾讯地理位置接口失败 {e.args}")
  187. if not is_success:
  188. try:
  189. # 使用百度接口
  190. url = "http://api.map.baidu.com/geocoder?location=%s,%s&output=json"%(lat,lng)
  191. requests.adapters.DEFAULT_RETRIES = 5 # 增加重连次数
  192. s = requests.session()
  193. s.keep_alive = False # 关闭多余连接
  194. ret = s.get(url)
  195. addr = json.loads(ret.text)
  196. province = addr["result"]["addressComponent"]["province"]
  197. city = addr["result"]["addressComponent"]["city"]
  198. district = addr["result"]["addressComponent"]["district"]
  199. is_success = True
  200. except Exception as e:
  201. logger.error(f"获取百度地理位置接口失败 {e.args}")
  202. return is_success, province, city, district
  203. # 获取天气数据
  204. def get_address_by_lntlat(lng, lat):
  205. province, city, district = "", "", ""
  206. try:
  207. key = "78ce288400f4fc6d9458989875c833c2"
  208. adcode_url = "http://restapi.amap.com/v3/geocode/regeo?key={key}&location={lng},{lat}&poitype=&radius=&" \
  209. "extensions=all&batch=false&roadlevel=0".format(key=key, lng=lng, lat=lat)
  210. res = requests.get(adcode_url)
  211. rsp = res.json()
  212. address_info = rsp['regeocode']['addressComponent']
  213. adcode = address_info['adcode']
  214. if adcode != "900000":
  215. province, city, district = address_info['province'], address_info['city'], address_info['district']
  216. if (not city) and district:
  217. city = district
  218. except Exception as e:
  219. pass
  220. return province, city, district
  221. # 获取天气相关信息
  222. def get_weather_info(lng=None, lat=None):
  223. data = {}
  224. if lng and lat:
  225. try:
  226. url = "http://114.115.147.140:8080/weather"
  227. res = requests.post(url, {"lat": lat, "lng": lng})
  228. result = res.json()
  229. if result['status'] == 'true':
  230. data = result['data']
  231. except Exception as e:
  232. pass
  233. return data
  234. def md5value(appSecret):
  235. """sign加密"""
  236. times = int(time.time())
  237. # 随机生成32位字符串
  238. nonce = ''.join(random.sample(string.ascii_letters + string.digits, 32))
  239. sign = "time:{},nonce:{},appSecret:{}".format(times, nonce, appSecret)
  240. input_name = hashlib.md5()
  241. input_name.update(sign.encode("utf-8"))
  242. sign = (input_name.hexdigest()).lower()
  243. return times,nonce,sign
  244. def deviceAccessToken(appId, appSecret):
  245. """
  246. 乐橙云账号秘钥
  247. appSecret
  248. appId
  249. 使用乐橙云账号的appid和appSecret获取监控token
  250. 请求时数据格式
  251. {
  252. "id":"98a7a257-c4e4-4db3-a2d3-d97a3836b87c",
  253. "system":{
  254. "ver":"1.0",
  255. "appId":"lcdxxxxxxxxx",
  256. "sign":"b7e5bbcc6cc07941725d9ad318883d8e",
  257. "time":1599013514,
  258. "nonce":"fbf19fc6-17a1-4f73-a967-75eadbc805a2"},
  259. "params":{}
  260. }
  261. 签名原始串为:"time:1531401328,nonce:61f38836685b66f3201469543d8365f7,appSecret:12459ac547434b3ea83db5e6d56789"
  262. """
  263. # 先从redis 中获取token
  264. tokens = redis_pool.get(appId)
  265. if tokens and tokens !=None:
  266. redis_jk_data = eval(tokens)
  267. status = redis_jk_data.get("status",1)
  268. if status:
  269. # 查看到期时间
  270. expireTime = redis_pool.ttl(appId)
  271. # 设置到期时间 秒
  272. # redis_pool.expire('ttt', 10)
  273. redis_jk_data["result"]["data"]["expireTime"] = expireTime
  274. else:
  275. redis_jk_data = {"status":0}
  276. return redis_jk_data
  277. else:
  278. status = 0
  279. if not status:
  280. url = "http://172.100.91.30/openapi/openapi/accessToken"
  281. # 加密
  282. times,nonce,sign = md5value(appSecret)
  283. data = {
  284. "system":{
  285. "ver":"1.0",
  286. "appId":appId,
  287. "sign":sign,
  288. "time":times,
  289. "nonce":nonce
  290. },
  291. "id":nonce,
  292. "params":{
  293. }
  294. }
  295. token_data = requests.post(url,json=data)
  296. if token_data.status_code == 200:
  297. try:
  298. token_json_data = json.loads(token_data.text)
  299. expireTime = token_json_data["result"]["data"]["expireTime"]
  300. # status 1 代表获取token 成功 0失败
  301. token_json_data["status"] = 1
  302. except Exception as e:
  303. token_json_data = {"status":0}
  304. expireTime = 5
  305. else:
  306. token_json_data = {"status":0}
  307. expireTime = 5
  308. redis_pool.set(appId,token_json_data,expireTime)
  309. return token_json_data
  310. def device_config(appId,appSecret):
  311. """
  312. 配置项
  313. """
  314. time,nonce,sign = md5value(appSecret)
  315. token_data = deviceAccessToken(appId, appSecret)
  316. if token_data.get("status","0"):
  317. token = token_data["result"]["data"]["accessToken"]
  318. else:
  319. token = ""
  320. return time,nonce,sign,token
  321. def controlMove(appId,appSecret,deviceId,operation,channelId="0"):
  322. """
  323. 云台控制接口
  324. 请求样例:
  325. operation 0-上,1-下,2-左,3-右8-放大9-缩小10-停止
  326. {
  327. "id":"d5c287b4-5b2f-4f03-baf5-8032c5c354af",
  328. "system":{
  329. "ver":"1.0",
  330. "appId":"lcdxxxxxxxxx",
  331. "sign":"74bc756ebd53e9eef2836f8cf1730c10",
  332. "time":1599031074,
  333. "nonce":"8ec8a7bd1d1c95420de20d92422d457d"
  334. },
  335. "params":{
  336. "token":"At_00006acr3456d12312d3grf60147de7ec",
  337. "deviceId":"MEGREZ0000001842",
  338. "channelId":"0",
  339. "operation":"1",
  340. "duration":"1000" # 移动持续时间,单位毫秒
  341. }
  342. }
  343. """
  344. url = "http://172.100.91.30/openapi/openapi/controlMovePTZ"
  345. time,nonce,sign,token = device_config(appId, appSecret)
  346. if not token:
  347. return {"msg":"控制失败"}
  348. data = {
  349. "system":{
  350. "ver":"1.0",
  351. "appId":appId,
  352. "sign":sign,
  353. "time":time,
  354. "nonce":nonce
  355. },
  356. "id":nonce,
  357. "params":{
  358. "token":token,
  359. "deviceId":deviceId,
  360. "channelId":channelId,
  361. "operation":operation,
  362. "duration":"1000"
  363. }
  364. }
  365. control_Move = requests.post(url,json=data)
  366. return control_Move.json()
  367. def expire_time(times):
  368. data_time = datetime.datetime.now()
  369. cultivate_time_expire = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(times))
  370. time1 = datetime.datetime.strptime(cultivate_time_expire,"%Y-%m-%d %H:%M:%S")
  371. num=(time1-data_time).days
  372. print("设备到期天数---",num)
  373. if int(num) <=7 and int(num) >= 0:
  374. print("即将到期")
  375. status = 2
  376. elif int(num) < 0:
  377. print("已到期")
  378. status = 1
  379. else:
  380. print("未到期")
  381. status = 0
  382. return status
  383. def get_center_lnglat(lnglats_list):
  384. x, y, z = 0, 0, 0
  385. length = len(lnglats_list)
  386. for n, a in lnglats_list:
  387. g, t = math.radians(float(n)), math.radians(float(a))
  388. x += math.cos(t) * math.cos(g)
  389. y += math.cos(t) * math.sin(g)
  390. z += math.sin(t)
  391. x = float(x / length)
  392. y = float(y / length)
  393. z = float(z / length)
  394. lng = round(math.degrees(math.atan2(y, x)), 4)
  395. lat = round(math.degrees(math.atan2(z, math.sqrt(x*x + y*y))), 4)
  396. return lng, lat
  397. if __name__ == "__main__":
  398. t = get_recent_month(1)
  399. print(t)