worm_lamp.py 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011
  1. import sys
  2. import json,os
  3. import logging
  4. from json import JSONDecodeError
  5. import pymysql
  6. from django.db.models import Sum, Max
  7. from django.conf import settings
  8. from django.core.paginator import Paginator
  9. from smartfarming.models.device import (
  10. MongoDevice,
  11. MongoCBDData,
  12. MongoBZYData,
  13. MongoSCDData,
  14. MongoXYCBData,
  15. DevicePestWarning,
  16. )
  17. from smartfarming.models.weather import QXZThresholdWarning
  18. from smartfarming.models.worm_forecast import MongoCBDphoto
  19. from smartfarming.api.views.forecast.all_dict import insect_dict, attract_discern
  20. from smartfarming.api.views.forecast.forecast_serializers import (
  21. MongoSCDDataSerializers,
  22. MongoCBDDataSerializers,
  23. MongoXYCBDataSerializers,
  24. MongoBZYDataSerializers
  25. )
  26. from kedong.decoration import kedong_deco, PortError
  27. from smartfarming.utils import expire_time
  28. config_dict = settings.CONFIG
  29. logger = logging.getLogger("myapp")
  30. config = {
  31. 'host': config_dict['bigdata']['mysql_host'],
  32. 'port': int(config_dict['bigdata']['mysql_port']),
  33. 'user': config_dict['bigdata']['mysql_user'],
  34. 'password': config_dict['bigdata']['mysql_password'],
  35. 'db': config_dict['bigdata']['mysql_db'],
  36. 'charset': 'utf8mb4',
  37. 'cursorclass': pymysql.cursors.DictCursor,
  38. }
  39. @kedong_deco(login_required=True)
  40. def lamp_list(request):
  41. """
  42. 设备列表的
  43. 测报系统 :虫情测报灯,孢子仪
  44. 参数:
  45. device_type_id 必传 (string) 测报系统的设备类型 3虫情测报灯 7孢子仪
  46. page 非必传(num) 页码,默认为1
  47. page_size 非必传(num) 每页数量, 不传默认为所有设备列表,一页展示全部,用与测报灯投屏, 传值代表每页数量
  48. device_id 非必传(string) 搜索项。设备id
  49. device_name 非必传(string) 搜索项。设备名称
  50. device_status 非必传(string) 搜索项。状态id
  51. 返回值:
  52. {
  53. "data": [
  54. {
  55. "device_name": "这里是设备名称", 设备名称
  56. "imei": "6886565004320786589", 设备id
  57. "is_online": 1, 0离线 1在线
  58. "addtime": 1590147148, 时间戳
  59. "dtype": "DCCBD-2_HK77" 设备型号/类型
  60. "address":'', 设备地址
  61. "cultivate_time": 培养液更换时间,
  62. "status_cul": 培养液状态 0未到期,1已到期,2即将到期,
  63. "glass_slide_time": 载玻片更换时间,
  64. "status_glass": 载玻状态 0未到期,1已到期,2即将到期
  65. }
  66. ],
  67. "errorCode": 0,
  68. "message": "",
  69. "formError": {}
  70. }
  71. """
  72. post_info = request.POST
  73. device_id = post_info.get('device_id','')
  74. device_name = post_info.get('device_name','')
  75. page = int(post_info.get('page', 1))
  76. page_size = post_info.get('page_size')
  77. device_model = post_info.get("device_model", '')
  78. device_status = post_info.get("device_status", '')
  79. device_code = ''
  80. try:
  81. type_id = int(post_info.get("device_type_id", ''))
  82. except Exception as e:
  83. raise PortError('device_type_id', '查看设备类型不存在')
  84. search_dict = {}
  85. search_dict["device_type_id"] = type_id
  86. devices = MongoDevice.objects.all().order_by('-device_status', '-addtime')
  87. if device_status:
  88. device_status = int(device_status)
  89. search_dict["device_status"] = device_status
  90. if device_id:
  91. devices = devices.filter(Q(device_id__icontains=device_id) | Q(device_name__icontains=device_id))
  92. if device_name:
  93. devices = devices.filter(device_name__icontains=device_name)
  94. if device_model:
  95. devices = devices.filter(device_model__icontains=device_model)
  96. devices = devices.filter(**search_dict) # 所有的测报灯
  97. counts = devices.count()
  98. if page_size:
  99. page_size = int(page_size)
  100. start = max((page - 1), 0) * page_size
  101. end = page * page_size
  102. devices = devices[start:end]
  103. data = []
  104. for i in devices:
  105. real_name = ""
  106. sale_user = ""
  107. device_model, device_code, decoy = "", "", ""
  108. xy_expire = "未设置诱芯到期时间"
  109. xy_uptime = 0
  110. if type_id == 4:
  111. device_model = i.device_model
  112. device_code = i.device_code
  113. decoy = i.decoy
  114. xy_uptime = i.xy_uptime
  115. xy_expire_time = i.xy_expire_time
  116. nowtime_stamp = int(time.time())
  117. if xy_expire_time == 0:
  118. xy_expire = "未设置诱芯到期时间"
  119. elif xy_expire_time !=0 and nowtime_stamp > xy_expire_time:
  120. xy_expire = "诱芯已经到期"
  121. elif xy_expire_time !=0 and (xy_expire_time-nowtime_stamp) <= 60*60*24*7:
  122. xy_expire = "诱芯即将到期,请注意更换"
  123. else:
  124. xy_expire = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(xy_expire_time))
  125. if xy_uptime == 0:
  126. xy_uptime = "暂无"
  127. else:
  128. xy_uptime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(xy_uptime))
  129. glass_slide_time = i.glass_slide_time
  130. cultivate_time = i.cultivate_time
  131. status_cul = ""
  132. status_glass = ""
  133. if type_id == 7:
  134. if cultivate_time:
  135. status_cul = expire_time(cultivate_time)
  136. if glass_slide_time:
  137. status_glass = expire_time(glass_slide_time)
  138. data.append({
  139. "d_id": i.id,
  140. "imei": i.device_id,
  141. "device_name": i.device_name,
  142. "is_online": i.device_status,
  143. "dtype": i.dver_num,
  144. "addtime": i.addtime,
  145. "uptime" : i.uptime,
  146. "device_code": device_code,
  147. "xy_expire": xy_expire,
  148. "xy_uptime": xy_uptime,
  149. "sale_user": sale_user,
  150. "device_model": device_model,
  151. "address": i.province + i.city + i.district,
  152. "lat": str(i.lat).strip('0'),
  153. "lng": str(i.lng).strip('0'),
  154. "decoy": decoy,
  155. "disable": i.disable,
  156. "real_name": real_name,
  157. "networking": i.networking,
  158. "equipment_status": i.equipment,
  159. "salesman_task_number": i.salesman_task_number,
  160. "device_expire_days": i.device_expire_days,
  161. "device_expire_time": i.device_expire_time,
  162. "device_expire": i.device_expire,
  163. "cultivate_time": cultivate_time,
  164. "status_cul": status_cul,
  165. "glass_slide_time": glass_slide_time,
  166. "status_glass": status_glass,
  167. })
  168. return {"data":data,"counts":counts}
  169. @kedong_deco(login_required=True)
  170. def device_status_data(request):
  171. """
  172. 虫情测报灯/数据详情
  173. 设备实时状态接口
  174. 参数:
  175. device_id 必传 设备id
  176. 返回值:
  177. "data": {
  178. "upds": 1, 上仓门状态 1打开,0关闭
  179. "tpl": 5, 低温保护阈值温度
  180. "dver": "1.0.0", 设备固件版本
  181. "gs": 0, 通道状态 1落虫,0排水
  182. "hs": 0, 加热状态 1加热,0正常
  183. "dnds": 0, 下仓门状态 1打开,0关闭
  184. "is_online": 0, 在线状态
  185. "csq": 29, 信号强度
  186. "tph": 70, 高温保护阈值温度
  187. "ts": 0 定时模式 0光控,1时控
  188. "tps": 1 温控状态 1 温控,0 正常
  189. "lps": 0 光控状态 1 光控,0 正常
  190. "hrt": 22 加热仓实时温度
  191. "device_name":"这里是设备名称",
  192. "address": "这里是设备位置",
  193. "iccid": 1234444 SIM卡号
  194. }
  195. """
  196. post_info = request.POST
  197. _device_id = post_info.get("device_id")
  198. if not _device_id:
  199. raise PortError('device_id', "该设备不存在")
  200. try:
  201. device = MongoDevice.objects.get(device_id=_device_id)
  202. except:
  203. raise PortError('device_id','暂无此设备')
  204. d_id = device.id
  205. device_name = device.device_name
  206. province = device.province
  207. city = device.city
  208. district = device.district
  209. device_status = device.device_status # 在线状态
  210. myuser_type = request.user_type
  211. device_datas = MongoCBDData.objects.filter(device_id=d_id).order_by('-id')
  212. try:
  213. device_data = json.loads(device_datas[0].device_data)
  214. except JSONDecodeError as e:
  215. device_data = eval(device_datas[0].device_data)
  216. except:
  217. raise PortError("device_id","暂无数据")
  218. ds = device_data.get("ds",1 )
  219. ts = device_data.get("ts",1)
  220. up_st = {
  221. "is_online": device_status,
  222. "ts":ts,
  223. "hs":device_data["hs"],
  224. "upds":device_data["upds"],
  225. "dnds":device_data["dnds"],
  226. "csq":device_data["csq"],
  227. "dver":device_data["dver"],
  228. "tph":device_data["tph"],
  229. "tpl":device_data["tpl"],
  230. "tps":device_data["tps"],
  231. "lps":device_data["lps"],
  232. "hrt":device_data["hrt"],
  233. "iccid":device_data["iccid"],
  234. "rps":device_data["rps"],
  235. "ah":device_data["ah"],
  236. "at":device_data["at"],
  237. "ds":ds,
  238. "device_name":device_name,
  239. "address": province + city + district,
  240. }
  241. return up_st
  242. @kedong_deco(login_required=True)
  243. def device_history_data(request):
  244. """
  245. 虫情测报灯/孢子仪 数据详情页面/列表展示
  246. """
  247. post_info = request.POST
  248. try:
  249. device_type_id = post_info.get("device_type_id")
  250. start_time = post_info.get('start_time')
  251. end_time = post_info.get('end_time')
  252. d_id = post_info.get("device_id")
  253. page_num = int(post_info.get('page', 1))
  254. page_size = int(post_info.get('page_size', 10))
  255. device = MongoDevice.objects.get(device_id=d_id)
  256. device_dict = {
  257. "2": [MongoSCDData, MongoSCDDataSerializers],
  258. "3": [MongoCBDData, MongoCBDDataSerializers],
  259. "4": [MongoXYCBData, MongoXYCBDataSerializers],
  260. "7": [MongoBZYData, MongoBZYDataSerializers]
  261. }
  262. models_type = device_dict.get(device_type_id)
  263. queryset = models_type[0].objects.filter(device_id=device.id).order_by("-addtime")
  264. if start_time and end_time:
  265. queryset = queryset.filter(addtime__gte=int(start_time),addtime__lte=int(end_time))
  266. total_obj = queryset.count()
  267. paginator = Paginator(queryset, page_size)
  268. page_obj = paginator.get_page(page_num)
  269. serializers = models_type[1](page_obj, many=True)
  270. return {
  271. "data": serializers.data,
  272. "counts": total_obj
  273. }
  274. except Exception as e:
  275. print(e)
  276. raise PortError('msg', "请联系管理员")
  277. @kedong_deco(login_required=True)
  278. def device_polyline_data(request):
  279. """
  280. 虫情测报灯/性诱测报/孢子仪/杀虫灯
  281. 数据详情-折线图接口
  282. """
  283. post_info = request.POST
  284. device_type_id = post_info.get("device_type_id")
  285. start_time = post_info.get('start_time')
  286. end_time = post_info.get('end_time')
  287. if not device_type_id:
  288. raise PortError("device_type_id", "没有对应型号设备")
  289. d_id = post_info.get("d_id")
  290. if not d_id:
  291. raise PortError('d_id', "请输入设备id")
  292. try:
  293. device = MongoDevice.objects.get(id=d_id)
  294. device_expire = device.device_expire
  295. device_expire_time = device. device_expire_time
  296. except:
  297. raise PortError('device_id',"暂无此设备")
  298. if device_type_id == "7":
  299. models = "sa_device_bzy_data"
  300. mode = MongoBZYData
  301. elif device_type_id == "4":
  302. models = "sa_device_xycb_data"
  303. mode = MongoXYCBData
  304. elif device_type_id == "2":
  305. models = "sa_device_scd_data"
  306. mode = MongoSCDData
  307. elif device_type_id == "3":
  308. models = "sa_device_cbd_data"
  309. mode = MongoCBDData
  310. else:
  311. raise PortError('device_id',"暂不支持该设备类型")
  312. counts = mode.objects.filter(device_id=d_id,addtime__range=(start_time,end_time)).count()
  313. limit = ""
  314. if counts >= 400:
  315. limit = "limit 400"
  316. else:
  317. limit = "limit {}".format(counts)
  318. connection = pymysql.connect(**config)
  319. cursor = connection.cursor()
  320. result = ""
  321. ath = []
  322. myuser_type = request.user_type
  323. if not myuser_type == 1 and device_expire == "1":
  324. if start_time and int(end_time) > int(device_expire_time):
  325. end_time = device_expire_time
  326. sql = 'select id,device_data,addtime from {} where device_id={} and addtime between {} and {} ORDER BY addtime {} '.format(models,d_id,start_time,end_time,limit)
  327. cursor.execute(sql)
  328. result = cursor.fetchall()
  329. else:
  330. if start_time:
  331. sql = 'select id,device_data,addtime FROM {} where device_id = {} and addtime between {} and {} ORDER BY addtime {}'.format(models,int(d_id),start_time,end_time,limit)
  332. #sql = 'select id,device_data,addtime from(select id,device_data,addtime from {} where device_id = {})as t where addtime between {} and {} ORDER BY id {}'.format(models,int(d_id),start_time,end_time,limit)
  333. # sql = 'select device_data, addtime from {} where device_id={} and addtime between {} and {}'.format(models,d_id,start_time,end_time)
  334. cursor.execute(sql)
  335. result = cursor.fetchall()
  336. if cursor:
  337. cursor.close()
  338. if connection:
  339. connection.close()
  340. if result:
  341. for i in result:
  342. d_t = eval(i['device_data'])
  343. try:
  344. temperature = d_t["at"]
  345. humidity = d_t["ah"]
  346. except:
  347. temperature = 0
  348. humidity = 0
  349. try:
  350. new_tem = d_t["new_tem"]
  351. new_hum = d_t["new_hum"]
  352. except:
  353. new_tem = ""
  354. new_hum = ""
  355. if device_type_id == "4":
  356. new_tem = d_t["at"]
  357. new_hum = d_t["ah"]
  358. others = ''
  359. set_temp = ''
  360. if device_type_id == '3':
  361. try:
  362. others = d_t["hrt"]
  363. except:
  364. continue
  365. elif device_type_id == '2':
  366. try:
  367. others = {
  368. "ct": d_t["ct"],
  369. "cv": d_t["cv"],
  370. "bv": d_t["bv"],
  371. }
  372. except:
  373. others = {
  374. "ct": "0",
  375. "cv": "13.905",
  376. "bv": "13.227",
  377. }
  378. elif device_type_id == '7':
  379. try:
  380. others = d_t["pre_temp"]
  381. set_temp = d_t["set_temp"]
  382. except:
  383. others = "0"
  384. set_temp = "0"
  385. elif device_type_id == '4':
  386. try:
  387. others = {
  388. "wind_drec":d_t["wind_drec"],
  389. "wind_sped":d_t["wind_sped"],
  390. }
  391. except:
  392. try:
  393. others = {
  394. "volt_ct":d_t["volt_ct"],
  395. "infr_ct":d_t["infr_ct"],
  396. }
  397. except:
  398. raise PortError('device_id',"该设备数据出错")
  399. elif device_type_id == "9":
  400. others = d_t["csq"]
  401. ath.append({
  402. "temperature":temperature,
  403. "humidity":humidity,
  404. "others":others,
  405. "addtime": i["addtime"],
  406. "set_temp":set_temp,
  407. "new_tem": new_tem,
  408. "new_hum":new_hum,
  409. })
  410. return ath
  411. @kedong_deco(login_required=True)
  412. def pest_raise_info(request):
  413. """
  414. 害虫统计页面
  415. 害虫浮现日期
  416. 参数:
  417. d_ids 必传 设备自增ID
  418. identify_model 必传 识别模型('A'为识别模型A,'B'为识别模型B)
  419. year 必传 年份
  420. amend 必传 机器'0'或者人为'1',不传默认为'0'机器识别
  421. return:
  422. data返回值字段,pest_info害虫信息,pest_list害虫列表
  423. "data": {
  424. "pest_info": {
  425. "棉铃虫": {
  426. "startTime": "2022-07-07",
  427. "highTime": "2022-07-12",
  428. "endTime": "2022-07-12",
  429. "highNum": 29
  430. },
  431. ...
  432. },
  433. "pest_list": [
  434. "棉铃虫",
  435. "东方粘虫",
  436. "小地老虎",
  437. "铜绿丽金龟",
  438. "黄褐丽金龟"
  439. ]
  440. }
  441. """
  442. parameters = request.POST
  443. d_ids = parameters.get("d_ids")
  444. year = parameters.get("year")
  445. amend = parameters.get("amend","0")
  446. # 获取统计设备列表
  447. if d_ids:
  448. d_id_list = [int(d_id) for d_id in d_ids.split(",")]
  449. else:
  450. raise PortError("d_ids","参数缺失")
  451. # 获取年份位于时间戳段
  452. start_date = year+"-01-01 00:00:00"
  453. end_date = year+"-12-31 23:59:59"
  454. start_time = time.strptime(start_date,"%Y-%m-%d %H:%M:%S")
  455. end_time = time.strptime(end_date,"%Y-%m-%d %H:%M:%S")
  456. start_stamp = int(time.mktime(start_time))
  457. end_stamp = int(time.mktime(end_time))
  458. # 统计
  459. photo_queryset = MongoCBDphoto.objects.filter(device_id__in=d_id_list,photo_status=1,addtime__range=(start_stamp,end_stamp))
  460. if amend == "0":
  461. photo_queryset = photo_queryset.filter(~Q(indentify_result="")).order_by("addtime")
  462. else:
  463. photo_queryset = photo_queryset.filter(~Q(indentify_result="") | ~Q(mark="")).order_by("addtime")
  464. pest_info = {}
  465. pest_day_info = {}
  466. time_recording = 0
  467. for photo_object in photo_queryset:
  468. addtime = photo_object.addtime
  469. time_serialize = time.strftime("%Y-%m-%d",time.localtime(addtime))
  470. # 按天归档
  471. if time_serialize != time_recording:
  472. for pest_day_key,pest_day_value in pest_day_info.items():
  473. if pest_day_key in pest_info:
  474. pest_info[pest_day_key]["endTime"] = pest_day_value["endTime"]
  475. if pest_day_value["highNum"] >= pest_info[pest_day_key]["highNum"]:
  476. pest_info[pest_day_key]["highTime"] = pest_day_value["highTime"]
  477. pest_info[pest_day_key]["highNum"] = pest_day_value["highNum"]
  478. else:
  479. pest_info[pest_day_key] = pest_day_value
  480. pest_day_info.clear()
  481. time_recording = time_serialize
  482. # 单张照片结果
  483. indentify_result = photo_object.indentify_result
  484. mark = photo_object.mark
  485. if amend == "1" and mark:
  486. mark = json.loads(mark)
  487. for label in mark:
  488. pest_name = label.get("text")
  489. pest_num = 1
  490. if pest_name in pest_day_info:
  491. pest_day_info[pest_name]["highNum"] += pest_num
  492. else:
  493. pest_day_info[pest_name] = {"startTime":time_serialize,"highTime":time_serialize,"endTime":time_serialize,"highNum":pest_num}
  494. else:
  495. for result in indentify_result.split("#"):
  496. tuple_result = result.split(",")
  497. if len(tuple_result) == 2:
  498. pest_name = insect_dict.get(tuple_result[0],"未命名")
  499. pest_num = int(tuple_result[1])
  500. if pest_name in pest_day_info:
  501. pest_day_info[pest_name]["highNum"] += pest_num
  502. else:
  503. pest_day_info[pest_name] = {"startTime":time_serialize,"highTime":time_serialize,"endTime":time_serialize,"highNum":pest_num}
  504. # 最后一天的数据统计,循环内加不了
  505. for pest_day_key,pest_day_value in pest_day_info.items():
  506. if pest_day_key in pest_info:
  507. pest_info[pest_day_key]["endTime"] = pest_day_value["endTime"]
  508. if pest_day_value["highNum"] >= pest_info[pest_day_key]["highNum"]:
  509. pest_info[pest_day_key]["highTime"] = pest_day_value["highTime"]
  510. pest_info[pest_day_key]["highNum"] = pest_day_value["highNum"]
  511. else:
  512. pest_info[pest_day_key] = pest_day_value
  513. return {"pest_info":pest_info,"pest_list":list(pest_info.keys())}
  514. @kedong_deco(login_required=True)
  515. def pest_statistics_char_new(request):
  516. """
  517. 害虫统计页面
  518. 害虫变化趋势折线图
  519. 参数:
  520. d_ids 必传 设备自增ID
  521. amend 必传 机器'0'或者人为'1',不传默认为'0'机器识别
  522. start_time 必传(string 秒级时间戳) 开始时间 (用于时间搜索)
  523. end_time 必传(string 秒级时间戳) 结束时间 (用于时间所有)
  524. 返回值:
  525. 单台设备会有at,ah,多台设备情况下不会有at,ah
  526. "data": {
  527. "char_data": {
  528. "棉铃虫": [
  529. {
  530. "addtime": 1657123200,
  531. "sum": 29,
  532. "at": 24,
  533. "ah": 38
  534. },
  535. ...
  536. ],
  537. ...
  538. },
  539. "pest_total": {
  540. "蓝目天蛾": 1,
  541. "黑绒绢金龟": 1,
  542. "瓢虫": 1,
  543. "铜绿丽金龟": 3,
  544. "黄褐丽金龟": 3,
  545. "小地老虎": 6,
  546. "东方粘虫": 66,
  547. "棉铃虫": 87
  548. },
  549. "at_ah_info": [
  550. {
  551. "addtime": 1657123200,
  552. "at": 24,
  553. "ah": 38
  554. },
  555. ...
  556. ]
  557. },
  558. """
  559. parameters = request.POST
  560. d_ids = parameters.get("d_ids")
  561. start_time = int(parameters.get("start_time"))
  562. end_time = int(parameters.get("end_time"))
  563. amend = parameters.get("amend","0")
  564. # 获取统计设备列表
  565. if d_ids:
  566. d_id_list = [int(d_id) for d_id in d_ids.split(",")]
  567. else:
  568. raise PortError("d_ids","参数缺失")
  569. # 统计
  570. photo_queryset = MongoCBDphoto.objects.filter(device_id__in=d_id_list,photo_status=1,addtime__range=(start_time,end_time))
  571. if amend == "0":
  572. photo_queryset = photo_queryset.filter(~Q(indentify_result="")).order_by("addtime")
  573. else:
  574. photo_queryset = photo_queryset.filter(~Q(indentify_result="") | ~Q(mark="")).order_by("addtime")
  575. chart_info = {}
  576. pest_day_info = {}
  577. at_day_info = []
  578. ah_day_info = []
  579. at_ah_info = []
  580. pest_info_total = {}
  581. time_recording = 0
  582. for photo_object in photo_queryset:
  583. addtime = photo_object.addtime
  584. time_date = time.strftime("%Y-%m-%d",time.localtime(addtime))
  585. date_stamp = int(time.mktime(time.strptime(time_date,"%Y-%m-%d")))
  586. # 按天归档
  587. if date_stamp != time_recording:
  588. for pest_day_key,pest_day_value in pest_day_info.items():
  589. if pest_day_key in chart_info:
  590. chart_info[pest_day_key].append(pest_day_value)
  591. else:
  592. chart_info[pest_day_key] = []
  593. chart_info[pest_day_key].append(pest_day_value)
  594. if len(d_id_list) == 1: # 单台设备可以来获取温湿度,多台设备不能获取温湿度
  595. if time_recording != 0:
  596. at_avg = int(sum(at_day_info)//len(at_day_info)) if len(at_day_info)!=0 else 25
  597. ah_avg = int(sum(ah_day_info)//len(ah_day_info)) if len(ah_day_info)!=0 else 30
  598. at_ah_info.append({"addtime":time_recording,"at":at_avg,"ah":ah_avg})
  599. pest_day_info.clear()
  600. at_day_info.clear()
  601. ah_day_info.clear()
  602. time_recording = date_stamp
  603. # 单张照片结果
  604. if len(d_id_list) == 1:
  605. at = eval(photo_object.at) if photo_object.at else 0
  606. ah = eval(photo_object.ah) if photo_object.ah else 0
  607. if at != 0:
  608. at_day_info.append(at)
  609. if ah != 0:
  610. ah_day_info.append(ah)
  611. indentify_result = photo_object.indentify_result
  612. mark = photo_object.mark
  613. if amend == "1" and mark:
  614. mark = json.loads(mark)
  615. for label in mark:
  616. pest_name = label.get("text")
  617. pest_num = 1
  618. if pest_name in pest_day_info:
  619. pest_day_info[pest_name]["sum"] += pest_num
  620. else:
  621. pest_day_info[pest_name] = {"addtime":date_stamp,"sum":pest_num}
  622. if pest_name in pest_info_total:
  623. pest_info_total[pest_name] += pest_num
  624. else:
  625. pest_info_total[pest_name] = pest_num
  626. else:
  627. for result in indentify_result.split("#"):
  628. tuple_result = result.split(",")
  629. if len(tuple_result) >= 2:
  630. try:
  631. pest_name = insect_dict.get(tuple_result[0],"未命名")
  632. pest_num = int(tuple_result[1])
  633. if pest_name in pest_day_info:
  634. pest_day_info[pest_name]["sum"] += pest_num
  635. else:
  636. pest_day_info[pest_name] = {"addtime":date_stamp,"sum":pest_num}
  637. if pest_name in pest_info_total:
  638. pest_info_total[pest_name] += pest_num
  639. else:
  640. pest_info_total[pest_name] = pest_num
  641. except Exception as e:
  642. logger.error(f'虫情分析errorlogger.error(f"{result} {tuple_result} {e} {photo_object.id}")')
  643. # 最后一天的数据统计,循环内加不了
  644. for pest_day_key,pest_day_value in pest_day_info.items():
  645. if pest_day_key in chart_info:
  646. chart_info[pest_day_key].append(pest_day_value)
  647. else:
  648. chart_info[pest_day_key] = []
  649. chart_info[pest_day_key].append(pest_day_value)
  650. if len(d_id_list) == 1: # 单台设备可以来获取温湿度,多台设备不能获取温湿度
  651. if time_recording != 0:
  652. at_avg = int(sum(at_day_info)//len(at_day_info)) if len(at_day_info)!=0 else 25
  653. ah_avg = int(sum(ah_day_info)//len(ah_day_info)) if len(ah_day_info)!=0 else 30
  654. at_ah_info.append({"addtime":time_recording,"at":at_avg,"ah":ah_avg})
  655. # 字典排序
  656. pest_info_total = dict(sorted(pest_info_total.items(),key=lambda x:x[1],reverse=False))
  657. data = {"char_data":chart_info,"pest_total":pest_info_total}
  658. if len(d_id_list) == 1:
  659. data["at_ah_info"] = at_ah_info
  660. return data
  661. @kedong_deco(login_required=True)
  662. def pest_image_source(request):
  663. """
  664. 害虫统计页面
  665. 害虫溯源图片接口
  666. 参数:
  667. d_ids 必传 设备自增ID
  668. identify_model 必传 识别模型('A'为识别模型A,'B'为识别模型B)
  669. amend 必传 机器'0'或者人为'1',不传默认为'0'机器识别
  670. start_time 必传(string 秒级时间戳) 开始时间 (用于时间搜索)
  671. end_time 必传(string 秒级时间戳) 结束时间 (用于时间所有)
  672. pest_name 非必传 用于筛选项,有则查,无则全部,害虫名字
  673. page 非必传 页码 不传默认为1
  674. page_size 非必传 数据条数 默认为10
  675. 返回值:
  676. data": {
  677. "pest_image_data": [
  678. {
  679. "deviceId": "862285038174052",
  680. "deviceName": "测报灯",
  681. "pestName": "蓝目天蛾、黑绒绢金龟、瓢虫",
  682. "addtime": 1658246342,
  683. "location": "云南省昆明市呈贡区",
  684. "img_url": "https://bigdata-all.oss-cn-beijing.aliyuncs.com/Basics/cbd/620210630173657/2022/1/7/30.jpg",
  685. "indentify_photo": "http://bigdata-all.oss-accelerate.aliyuncs.com/Result/cbd/620210630173657/2022/1/7/30.jpg",
  686. "pest_dict": {
  687. "蓝目天蛾": "1",
  688. "黑绒绢金龟": "1",
  689. "瓢虫": "1"
  690. }
  691. }
  692. ],
  693. "total_count": 1,
  694. "current_count": 1
  695. }
  696. """
  697. parameters = request.POST
  698. d_ids = parameters.get("d_ids")
  699. start_time = int(parameters.get("start_time"))
  700. end_time = int(parameters.get("end_time"))
  701. select_name = parameters.get("pest_name")
  702. page = int(parameters.get("page","1"))
  703. page_size = int(parameters.get("page_size","10"))
  704. amend = parameters.get("amend","0")
  705. # 获取统计设备列表
  706. if d_ids:
  707. d_id_list = [int(d_id) for d_id in d_ids.split(",")]
  708. d_id_dicts = {}
  709. device_queryset = MongoDevice.objects.filter(id__in=d_id_list)
  710. for device_object in device_queryset:
  711. d_id_dicts[device_object.id] = {"location":device_object.province+device_object.city+device_object.district,
  712. "device_id":device_object.device_id,
  713. "device_code":device_object.device_code,
  714. "device_name":device_object.device_name if device_object.device_name else "测报灯"
  715. }
  716. else:
  717. raise PortError("d_ids","参数缺失")
  718. # 统计
  719. photo_queryset = MongoCBDphoto.objects.filter(device_id__in=list(d_id_dicts.keys()),photo_status=1,addtime__range=(start_time,end_time))
  720. if amend == "0":
  721. photo_queryset = photo_queryset.filter(~Q(indentify_result="")).order_by("-addtime")
  722. else:
  723. photo_queryset = photo_queryset.filter(~Q(indentify_result="") | ~Q(mark="")).order_by("-addtime")
  724. pest_image_data = []
  725. for photo_object in photo_queryset:
  726. # 单张照片结果
  727. indentify_result = photo_object.indentify_result
  728. mark = photo_object.mark
  729. pest_string = ""
  730. pest_dict = {}
  731. if amend == "1" and mark:
  732. if mark == "[]":
  733. continue
  734. else:
  735. mark = json.loads(mark)
  736. for index,label in enumerate(mark):
  737. pest_name = label.get("text")
  738. pest_num = 1
  739. if pest_name not in pest_string:
  740. if index != 0:
  741. pest_string += "、"
  742. pest_string += pest_name
  743. if pest_name in pest_dict:
  744. pest_dict[pest_name] += pest_num
  745. else:
  746. pest_dict[pest_name] = 1
  747. else:
  748. for index,result in enumerate(indentify_result.split("#")) :
  749. if index != 0:
  750. pest_string += "、"
  751. tuple_result = result.split(",")
  752. if len(tuple_result) >= 2:
  753. pest_name = insect_dict.get(tuple_result[0],"未命名")
  754. pest_string+=pest_name
  755. pest_dict[pest_name] = int(tuple_result[1])
  756. if select_name and select_name not in pest_string:
  757. continue
  758. addtime = photo_object.addtime
  759. __d_id = int(photo_object.device_id)
  760. device_code = d_id_dicts[__d_id]["device_code"]
  761. pest_image_data.append({"deviceId":d_id_dicts[__d_id]["device_id"],
  762. "deviceName":d_id_dicts[__d_id]["device_name"],
  763. "pestName":pest_string,
  764. "addtime":addtime,
  765. "location":d_id_dicts[__d_id]["location"],
  766. "img_url":photo_object.addr,
  767. "indentify_photo":photo_object.indentify_photo,
  768. "pest_dict":pest_dict
  769. })
  770. return_data = pest_image_data[(page-1)*page_size:page*page_size]
  771. return {"pest_image_data":return_data,"total_count":len(pest_image_data),"current_count":len(return_data)}
  772. @kedong_deco(login_required=True)
  773. def pest_base_data(request):
  774. """
  775. 害虫统计页面
  776. 虫害基础数据接口
  777. 参数:
  778. d_id 必传 设备自增ID
  779. identify_model 必传 识别模型('A'为识别模型A,'B'为识别模型B)
  780. amend 必传 机器'0'或者人为'1',不传默认为'0'机器识别
  781. start_time 必传(string 秒级时间戳) 开始时间 (用于时间搜索)
  782. end_time 必传(string 秒级时间戳) 结束时间 (用于时间所有)
  783. pest_name 非必传 用于筛选项,有则查,无则全部,害虫名字
  784. page 非必传 页码 不传默认为1
  785. page_size 非必传 数据条数 默认为10
  786. 返回值:
  787. "data": {
  788. "pest_image_data": [
  789. {
  790. "pest_name": "瓢虫",
  791. "pest_num": 1,
  792. "addtime": 1658246342
  793. }
  794. ],
  795. "total_count": 1,
  796. "current_count": 1
  797. }
  798. """
  799. parameters = request.POST
  800. d_ids = parameters.get("d_ids")
  801. start_time = int(parameters.get("start_time"))
  802. end_time = int(parameters.get("end_time"))
  803. select_name = parameters.get("pest_name")
  804. page = int(parameters.get("page","1"))
  805. page_size = int(parameters.get("page_size",10))
  806. amend = parameters.get("amend","0")
  807. # 获取统计设备列表
  808. if d_ids:
  809. d_id_list = [int(d_id) for d_id in d_ids.split(",")]
  810. else:
  811. raise PortError("d_ids","参数缺失")
  812. # 统计
  813. photo_queryset = MongoCBDphoto.objects.filter(device_id__in=d_id_list,photo_status=1,addtime__range=(start_time,end_time))
  814. if amend == "0":
  815. photo_queryset = photo_queryset.filter(~Q(indentify_result="")).order_by("-addtime")
  816. else:
  817. photo_queryset = photo_queryset.filter(~Q(indentify_result="") | ~Q(mark="")).order_by("-addtime")
  818. pest_base_data = []
  819. for photo_object in photo_queryset:
  820. # 单张照片结果
  821. indentify_result = photo_object.indentify_result
  822. mark = photo_object.mark
  823. addtime = photo_object.addtime
  824. pest_dict = {}
  825. if amend == "1" and mark:
  826. mark = json.loads(mark)
  827. for label in mark:
  828. pest_name = label.get("text")
  829. pest_num = 1
  830. if select_name and select_name not in pest_name:
  831. continue
  832. if pest_name in pest_dict:
  833. pest_dict[pest_name] += pest_num
  834. else:
  835. pest_dict[pest_name] = pest_num
  836. for label_key,label_value in pest_dict.items():
  837. pest_base_data.append(dict(pest_name=label_key,pest_num=label_value,addtime=addtime))
  838. else:
  839. for result in indentify_result.split("#"):
  840. tuple_result = result.split(",")
  841. if len(tuple_result) >= 2:
  842. pest_name = insect_dict.get(tuple_result[0],"未命名")
  843. if select_name and select_name not in pest_name:
  844. continue
  845. pest_num = int(tuple_result[1])
  846. pest_dict=dict(pest_name=pest_name,pest_num=pest_num,addtime=addtime)
  847. pest_base_data.append(pest_dict)
  848. return_data = pest_base_data[(page-1)*page_size:page*page_size]
  849. return {"pest_image_data":return_data,"total_count":len(pest_base_data),"current_count":len(return_data)}
  850. def pest_enumeration(request):
  851. """
  852. 虫情地图
  853. 指定时间段内害虫列举接口
  854. 参数:
  855. start_time 必传(秒级时间戳) 开始时间
  856. end_time 必传(秒级时间戳) 结束时间
  857. 返回:
  858. {
  859. "data": ["杨二尾舟蛾","劳氏粘虫", ...]
  860. }
  861. """
  862. parameters = request.POST
  863. start_time = parameters.get("start_time")
  864. end_time = parameters.get("end_time")
  865. if start_time:
  866. start_time = int(start_time)
  867. else:
  868. raise PortError("start_time","参数缺失")
  869. if end_time:
  870. end_time = int(end_time)
  871. else:
  872. raise PortError("end_time","参数缺失")
  873. pest_cursor = Pest_distribute.objects.filter(uptime__gte=start_time, uptime__lte=end_time).values("pest_name")
  874. pest_name_lists = [pest_obj["pest_name"] for pest_obj in pest_cursor]
  875. return pest_name_lists
  876. def pest_tendency(request):
  877. """
  878. 虫情地图
  879. 虫情趋势接口
  880. 参数:
  881. pest_name 必传(str) 害虫名称
  882. req 必传(str) 筛选条件('start':始见期,'end':终见期,'focus':高峰期)
  883. start_time 必传(秒级时间戳) 开始时间
  884. end_time 必传(秒级时间戳) 结束时间
  885. 返回:
  886. {
  887. "data": [
  888. {
  889. "province": "广东省",
  890. "city": "揭阳市",
  891. "uptime": 1659801600
  892. },
  893. {
  894. "province": "辽宁省",
  895. "city": "沈阳市",
  896. "uptime": 1659715200
  897. },
  898. ...
  899. ]
  900. }
  901. """
  902. parameters = request.POST
  903. pest_name = parameters.get("pest_name")
  904. start_time = parameters.get("start_time")
  905. end_time = parameters.get("end_time")
  906. if not pest_name:
  907. raise PortError("pest_name","参数缺失")
  908. if start_time:
  909. start_time = int(start_time)
  910. else:
  911. raise PortError("start_time","参数缺失")
  912. if end_time:
  913. end_time = int(end_time)
  914. else:
  915. raise PortError("end_time","参数缺失")
  916. req = parameters.get("req")
  917. if req == "start":
  918. req_sort = {"uptime": 1}
  919. elif req == "end":
  920. req_sort = {"uptime": -1}
  921. elif req == "focus":
  922. req_sort = {"avg_num": -1}
  923. else:
  924. raise PortError("req","参数异常")
  925. pest_cursor = Pest_distribute.objects.filter(
  926. pest_name=pest_name, uptime__gte=start_time, uptime_lte=end_time).values(
  927. "province", "city").annotate(pest_count=Max("uptime")).values("province", "city", "uptime").order_by('-uptime')
  928. data = [pest_obj for pest_obj in pest_cursor]
  929. return data
  930. def pest_distribution(request):
  931. """
  932. 虫情地图
  933. 虫情密度 地域分布接口
  934. 参数:
  935. pest_name 必传(str) 害虫名称
  936. start_time 必传(秒级时间戳) 开始时间
  937. end_time 必传(秒级时间戳) 结束时间
  938. 返回:
  939. {
  940. "data":[
  941. {
  942. "province": "江苏省",
  943. "city": "淮安市",
  944. "pest_count": 4.33
  945. },
  946. {
  947. "province": "四川省",
  948. "city": "达州市",
  949. "pest_count": 3.0
  950. },
  951. ...
  952. ]
  953. }
  954. """
  955. parameters = request.POST
  956. pest_name = parameters.get("pest_name")
  957. start_time = parameters.get("start_time")
  958. end_time = parameters.get("end_time")
  959. if not pest_name:
  960. raise PortError("pest_name","参数缺失")
  961. if start_time:
  962. start_time = int(start_time)
  963. else:
  964. raise PortError("start_time","参数缺失")
  965. if end_time:
  966. end_time = int(end_time)
  967. else:
  968. raise PortError("end_time","参数缺失")
  969. pest_cursor = Pest_distribute.objects.filter(
  970. pest_name=pest_name, uptime__gte=start_time, uptime_lte=end_time).values(
  971. "province", "city").annotate(pest_count=Sum("pest_count")).values(
  972. "province", "city", "pest_count")
  973. data = []
  974. for pest_obj in pest_cursor:
  975. pest_obj["pest_count"] = round(pest_obj["pest_count"],2)
  976. data.append(pest_obj)
  977. return data
  978. def pest_statistics(request):
  979. """
  980. 害虫统计页面
  981. 害虫变化趋势折线图
  982. 参数:
  983. d_id 必传 设备自增id
  984. start_time 非必传(string 时间戳) 开始时间 (用于时间搜索)
  985. end_time 非必传(string 时间戳) 结束时间 (用于时间搜索)
  986. pest_name 非必传(str) 害虫名称
  987. 返回值:
  988. "broken_line": [
  989. {
  990. "addtime": 1590230292, 时间
  991. "temperature": 39.8, 温度
  992. "humidity": 34.9, 湿度
  993. "_sums": 17 这个时间点的害虫总数
  994. "_sname": 蛾子 害虫名字
  995. },
  996. "date":[ 害虫搜索出来的数据
  997. {
  998. "addtime": 1590230292, 时间
  999. "temperature": 39.8, 温度
  1000. "humidity": 34.9, 湿度
  1001. "_sums": 17 这个时间点的害虫总数
  1002. "_sname": 蛾子 害虫名字
  1003. },
  1004. ],....]
  1005. "device_name":"这里是设备名称",
  1006. "address": "这里是设备位置",
  1007. "disable":device.disable, #0 不识别,1识别 2,计数
  1008. """
  1009. post_info = request.POST
  1010. d_id = post_info.get("d_id")
  1011. identify_model = post_info.get("identify_model")
  1012. start_time = post_info.get("start_time")
  1013. end_time = post_info.get("end_time")
  1014. pest_name = post_info.get("pest_name","")
  1015. if not d_id:
  1016. raise PortError('device_id', "设备不能为空")
  1017. device = MongoDevice.objects.get(id=d_id)
  1018. province = device.province
  1019. city = device.city
  1020. district = device.district
  1021. device_name = device.device_name
  1022. myuser = request.myuser
  1023. if not myuser.user_type == 1 and device.device_expire == "1":
  1024. if identify_model == "B":
  1025. cbdphotos = CBDphoto_B.objects.filter(~Q(indentify_photo=None),device_id=d_id,photo_status=1,addtime__lte=int(device.device_expire_time)).order_by('-addtime')
  1026. else:
  1027. cbdphotos = MongoCBDphoto.objects.filter(~Q(indentify_photo=None),device_id=d_id,photo_status=1,addtime__lte=int(device.device_expire_time)).order_by('-addtime')
  1028. if end_time and int(end_time) > int(device.device_expire_time):
  1029. end_time = device.device_expire_time
  1030. cbdphotos = cbdphotos.filter(addtime__range=(int(start_time),int(end_time)))
  1031. else:
  1032. if identify_model == "B":
  1033. cbdphotos = CBDphoto_B.objects.filter(~Q(indentify_photo=None),device_id=d_id,photo_status=1).order_by('-addtime')
  1034. else:
  1035. cbdphotos = MongoCBDphoto.objects.filter(~Q(indentify_photo=None),device_id=d_id,photo_status=1).order_by('-addtime')
  1036. if start_time:
  1037. cbdphotos = cbdphotos.filter(addtime__gte=int(start_time))
  1038. if end_time:
  1039. cbdphotos = cbdphotos.filter(addtime__lte=int(end_time))
  1040. page = post_info.get('page',1)
  1041. if page:
  1042. page = int(page)
  1043. page_size = post_info.get('page_size')
  1044. start = ''
  1045. end = ''
  1046. if page_size:
  1047. page_size = int(page_size)
  1048. if page and page_size:
  1049. start = max((page - 1), 0) * page_size
  1050. end = page * page_size
  1051. date = []
  1052. d_sums = {}
  1053. indentify_photos = {}
  1054. percentage = []
  1055. counts = ''
  1056. time_d_sums = []
  1057. nums = 0
  1058. nusm = 0
  1059. for c in cbdphotos:
  1060. photo_id = c.id
  1061. indentify_photo = c.indentify_photo
  1062. if not indentify_photo:
  1063. continue
  1064. if not indentify_photo.startswith('http'):
  1065. if str(indentify_photo).startswith('/'):
  1066. indentify_photo = config_dict['image_url']["discern"] + indentify_photo
  1067. else:
  1068. indentify_photo = config_dict['image_url']["discern"] + "/" + indentify_photo
  1069. if not pest_name:
  1070. time_d_sums.append({"pest": c.indentify_result,
  1071. "addtime": c.addtime,
  1072. "result_photo":indentify_photo,
  1073. "mark":c.mark,
  1074. })
  1075. if c.indentify_result != None and c.indentify_result != "":
  1076. sums = c.indentify_result.split('#')
  1077. for i in sums:
  1078. i_result = i.split(',')
  1079. if pest_name == insect_dict[i_result[0]]:
  1080. date.append({
  1081. "temperature": c.at,
  1082. "humidity": c.ah,
  1083. "addtime": c.addtime,
  1084. "_sums": i_result[1],
  1085. "_sname":insect_dict[i_result[0]],
  1086. })
  1087. if not pest_name:
  1088. _result = sums[0].split(',')
  1089. date.append({
  1090. "temperature": c.at,
  1091. "humidity": c.ah,
  1092. "addtime": c.addtime,
  1093. "_sums": _result[1],
  1094. "_sname": insect_dict[_result[0]]})
  1095. nums += int(_result[1])
  1096. d_sums.setdefault(i_result[0], []).append(int(i_result[1]))
  1097. indentify_photos.setdefault(i_result[0], []).append(photo_id)
  1098. # 增加用户手动标注的数据
  1099. # _nums = count + num
  1100. if c.mark:
  1101. mark = json.loads(c.mark)
  1102. for y in mark:
  1103. if pest_name == y["tagName"]:
  1104. nusm += 1
  1105. date.append({
  1106. "temperature": c.at,
  1107. "humidity": c.ah,
  1108. "addtime": c.addtime,
  1109. "_sums": nusm,
  1110. "_sname":y["tagName"]})
  1111. if not pest_name:
  1112. nusm += 1
  1113. date.append({
  1114. "temperature": c.at,
  1115. "humidity": c.ah,
  1116. "addtime": c.addtime,
  1117. "_sums": nusm,
  1118. "_sname":y["tagName"]})
  1119. d_sums.setdefault(y["tagName"], []).append(1)
  1120. indentify_photos.setdefault(y["tagName"], []).append(photo_id)
  1121. user_type = request.myuser.user_type
  1122. if user_type == 1:
  1123. disable = 1
  1124. else:
  1125. disable = device.disable
  1126. if not pest_name:
  1127. # user_type =
  1128. if disable == 0:
  1129. percentage = "设备不具备识别功能"
  1130. raise PortError('device_id', "此设备不具备识别功能")
  1131. elif disable == 1:
  1132. for k,v in d_sums.items():
  1133. try:
  1134. name_num = insect_dict[k]
  1135. except:
  1136. name_num = k
  1137. percentage.append({
  1138. "name_num":name_num,
  1139. "sum": sum(v),
  1140. "indentify_photos":indentify_photos[k],
  1141. "num":k})
  1142. #percentage = [{"name_num": insect_dict[k], "sum": sum(v),"indentify_photos":indentify_photos[k],"num":k} for k, v in d_sums.items()]
  1143. counts = len(percentage)
  1144. if start or end:
  1145. percentage = percentage[start:end]
  1146. time_d_sums = time_d_sums[start:end]
  1147. elif disable == 2:
  1148. percentage = nums
  1149. if start or end:
  1150. time_d_sums = time_d_sums[start:end]
  1151. data = {
  1152. "disable":disable, #0 不识别,1识别 2,计数
  1153. "percentage":percentage, # 统计
  1154. "time_d_sums":time_d_sums, # 时间详细
  1155. "device_name":device_name,
  1156. "address": province + city + district,
  1157. "counts":counts,
  1158. "date":date, #饼状图
  1159. }
  1160. return data
  1161. # import copy
  1162. import operator
  1163. def pest_statistics_total(request):
  1164. """
  1165. 害虫统计页面
  1166. 害虫变化趋势折线图
  1167. 参数:
  1168. start_time 非必传(string 时间戳) 开始时间 (用于时间搜索)
  1169. end_time 非必传(string 时间戳) 结束时间 (用于时间搜索)
  1170. pest_name 非必传(str) 害虫名称
  1171. 返回值:
  1172. "broken_line": [
  1173. {
  1174. "addtime": 1590230292, 时间
  1175. "at": 39.8, 温度
  1176. "ah": 34.9, 湿度
  1177. "_sums": 17 这个时间点的害虫总数
  1178. "_sname": 蛾子 害虫名字
  1179. },
  1180. "date":[ 害虫搜索出来的数据
  1181. {
  1182. "addtime": 1590230292, 时间
  1183. "at": 39.8, 温度
  1184. "ah": 34.9, 湿度
  1185. "_sums": 17 这个时间点的害虫总数
  1186. "_sname": 蛾子 害虫名字
  1187. },
  1188. ],....]
  1189. "device_name":"这里是设备名称",
  1190. "address": "这里是设备位置",
  1191. """
  1192. post_info = request.POST
  1193. start_time = post_info.get("start_time")
  1194. end_time = post_info.get("end_time")
  1195. pest_name = post_info.get("pest_name","")
  1196. myuser = request.myuser
  1197. devices = MongoDevice.devices(uid=myuser.uid,myuser=myuser)
  1198. if myuser.user_type != 4 or myuser.user_type != 1:
  1199. devices = devices.filter(disable=1)
  1200. #自动统计
  1201. date = []
  1202. d_sums = {}
  1203. percentage = []
  1204. time_d_sums = []
  1205. counts = ""
  1206. for i in devices:
  1207. if not myuser.user_type == 1 and i.device_expire == "1":
  1208. cbd_data = MongoCBDphoto.objects.filter(~Q(indentify_photo=None),device_id=i.id,photo_status=1,addtime__lte=int(i.device_expire_time)).order_by('-id')
  1209. if end_time and int(end_time) > int(i.device_expire_time):
  1210. end_time = i.device_expire_time
  1211. cbd_data = cbd_data.filter(addtime__range=(int(start_time),int(end_time)))
  1212. else:
  1213. cbd_data = MongoCBDphoto.objects.filter(~Q(indentify_photo=None),device_id=i.id,photo_status=1).order_by('-id')
  1214. if start_time:
  1215. cbd_data = cbd_data.filter(addtime__range=(int(start_time),int(end_time)))
  1216. page = post_info.get('page',1)
  1217. if page:
  1218. page = int(page)
  1219. page_size = post_info.get('page_size')
  1220. start = ''
  1221. end = ''
  1222. if page_size:
  1223. page_size = int(page_size)
  1224. if page and page_size:
  1225. start = max((page - 1), 0) * page_size
  1226. end = page * page_size
  1227. counts = ''
  1228. for c in cbd_data:
  1229. indentify_photo = c.indentify_photo
  1230. if not indentify_photo:
  1231. continue
  1232. if not indentify_photo.startswith('http'):
  1233. if str(indentify_photo).startswith('/'):
  1234. indentify_photo = config_dict['image_url']["discern"] + indentify_photo
  1235. else:
  1236. indentify_photo = config_dict['image_url']["discern"] + "/" + indentify_photo
  1237. if not pest_name:
  1238. time_d_sums.append({"pest": c.indentify_result,
  1239. "addtime": c.addtime,
  1240. "result_photo":indentify_photo,
  1241. })
  1242. if c.indentify_result != None and c.indentify_result != "":
  1243. sums = c.indentify_result.split('#')
  1244. for i in sums:
  1245. i_result = i.split(',')
  1246. if pest_name == insect_dict[i_result[0]]:
  1247. date.append({
  1248. "temperature": c.at,
  1249. "humidity": c.ah,
  1250. "addtime": c.addtime,
  1251. "_sums": i_result[1],
  1252. "_sname":insect_dict[i_result[0]],
  1253. })
  1254. if not pest_name:
  1255. _result = sums[0].split(',')
  1256. date.append({
  1257. "temperature": c.at,
  1258. "humidity": c.ah,
  1259. "addtime": c.addtime,
  1260. "_sums": int(_result[1]),
  1261. "_sname": insect_dict[_result[0]],
  1262. })
  1263. d_sums.setdefault(i_result[0], []).append(int(i_result[1]))
  1264. if not pest_name:
  1265. percentage = [{"name_num": insect_dict[k], "sum": sum(v),"num":k} for k, v in d_sums.items()]
  1266. counts = len(percentage)
  1267. if start or end:
  1268. percentage = percentage[start:end]
  1269. time_d_sums = time_d_sums[start:end]
  1270. data = {}
  1271. if pest_name:
  1272. for item in date:
  1273. add_time, _sums, _sname,at,ah = item['addtime'], item['_sums'], item['_sname'],item["temperature"],item["humidity"]
  1274. key = '{}_{}_{}_{}'.format(add_time, _sname,at,ah)
  1275. if key in data:
  1276. data[key] += _sums
  1277. else:
  1278. data[key] = _sums
  1279. result = []
  1280. for key, value in data.items():
  1281. add_time, _sname,at,ah= key.split('_')
  1282. result.append({
  1283. "addtime": add_time,
  1284. "_sums": data[key],
  1285. "_sname": _sname,
  1286. "at" : at,
  1287. "ah": ah
  1288. })
  1289. else:
  1290. for item in date:
  1291. add_time, _sums, _sname, at, ah = item['addtime'], item['_sums'], item['_sname'],item["temperature"],item["humidity"]
  1292. key = '{}_{}_{}_{}'.format(_sname,add_time,at,ah)
  1293. if key in data:
  1294. data[key] += _sums
  1295. else:
  1296. data[key] = _sums
  1297. result = []
  1298. for key, value in data.items():
  1299. _sname,add_time,at,ah= key.split('_')
  1300. result.append({
  1301. "addtime": add_time,
  1302. "_sums": data[key],
  1303. "_sname": _sname,
  1304. "at" : at,
  1305. "ah": ah
  1306. })
  1307. # 降序
  1308. # list2 = sorted(result, key=operator.itemgetter('addtime'),reverse=True)
  1309. list2 = sorted(result, key=operator.itemgetter('addtime'))
  1310. data = {
  1311. "percentage":percentage, # 统计
  1312. "time_d_sums":time_d_sums, # 时间详细
  1313. # "address": province + city + district,
  1314. "counts":counts,
  1315. "date":list2, #饼状图
  1316. }
  1317. return data
  1318. def pest_contrast_total(request):
  1319. """
  1320. 某一害虫对比
  1321. 参数:
  1322. d_id 必传(str) 设备id
  1323. start_time 非必传(string 时间戳) 开始时间 (用于时间搜索)
  1324. end_time 非必传(string 时间戳) 结束时间 (用于时间搜索)
  1325. pest_name 非必传(str) 害虫名称
  1326. 返回值:
  1327. """
  1328. post_info = request.POST
  1329. start_time = post_info.get("start_time")
  1330. identify_model = post_info.get("identify_model")
  1331. end_time = post_info.get("end_time")
  1332. pest_name = post_info.get("pest_name","")
  1333. d_id = post_info.get("d_id")
  1334. if not d_id:
  1335. raise PortError('device_id', "设备不能为空")
  1336. device = Device.objects.get(id=d_id)
  1337. myuser = request.myuser
  1338. if not myuser.user_type == 1 and device.device_expire == "1":
  1339. if identify_model == "B":
  1340. cbd_data = CBDphoto_B.objects.filter(~Q(indentify_photo=None),device_id=device.id,photo_status=1,addtime__lte=int(device.device_expire_time)).order_by("-id")
  1341. else:
  1342. cbd_data = CBDphoto.objects.filter(~Q(indentify_photo=None),device_id=device.id,photo_status=1,addtime__lte=int(device.device_expire_time)).order_by("-id")
  1343. if end_time and int(end_time) > int(device.device_expire_time):
  1344. end_time = device.device_expire_time
  1345. cbd_data = cbd_data.filter(addtime__range=(int(start_time),int(end_time)))
  1346. else:
  1347. if identify_model == "B":
  1348. cbd_data = CBDphoto_B.objects.filter(~Q(indentify_photo=None),device_id=device.id,photo_status=1).order_by("-id")
  1349. else:
  1350. cbd_data = CBDphoto.objects.filter(~Q(indentify_photo=None),device_id=device.id,photo_status=1).order_by("-id")
  1351. if start_time:
  1352. cbd_data = cbd_data.filter(addtime__range=(int(start_time),int(end_time)))
  1353. # cbdphotos = CBDphoto.objects.filter(~Q(indentify_photo=None),device_id=d_id).order_by('-id')
  1354. # if start_time:
  1355. # cbdphotos = cbdphotos.filter(addtime__gte=int(start_time))
  1356. # if end_time:
  1357. # cbdphotos = cbdphotos.filter(addtime__lte=int(end_time))
  1358. date = []
  1359. d_sums = {}
  1360. indentify_photos = {}
  1361. percentage = []
  1362. for c in cbd_data:
  1363. photo_id = c.id
  1364. indentify_photo = c.indentify_photo
  1365. if not indentify_photo:
  1366. continue
  1367. elif not c.indentify_result:
  1368. continue
  1369. sums = c.indentify_result.split('#')
  1370. for i in sums:
  1371. i_result = i.split(',')
  1372. if pest_name == insect_dict[i_result[0]]:
  1373. date.append({
  1374. "temperature": c.at,
  1375. "humidity": c.ah,
  1376. "addtime": c.addtime,
  1377. "_sums": i_result[1],
  1378. "_sname":insect_dict[i_result[0]],
  1379. })
  1380. if not pest_name:
  1381. date.append({
  1382. "temperature": c.at,
  1383. "humidity": c.ah,
  1384. "addtime": c.addtime,
  1385. "_sums": int(i_result[1]),
  1386. "_sname": insect_dict[i_result[0]],
  1387. })
  1388. d_sums.setdefault(i_result[0], []).append(int(i_result[1]))
  1389. indentify_photos.setdefault(i_result[0], []).append(photo_id)
  1390. if not pest_name:
  1391. percentage = [{"name_num": insect_dict[k], "sum": sum(v),"indentify_photos":indentify_photos[k],"num":k} for k, v in d_sums.items()]
  1392. data = {}
  1393. if pest_name:
  1394. for item in date:
  1395. add_time, _sums, _sname,at,ah = item['addtime'], item['_sums'], item['_sname'],item["temperature"],item["humidity"]
  1396. key = '{}_{}_{}_{}'.format(add_time, _sname,at,ah)
  1397. if key in data:
  1398. data[key] += _sums
  1399. else:
  1400. data[key] = _sums
  1401. result = []
  1402. for key, value in data.items():
  1403. add_time, _sname,at,ah= key.split('_')
  1404. result.append({
  1405. "addtime": add_time,
  1406. "_sums": data[key],
  1407. "_sname": _sname,
  1408. "at" : at,
  1409. "ah": ah
  1410. })
  1411. else:
  1412. for item in date:
  1413. add_time, _sums, _sname, at, ah = item['addtime'], item['_sums'], item['_sname'],item["temperature"],item["humidity"]
  1414. key = '{}_{}_{}_{}'.format(_sname,add_time,at,ah)
  1415. if key in data:
  1416. data[key] += _sums
  1417. else:
  1418. data[key] = _sums
  1419. result = []
  1420. for key, value in data.items():
  1421. _sname,add_time,at,ah= key.split('_')
  1422. result.append({
  1423. "addtime": add_time,
  1424. "_sums": data[key],
  1425. "_sname": _sname,
  1426. "at" : at,
  1427. "ah": ah
  1428. })
  1429. # 降序
  1430. # list2 = sorted(result, key=operator.itemgetter('addtime'),reverse=True)
  1431. list2 = sorted(result, key=operator.itemgetter('addtime'))
  1432. data = {
  1433. "percentage":percentage,
  1434. "list2":list2
  1435. }
  1436. return data
  1437. def photo_result(request):
  1438. """
  1439. 害虫统计页面
  1440. 害虫变化趋势折线图
  1441. 参数:
  1442. photo_ids 必传 照片自增id
  1443. """
  1444. post_info = request.POST
  1445. photo_ids = post_info.get("photo_ids","")
  1446. if not photo_ids:
  1447. raise PortError('photo_ids', "不能为空")
  1448. photo_ids = [int(i) for i in eval(photo_ids)]
  1449. cbdphotos = MongoCBDphoto.objects.filter(id__in=photo_ids).order_by('-id')
  1450. data = []
  1451. for p in cbdphotos:
  1452. indentify_photo = p.indentify_photo
  1453. if not indentify_photo.startswith('http'):
  1454. if str(indentify_photo).startswith('/'):
  1455. indentify_photo = config_dict['image_url']["discern"] + indentify_photo
  1456. else:
  1457. indentify_photo = config_dict['image_url']["discern"] + "/" + indentify_photo
  1458. data.append(
  1459. {
  1460. "indentify_photo":indentify_photo,
  1461. "indentify_result":p.indentify_result,
  1462. }
  1463. )
  1464. return data
  1465. def pest_manual_statistics(request):
  1466. """
  1467. 病虫害手动统计接口/害虫名称搜索:
  1468. 参数:
  1469. device_id 必传(str) 设备id
  1470. start_time 非必传(时间戳) 开始时间
  1471. end_time 非必传(时间戳) 结束时间
  1472. pest_name 非必传(str) 害虫名
  1473. """
  1474. device_id = request.POST.get('device_id')
  1475. start_time = request.POST.get("start_time")
  1476. end_time = request.POST.get("end_time")
  1477. pest_name = request.POST.get("pest_name")
  1478. page = int(request.POST.get('page',1))
  1479. try:
  1480. device = MongoDevice.objects.get(id=device_id)
  1481. except:
  1482. raise PortError('device_id', "没有该设备")
  1483. if not device_id:
  1484. raise PortError('device_id', "没有传设备号")
  1485. myuser = request.myuser
  1486. if not myuser.user_type == 1 and device.device_expire == "1":
  1487. cbdphotos = Device_Desc.objects.filter(device_id=device_id)
  1488. if end_time and int(end_time) > int(device.device_expire_time):
  1489. end_time = device.device_expire_time
  1490. cbdphotos = cbdphotos.filter(addtime__range=(int(start_time),int(end_time)))
  1491. else:
  1492. cbdphotos = Device_Desc.objects.filter(device_id=device_id)
  1493. if start_time:
  1494. cbdphotos = cbdphotos.filter(add_time__gte=start_time)
  1495. if end_time:
  1496. cbdphotos = cbdphotos.filter(add_time__lte=end_time)
  1497. dat = [] # 害虫名称
  1498. data = [] # 饼状图
  1499. date = [] # 列表
  1500. pest = [] # 折线图
  1501. if cbdphotos:
  1502. for i in cbdphotos:
  1503. cbd_img_list = MongoCBDphoto.objects.filter(id=i.photo_id)
  1504. pest_num = 0
  1505. if i.pest_name not in dat:
  1506. dat.append(i.pest_name)
  1507. pest_list = cbdphotos.filter(pest_name=i.pest_name)
  1508. for y in pest_list:
  1509. pest_num += int(y.pest_num)
  1510. data.append({"pest_name":i.pest_name,"pest_num":pest_num})
  1511. image = ""
  1512. for x in cbd_img_list:
  1513. image = x.addr
  1514. if image.startswith("http"):
  1515. image = image
  1516. else:
  1517. image = config_dict["image_url"]["frond"] + image
  1518. date.append({
  1519. "pest_num":i.pest_num,
  1520. "pest_name":i.pest_name,
  1521. "crop_name":i.crop_name,
  1522. "pest_case":i.pest_case,
  1523. "add_time":i.add_time,
  1524. "image":image
  1525. })
  1526. dat_list = date[(10*(page-1)):(page*10)]
  1527. else:
  1528. dat_list = []
  1529. if dat:
  1530. if pest_name:
  1531. pest_list = cbdphotos.filter(pest_name=pest_name)
  1532. else:
  1533. pest_list = cbdphotos.filter(pest_name=dat[0])
  1534. pest_name = dat[0]
  1535. for ii in pest_list:
  1536. pests = {"pest_name":pest_name}
  1537. if pest_name == ii.pest_name:
  1538. pest.append({
  1539. "pest_num":ii.pest_num,
  1540. "add_time":ii.add_time})
  1541. pests["pest_list"] = pest
  1542. else:
  1543. pests = {}
  1544. nums = cbdphotos.count()
  1545. data = {"nums":nums,"dat":data,"date":dat_list,"pests":pests}
  1546. return data
  1547. from django.db.models import Q
  1548. import time
  1549. import pymysql
  1550. # 已弃用
  1551. # @kedong_deco(login_required=True)
  1552. def worm_list(request):
  1553. """
  1554. 害虫列表
  1555. 参数;
  1556. 暂无
  1557. 返回值:
  1558. "data": [
  1559. {
  1560. "name": "暗纹紫褐螟",
  1561. "num": "317"
  1562. },....
  1563. ]
  1564. """
  1565. insect_dict = ""
  1566. try:
  1567. dir_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))))
  1568. path = os.path.join(dir_path, "scripts/pest_dict.json")
  1569. with open(path,'r',encoding='utf-8') as f:
  1570. insect_dict = json.loads(f.read())
  1571. except Exception as e:
  1572. path = sys.path[0] + "/scripts/pest_dict.json"
  1573. with open(path,'r',encoding='utf-8') as f:
  1574. insect_dict = json.loads(f.read())
  1575. return insect_dict
  1576. @kedong_deco(login_required=True)
  1577. def cbd_pest_warning(request):
  1578. """
  1579. 测报灯-害虫预警
  1580. 2022-05-19 14:22 csx
  1581. 参数:
  1582. page 非必传(num) 页码,默认为1
  1583. page_size 非必传(num) 每页数量,默认为10
  1584. status 非必传(str) 为yes时 是设置一键已读
  1585. d_id 非必传(str) 传id时,为单个数据设置已读
  1586. device_id 非必传(str) 传设备号时,为当前设备的预警信息
  1587. 返回值:
  1588. {
  1589. "errorCode": 0,
  1590. "message": "",
  1591. "formError": {},
  1592. "data": {
  1593. "data": [
  1594. {
  1595. "device_id": "862167051501330", 设备号
  1596. "warning_content": 4, 害虫种类数
  1597. "warning_status": "1", 1目标种类预警 2、指定害虫数量预警 3 害虫数量总和预警 4综合预警
  1598. "upltime": 1652936123, 时间戳
  1599. "status": 0 0未读 1已读
  1600. },
  1601. {
  1602. "device_id": "862167051501330",
  1603. "warning_content": 411,
  1604. "warning_status": "3",
  1605. "upltime": 1652936123,
  1606. "status": 0
  1607. },
  1608. {
  1609. "device_id": "862167051501330",
  1610. "warning_content": {
  1611. "铜绿丽金龟": "1头",
  1612. "水龟虫": "48头",
  1613. "龙虱": "4头",
  1614. "负子蝽": "13头"
  1615. },
  1616. "warning_status": "4",
  1617. "upltime": 1652936123,
  1618. "status": 0
  1619. },
  1620. """
  1621. page = request.POST.get('page',1)
  1622. page_size = request.POST.get('page_size',10)
  1623. status = request.POST.get('status')
  1624. d_id = request.POST.get('d_id')
  1625. deviceid = request.POST.get("device_id")
  1626. devices = MongoDevice.objects.filter(device_type_id=3)
  1627. if deviceid:
  1628. devices = devices.filter(device_id__icontains=deviceid)
  1629. devices = devices.values("device_id")
  1630. device_list = [d['device_id'] for d in devices]
  1631. if page and page_size:
  1632. page_size = int(page_size)
  1633. page = int(page)
  1634. start = max((page - 1), 0) * page_size
  1635. end = page * page_size
  1636. pest_warn = DevicePestWarning.objects.filter(device_id__in=device_list)
  1637. if d_id:
  1638. pest_warn = DevicePestWarning.objects.filter(id=d_id).update(status=1)
  1639. return True
  1640. data = []
  1641. nums = pest_warn.count()
  1642. if nums:
  1643. if status:
  1644. if status == "yes":
  1645. pest_warn.update(status=1)
  1646. return True
  1647. else:
  1648. raise PortError('',"参数错误")
  1649. for x in pest_warn.order_by("-id")[start:end]:
  1650. data.append({
  1651. "d_id":x.id,
  1652. "device_id":x.device_id,
  1653. "warning_content":eval(x.warning_content),
  1654. "warning_status":x.warning_status,
  1655. "upltime":x.upltime,
  1656. "status":x.status
  1657. })
  1658. return {"data":data,"nusm":nums}
  1659. @kedong_deco(login_required=True)
  1660. def qxz_warning(request):
  1661. """
  1662. 气象站-通道要素预警
  1663. 2022-05-20 10:22 csx
  1664. 参数:
  1665. page 非必传(num) 页码,默认为1
  1666. page_size 非必传(num) 每页数量,默认为10
  1667. status 非必传(str) 为yes时 是设置一键已读
  1668. d_id 非必传(str) 传id时,为单个数据设置已读
  1669. 返回值:
  1670. {
  1671. "errorCode": 0,
  1672. "message": "",
  1673. "formError": {},
  1674. "data": {
  1675. "data": [
  1676. {
  1677. "d_id": 1, 数据id
  1678. "device_id": "866193059770251", 设备号
  1679. "warning_content": "大于预警", 预警描述
  1680. "ekey": "空气温度#℃", 要素描述 加单位
  1681. "set_value": "13", 用户设置预警值
  1682. "current_value": "19.3", 设备当前上传的数据值
  1683. "upltime": 1653012464, 保存时间
  1684. "status": 0 0 未读 1已读
  1685. },
  1686. {
  1687. "d_id": 2,
  1688. "device_id": "866193059770251",
  1689. "warning_content": "大于预警",
  1690. "ekey": "空气温度#℃",
  1691. "set_value": "13",
  1692. "current_value": "19.3",
  1693. "upltime": 1653012757,
  1694. "status": 0
  1695. },
  1696. """
  1697. page = request.POST.get('page','1')
  1698. page_size = request.POST.get('page_size','10')
  1699. status = request.POST.get('status')
  1700. device_type = request.POST.get('device_type',"5")
  1701. d_id = request.POST.get('d_id')
  1702. if device_type not in ("5","8"):
  1703. raise PortError("","设备类型超出")
  1704. if d_id:
  1705. warn = QXZThresholdWarning.objects.filter(id=d_id).update(status=1)
  1706. return True
  1707. devices = MongoDevice.objects.filter(device_type_id=device_type)
  1708. device_list = [device_id.device_id for device_id in devices]
  1709. if page and page_size:
  1710. if not page.isdigit() and not page_size.isdigit():
  1711. raise PortError("","参数错误")
  1712. page_size = int(page_size)
  1713. page = int(page)
  1714. else:
  1715. page = 1
  1716. page_size = 10
  1717. start = max((page - 1), 0) * page_size
  1718. end = page * page_size
  1719. warn = QXZThresholdWarning.objects.filter(device_id__in=device_list)
  1720. data = []
  1721. nums = warn.count()
  1722. if nums:
  1723. if status:
  1724. if status == "yes":
  1725. warn.update(status=1)
  1726. return True
  1727. else:
  1728. raise PortError('',"参数错误")
  1729. for x in warn.order_by("-id")[start:end]:
  1730. data.append({
  1731. "d_id":x.id,
  1732. "device_id":x.device_id,
  1733. "warning_content":x.warning_content,
  1734. "ekey":x.ekey,
  1735. "set_value":x.set_value,
  1736. "current_value":x.current_value,
  1737. "upltime":x.upltime,
  1738. "status":x.status
  1739. })
  1740. return {"data":data,"nusm":nums}
  1741. @kedong_deco(login_required=True)
  1742. def xycb_pest_chart(request):
  1743. """
  1744. 性诱1.0,3.0设备害虫折线图
  1745. 参数:
  1746. d_id 必传 设备id
  1747. start_time 必传(string 秒级时间戳) 开始时间
  1748. end_time 必传(string 秒级时间戳) 结束时间
  1749. device_type_id 必传 设备类型编号 4性诱测报1.0, 8性诱测报3.0
  1750. return
  1751. {
  1752. "total_num": 0,
  1753. "pest_data": [
  1754. {
  1755. "pest_num": 0,
  1756. "addtime": 1659024000
  1757. },
  1758. ]
  1759. }
  1760. """
  1761. post_info = request.POST
  1762. start_time = post_info.get('start_time')
  1763. end_time = post_info.get('end_time')
  1764. d_id = post_info.get("d_id")
  1765. device_type_id = post_info.get("device_type_id")
  1766. if d_id:
  1767. d_id = int(d_id)
  1768. else:
  1769. raise PortError('d_id', "请输入设备id")
  1770. if device_type_id:
  1771. device_type_id = int(device_type_id)
  1772. else:
  1773. raise PortError("device_type_id", "请输入设备类型编号")
  1774. if start_time:
  1775. start_time = int(start_time)
  1776. else:
  1777. raise PortError('start_time', "请输入设备start_time")
  1778. if end_time:
  1779. end_time = int(end_time)
  1780. else:
  1781. raise PortError('end_time', "请输入设备end_time")
  1782. try:
  1783. device = MongoDevice.objects.get(id=d_id)
  1784. device_expire = device.device_expire
  1785. device_expire_time = device.device_expire_time
  1786. except:
  1787. raise PortError('device_id', "暂无此设备")
  1788. myuser_type = request.myuser.user_type
  1789. if not myuser_type == 1 and not myuser_type == 5 and device_expire == "1":
  1790. if end_time > int(device_expire_time):
  1791. end_time = int(device_expire_time)
  1792. if end_time < start_time:
  1793. raise PortError("expire time", "设备已到期")
  1794. queryset = MongoXYCBData.objects.filter(device_id=d_id, addtime__gte=start_time, addtime__lte=end_time).order_by('-addtime')
  1795. pest_data = []
  1796. total_pest_num = 0
  1797. for item in queryset:
  1798. try:
  1799. device_data = json.loads((str(item.device_data)).replace("'", '"'))
  1800. infr_ct = device_data['infr_ct']
  1801. addtime = item.addtime
  1802. pest_data.append({
  1803. "pest_num": infr_ct,
  1804. "addtime": addtime
  1805. })
  1806. try:
  1807. infr_ct = int(infr_ct)
  1808. except Exception as e:
  1809. infr_ct = 0
  1810. total_pest_num += infr_ct
  1811. except Exception as e:
  1812. logger.error(f"Json 解析错误:{e}")
  1813. return {"total_num": 0, "pest_data": []}
  1814. return {"total_num": total_pest_num, "pest_data": pest_data}
  1815. @kedong_deco(login_required=True)
  1816. def set_decopy(request):
  1817. """
  1818. 设置诱芯接口
  1819. 参数:
  1820. device_type_id 必传 设备类型ID
  1821. device_id 必传 设备编号
  1822. decoy 必传 诱芯名称
  1823. expire_time 非必传 诱芯过期时间
  1824. """
  1825. post_info = request.POST
  1826. device_type_id = post_info.get("device_type_id")
  1827. device_id = post_info.get("device_id")
  1828. decoy = post_info.get("decoy")
  1829. expire_time = post_info.get("expire_time")
  1830. if not device_id:
  1831. raise PortError("device_id","参数缺失")
  1832. if not decoy:
  1833. raise PortError("decoy","参数缺失")
  1834. now_timestamp = int(time.time())
  1835. if device_type_id == "4" or device_type_id == "8":
  1836. try:
  1837. device_object = MongoDevice.objects.get(device_id=device_id)
  1838. except Exception as e:
  1839. raise PortError("device_id","未查找到该设备")
  1840. device_object.decoy = decoy
  1841. else:
  1842. raise PortError("device_type_id","参数缺失")
  1843. device_object.xy_uptime = now_timestamp
  1844. if expire_time:
  1845. device_object.xy_expire_time = int(expire_time)
  1846. device_object.save()
  1847. return {"status":True}