forecast_system.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. # -*- coding:utf-8 -*-
  2. # @Time : 2020/8/25 9.45 上午
  3. # @Author : Creat by cao
  4. import operator
  5. import json
  6. import time
  7. import os
  8. import requests
  9. import datetime
  10. import uuid
  11. import ast
  12. from django.conf import settings
  13. from smartfarming.api.views.forecast.all_dict import insect_dict, attract_discern
  14. from smartfarming.models.sim_card import MongoMsg_Conf
  15. from smartfarming.models.device import MongoDevice
  16. from smartfarming.models.worm_forecast import MongoCBDphoto, MongoCBDphoto_B, MongoCBDphoto_C
  17. from kedong.decoration import kedong_deco, PortError
  18. from .common import *
  19. from django.db.models import Q
  20. config_dict = settings.CONFIG
  21. @kedong_deco(login_required=True)
  22. def time_folder(request):
  23. """
  24. 测报灯/色诱/吸虫塔/性诱3.0隐藏时间文件夹接口
  25. device_id 必传(str) 设备id
  26. identify_model 必传(str) 识别模型AB
  27. 返回值:
  28. "data":[
  29. {
  30. "2021":{
  31. "10":[
  32. "14",
  33. "13",
  34. ],
  35. "09":[
  36. "30",
  37. "29",
  38. "28",
  39. "27",
  40. "16",
  41. "06"
  42. ]
  43. }
  44. }
  45. ],
  46. """
  47. device_id = request.POST.get('device_id')
  48. if not device_id:
  49. raise PortError("device_id", "未传设备号")
  50. try:
  51. device = MongoDevice.objects.get(device_id=device_id)
  52. except:
  53. raise PortError("", "设备号不对")
  54. myuser_type = request.user_type
  55. if device.device_type_id == 3:
  56. identify_model = request.POST.get("identify_model","A")
  57. if identify_model=="A":
  58. models = MongoCBDphoto
  59. elif identify_model=="B":
  60. models = MongoCBDphoto_B
  61. if not myuser_type == 1 and device.device_expire == "1":
  62. photo_list = models.objects.filter(device_id=device.id,photo_status=1,addtime__lte=int(device.device_expire_time)).order_by("-id")
  63. else:
  64. photo_list = models.objects.filter(device_id=device.id,photo_status=1).order_by("-id")
  65. else:
  66. raise PortError("","暂不支持的设备类型")
  67. repeat_data = []
  68. for i in photo_list:
  69. othertime = time.strftime("%Y-%m-%d", time.localtime(i.addtime))
  70. year,month,day = othertime.split("-")
  71. time_tup = year,month,day
  72. repeat_data.append(time_tup)
  73. data = list(set(repeat_data))
  74. data.sort(key=repeat_data.index)
  75. time_data = []
  76. year_list = []
  77. month_list = []
  78. crowbar = -1 #使用撬棍进行列表下标标识,因为数据时经过去重和排序的,所以可以进行。
  79. for time_i in data:
  80. year_time = time_i[0]
  81. month_time = time_i[1]
  82. day_time = time_i[2]
  83. if year_time in year_list:
  84. if year_time+month_time in month_list:
  85. time_data[crowbar][year_time][month_time].append(day_time)
  86. else:
  87. time_data[crowbar][year_time][month_time] = [day_time]
  88. month_list.append(year_time+month_time)
  89. else:
  90. year_list.append(year_time)
  91. month_list.append(year_time+month_time)
  92. month_dict = {month_time:[day_time]}
  93. time_data.append({year_time:month_dict})
  94. crowbar+=1
  95. return(time_data)
  96. @kedong_deco(login_required=True)
  97. def device_photo_details(request):
  98. """
  99. 色诱测报灯/测报灯/吸虫塔/性诱3.0/图片详情接口
  100. img_id 必传(str) 图片id
  101. cmd 非必传(str) cmd有值并且为sy时,是色诱测报图片列表接口,
  102. 为xct时,是吸虫塔图片列表,
  103. 为cbd是,是测报灯图片列表,
  104. 为xy_three 时, 是性诱3.0图片列表
  105. identify_model 非必传("A","B") cmd为cbd时,A是A模型,B是B模型
  106. 返回值:
  107. "data": {
  108. "device_id": "2631",
  109. "addtime": 1632413928,
  110. "addr": "http://bigdata-all.oss-accelerate.aliyuncs.com/Basics/cbd/867435059571471/2021/9/24/20210924001848354843.jpg",
  111. "ids": 86524,
  112. "mark": "",
  113. "label": "",
  114. "indentify_photo": "http://bigdata-all.oss-accelerate.aliyuncs.com/Result/cbd/867435059571471/2021/9/24/20210924001848354843.jpg",
  115. "indentify_result": "158,38#670,26#672,4"
  116. },
  117. """
  118. img_id = request.POST.get("img_id")
  119. try:
  120. imgs = MongoCBDphoto.objects.get(id=img_id)
  121. except:
  122. raise PortError("img_id", "未找到该图片id")
  123. label = imgs.label
  124. indentify_photo = imgs.indentify_photo
  125. indentify_result = imgs.indentify_result
  126. img_url = imgs.addr
  127. mark = imgs.mark
  128. if mark:
  129. mark = json.loads(mark)
  130. else:
  131. mark = []
  132. data= {
  133. "device_id":imgs.device_id,
  134. "addtime":imgs.addtime,
  135. "addr":img_url,
  136. "ids":imgs.id,
  137. "mark":mark,
  138. "indentify_photo":indentify_photo,
  139. "indentify_result":indentify_result,
  140. "label":label}
  141. return data
  142. @kedong_deco(login_required=True)
  143. def device_photo_list(request):
  144. """
  145. 测报灯图片展示接口
  146. device_id 必传(str) 设备id
  147. page 非必传(str) 页数
  148. page_number 非必传(num) 页面显示数据总数,默认10条
  149. time_begin 非必传(时间戳) 开始时间
  150. time_end 非必传(时间戳) 结束时间
  151. 返回值:
  152. "data": {
  153. "disable":0 禁用识别的状态 1 开启识别的状态,
  154. {
  155. '2021-04-09': [{
  156. 'device_id': '836',
  157. 'addtime': 1617936849,
  158. 'describe': '',
  159. 'addr': 'http://182.92.193.64:8003/Basics/cbd/866262046927462/2021/4/9/20210409105402642179.jpg',
  160. 'mark': None,
  161. 'id': 5877,
  162. 'add_time': '2021-04-09'
  163. }],
  164. '2021-04-08': [{
  165. 'device_id': '836',
  166. 'addtime': 1617867971,
  167. 'describe': '',
  168. 'addr': 'http://182.92.193.64:8003/Basics/cbd/866262046927462/2021/4/8/20210408154604657028.jpg',
  169. 'mark': None,
  170. 'id': 5810,
  171. 'add_time': '2021-04-08'
  172. }
  173. }
  174. """
  175. deviceas = request.POST
  176. device_id = deviceas.get("device_id")
  177. page = int(deviceas.get("page",1))
  178. time_begin = deviceas.get("time_begin")
  179. time_end = deviceas.get("time_end")
  180. page_number = int(deviceas.get("page_number",12))
  181. if not device_id:
  182. raise PortError("device_id", "未传设备号")
  183. try:
  184. device = MongoDevice.objects.get(device_id=device_id)
  185. except:
  186. raise PortError("", "设备号不对")
  187. data = []
  188. image_path = config_dict["image_url"]["image"]
  189. photo_list = MongoCBDphoto.objects.filter(device_id=device.id,photo_status=1).order_by("-id")
  190. if time_begin and time_begin.isdigit() and time_end.isdigit():
  191. photo_list = photo_list.filter(addtime__range=(int(time_begin),int(time_end)))
  192. num = photo_list.count()
  193. for i in photo_list[(page_number*(page-1)):(page*page_number)]:
  194. # 判断是否有手动标注结果
  195. if i.is_mark == 1:
  196. try:
  197. mark = ast.literal_eval(i.mark)
  198. except:
  199. mark = json.loads(i.mark)
  200. pest_counts = len(mark)
  201. else:
  202. indentify_result = "" if i.indentify_result == "0" else i.indentify_result
  203. pest_counts = sum([int(i.split(",")[1]) for i in indentify_result.split("#")]) if indentify_result else 0
  204. # TODO 展示图片暂时处理
  205. if str(i.addr).startswith('http'):
  206. img_url = i.addr
  207. else:
  208. img_url = image_path + i.addr
  209. if str(i.indentify_photo).startswith('http'):
  210. indentify_photo = i.indentify_photo
  211. else:
  212. indentify_photo = image_path + i.indentify_photo
  213. data.append({
  214. "device_id":i.device_id,
  215. "addtime":i.addtime,
  216. "describe":i.describe,
  217. "addr":img_url,
  218. "ids":i.id,
  219. "mark":i.mark,
  220. "pest_counts":pest_counts,
  221. "indentify_photo":indentify_photo,
  222. "indentify_result":i.indentify_result
  223. })
  224. return {"disable":device.disable,"data":data,"num":num}
  225. @kedong_deco(login_required=True)
  226. def equip_photo_del(request):
  227. """
  228. 测报灯/孢子仪/性诱/吸虫塔/性诱3.0图片删除接口
  229. 参数
  230. device_id 必传(str) 设备号
  231. addrlist 非必传(str) 图片列表
  232. addrlist没值删除所有的图片,有值就删除里面的值
  233. """
  234. deviceas = request.POST
  235. device_id = deviceas.get("device_id")
  236. img_list = deviceas.get("addrlist")
  237. if not device_id:
  238. raise PortError("", "未传设备号")
  239. try:
  240. device_ids = MongoDevice.objects.get(device_id=device_id)
  241. except:
  242. raise PortError("", "设备号不存在")
  243. img_list = eval(img_list)
  244. if device_ids.device_type_id == 3:
  245. modules = MongoCBDphoto
  246. if img_list:
  247. for i in img_list:
  248. try:
  249. modules.objects.filter(id=i).update(photo_status=4)
  250. except:
  251. raise PortError("device_id", "删除失败")
  252. else:
  253. try:
  254. modules.objects.filter(device_id=device_ids.id).update(photo_status=4)
  255. except:
  256. raise PortError("device_id", "删除失败")
  257. return True
  258. # 测报灯短信配置
  259. @kedong_deco(login_required=True)
  260. def cbd_msg_conf(request):
  261. """
  262. 测报灯害虫预警短信配置接口:
  263. 参数:
  264. device_id 必传(str) 设备号
  265. conf 非必传(str) 害虫配置信息
  266. 不传conf: 当前短信预警配置
  267. 传conf:修改短信预警配置
  268. """
  269. device_id = request.POST.get("device_id")
  270. if not device_id:
  271. raise PortError("device_id", "参数不对")
  272. uptime = int(time.time())
  273. conf = request.POST.get("conf")
  274. if conf:
  275. try:
  276. if MongoMsg_Conf.objects.filter(device_id=device_id).exists():
  277. msgconf = MongoMsg_Conf.objects.get(device_id=device_id)
  278. msgconf.conf = conf
  279. msgconf.save()
  280. else:
  281. MongoMsg_Conf.objects.create(device_id=device_id,conf=conf,uptime=uptime)
  282. except:
  283. raise PortError(" ", "保存失败")
  284. return True
  285. else:
  286. try:
  287. msgconf = MongoMsg_Conf.objects.get(device_id=device_id)
  288. data = msgconf.conf
  289. except:
  290. data = ""
  291. return data
  292. @kedong_deco(login_required=True)
  293. def equip_photo_discern(request):
  294. # 测报灯、吸虫塔、色诱测报害虫重新图片识别\详情\手动标注接口
  295. img_id = request.POST.get("img_id")
  296. ret = request.POST.get("ret")
  297. if ret == "again":
  298. # 手动标注
  299. # 获取该图片对象
  300. photo_obj = MongoCBDphoto.objects.filter(id=img_id)
  301. photo_obj = photo_obj.first() if photo_obj else None
  302. date = []
  303. if photo_obj:
  304. # 当图片对象存在
  305. addr = photo_obj.addr
  306. if addr:
  307. # 该图片对应设备的信息
  308. device = MongoDevice.objects.filter(id=photo_obj.device_id)
  309. device = device.first() if device else None
  310. # 获取图片本地路径
  311. img_content_url = f'{config_dict.get("image_url").get("image")}/media'
  312. media = f'{config_dict.get("media")}'
  313. if addr.startswith("http"):
  314. addr = addr.replace(img_content_url,media)
  315. else:
  316. addr = addr.replace("/media",media)
  317. print(addr, "--------")
  318. pass
  319. # 重新调用识别接口
  320. identify_url = config_dict.get("image_url").get("identify_url")
  321. if device.lng and device.lat:
  322. request_data = {
  323. "longitude": device.lng,
  324. "latitude": device.lat
  325. }
  326. else:
  327. request_data = {
  328. "longitude": "126.40548",
  329. "latitude": "47.82857"
  330. }
  331. if os.path.exists(addr):
  332. imageFile = {
  333. "imageFile": ('pic.jpg', open(addr, "rb"), 'image/jpeg')
  334. }
  335. res = requests.post(url=identify_url, data=request_data, files=imageFile, timeout=(10, 20))
  336. image_result = json.loads(res.text)
  337. try:
  338. if image_result.get("returnResult").get("returnStatus") != "0":
  339. returnString = image_result["returnResult"]["returnString"]
  340. returnImageUrl = image_result["returnResult"]["returnImageUrl"]
  341. returnCode = image_result["returnResult"].get("returnCode","")
  342. remote_content = requests.get(returnImageUrl).content
  343. indentify_photo = photo_obj.indentify_photo
  344. # 如果第一次识别图片存在
  345. if photo_obj:
  346. if indentify_photo.startswith("http"):
  347. indentify_photo = indentify_photo.replace(img_content_url,media)
  348. else:
  349. indentify_photo = indentify_photo.replace("/media",media)
  350. else:
  351. # 如果第一次识别图片不存在
  352. inden_path = os.path.join(media, f"result/cbd/{device.device_id}")
  353. os.makedirs(inden_path) if not os.path.exists(inden_path) else None
  354. stamp = int(datetime.now().timestamp())
  355. unique_id = uuid.uuid4()
  356. combined_id = str(stamp) + "-" + str(unique_id)
  357. indentify_photo = os.path.join(inden_path, f"{combined_id}.jpg")
  358. # 把原本地图片覆盖
  359. with open(indentify_photo, "wb") as f:
  360. f.write(remote_content)
  361. # 更新结果
  362. cbd_img = indentify_photo.replace(media, img_content_url)
  363. photo_obj.indentify_photo = cbd_img
  364. photo_obj.indentify_result = returnString
  365. photo_obj.label = returnCode
  366. photo_obj.save()
  367. pest_list = returnString.split("#")
  368. for i in pest_list:
  369. if i:
  370. res = i.split(",")
  371. nums = res[1] #数量
  372. number = res[0] #编号
  373. try:
  374. result_list = insect_dict[number]
  375. except:
  376. result_list = attract_discern[number]
  377. date.append({"nums":nums,"result_list":result_list,"number":number})
  378. dat = {"image":cbd_img,"result":date, "label": returnCode}
  379. print(dat)
  380. return dat
  381. else:
  382. return {"code": 2, "msg": "无识别结果"}
  383. except Exception as e:
  384. return {"code": 2, "msg": "无识别结果"}
  385. else:
  386. return {"code": 2, "msg": "参数范围越界"}
  387. @kedong_deco(login_required=True)
  388. def cbdphoto_receive(request):
  389. # 测报灯/色诱/吸虫塔/害虫图片手动添加标注接口:
  390. img_id = request.POST.get('img_id')
  391. mark = request.POST.get('mark')
  392. photo_obj = MongoCBDphoto.objects.get(id=img_id)
  393. photo_obj.is_mark = 1
  394. photo_obj.mark = mark
  395. photo_obj.save()
  396. return json.loads(mark)