worm_lamp.py 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003
  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. pest_name = insect_dict.get(tuple_result[0],"未命名")
  498. pest_num = int(tuple_result[1])
  499. if pest_name in pest_day_info:
  500. pest_day_info[pest_name]["highNum"] += pest_num
  501. else:
  502. pest_day_info[pest_name] = {"startTime":time_serialize,"highTime":time_serialize,"endTime":time_serialize,"highNum":pest_num}
  503. # 最后一天的数据统计,循环内加不了
  504. for pest_day_key,pest_day_value in pest_day_info.items():
  505. if pest_day_key in pest_info:
  506. pest_info[pest_day_key]["endTime"] = pest_day_value["endTime"]
  507. if pest_day_value["highNum"] >= pest_info[pest_day_key]["highNum"]:
  508. pest_info[pest_day_key]["highTime"] = pest_day_value["highTime"]
  509. pest_info[pest_day_key]["highNum"] = pest_day_value["highNum"]
  510. else:
  511. pest_info[pest_day_key] = pest_day_value
  512. return {"pest_info":pest_info,"pest_list":list(pest_info.keys())}
  513. @kedong_deco(login_required=True)
  514. def pest_statistics_char_new(request):
  515. """
  516. 害虫统计页面
  517. 害虫变化趋势折线图
  518. 参数:
  519. d_ids 必传 设备自增ID
  520. amend 必传 机器'0'或者人为'1',不传默认为'0'机器识别
  521. start_time 必传(string 秒级时间戳) 开始时间 (用于时间搜索)
  522. end_time 必传(string 秒级时间戳) 结束时间 (用于时间所有)
  523. 返回值:
  524. 单台设备会有at,ah,多台设备情况下不会有at,ah
  525. "data": {
  526. "char_data": {
  527. "棉铃虫": [
  528. {
  529. "addtime": 1657123200,
  530. "sum": 29,
  531. "at": 24,
  532. "ah": 38
  533. },
  534. ...
  535. ],
  536. ...
  537. },
  538. "pest_total": {
  539. "蓝目天蛾": 1,
  540. "黑绒绢金龟": 1,
  541. "瓢虫": 1,
  542. "铜绿丽金龟": 3,
  543. "黄褐丽金龟": 3,
  544. "小地老虎": 6,
  545. "东方粘虫": 66,
  546. "棉铃虫": 87
  547. },
  548. "at_ah_info": [
  549. {
  550. "addtime": 1657123200,
  551. "at": 24,
  552. "ah": 38
  553. },
  554. ...
  555. ]
  556. },
  557. """
  558. parameters = request.POST
  559. d_ids = parameters.get("d_ids")
  560. start_time = int(parameters.get("start_time"))
  561. end_time = int(parameters.get("end_time"))
  562. amend = parameters.get("amend","0")
  563. # 获取统计设备列表
  564. if d_ids:
  565. d_id_list = [int(d_id) for d_id in d_ids.split(",")]
  566. else:
  567. raise PortError("d_ids","参数缺失")
  568. # 统计
  569. photo_queryset = MongoCBDphoto.objects.filter(device_id__in=d_id_list,photo_status=1,addtime__range=(start_time,end_time))
  570. if amend == "0":
  571. photo_queryset = photo_queryset.filter(~Q(indentify_result="")).order_by("addtime")
  572. else:
  573. photo_queryset = photo_queryset.filter(~Q(indentify_result="") | ~Q(mark="")).order_by("addtime")
  574. chart_info = {}
  575. pest_day_info = {}
  576. at_day_info = []
  577. ah_day_info = []
  578. at_ah_info = []
  579. pest_info_total = {}
  580. time_recording = 0
  581. for photo_object in photo_queryset:
  582. addtime = photo_object.addtime
  583. time_date = time.strftime("%Y-%m-%d",time.localtime(addtime))
  584. date_stamp = int(time.mktime(time.strptime(time_date,"%Y-%m-%d")))
  585. # 按天归档
  586. if date_stamp != time_recording:
  587. for pest_day_key,pest_day_value in pest_day_info.items():
  588. if pest_day_key in chart_info:
  589. chart_info[pest_day_key].append(pest_day_value)
  590. else:
  591. chart_info[pest_day_key] = []
  592. chart_info[pest_day_key].append(pest_day_value)
  593. if len(d_id_list) == 1: # 单台设备可以来获取温湿度,多台设备不能获取温湿度
  594. if time_recording != 0:
  595. at_avg = int(sum(at_day_info)//len(at_day_info)) if len(at_day_info)!=0 else 25
  596. ah_avg = int(sum(ah_day_info)//len(ah_day_info)) if len(ah_day_info)!=0 else 30
  597. at_ah_info.append({"addtime":time_recording,"at":at_avg,"ah":ah_avg})
  598. pest_day_info.clear()
  599. at_day_info.clear()
  600. ah_day_info.clear()
  601. time_recording = date_stamp
  602. # 单张照片结果
  603. if len(d_id_list) == 1:
  604. at = eval(photo_object.at) if photo_object.at else 0
  605. ah = eval(photo_object.ah) if photo_object.ah else 0
  606. if at != 0:
  607. at_day_info.append(at)
  608. if ah != 0:
  609. ah_day_info.append(ah)
  610. indentify_result = photo_object.indentify_result
  611. mark = photo_object.mark
  612. if amend == "1" and mark:
  613. mark = json.loads(mark)
  614. for label in mark:
  615. pest_name = label.get("text")
  616. pest_num = 1
  617. if pest_name in pest_day_info:
  618. pest_day_info[pest_name]["sum"] += pest_num
  619. else:
  620. pest_day_info[pest_name] = {"addtime":date_stamp,"sum":pest_num}
  621. if pest_name in pest_info_total:
  622. pest_info_total[pest_name] += pest_num
  623. else:
  624. pest_info_total[pest_name] = pest_num
  625. else:
  626. for result in indentify_result.split("#"):
  627. tuple_result = result.split(",")
  628. pest_name = insect_dict.get(tuple_result[0],"未命名")
  629. pest_num = int(tuple_result[1])
  630. if pest_name in pest_day_info:
  631. pest_day_info[pest_name]["sum"] += pest_num
  632. else:
  633. pest_day_info[pest_name] = {"addtime":date_stamp,"sum":pest_num}
  634. if pest_name in pest_info_total:
  635. pest_info_total[pest_name] += pest_num
  636. else:
  637. pest_info_total[pest_name] = pest_num
  638. # 最后一天的数据统计,循环内加不了
  639. for pest_day_key,pest_day_value in pest_day_info.items():
  640. if pest_day_key in chart_info:
  641. chart_info[pest_day_key].append(pest_day_value)
  642. else:
  643. chart_info[pest_day_key] = []
  644. chart_info[pest_day_key].append(pest_day_value)
  645. if len(d_id_list) == 1: # 单台设备可以来获取温湿度,多台设备不能获取温湿度
  646. if time_recording != 0:
  647. at_avg = int(sum(at_day_info)//len(at_day_info)) if len(at_day_info)!=0 else 25
  648. ah_avg = int(sum(ah_day_info)//len(ah_day_info)) if len(ah_day_info)!=0 else 30
  649. at_ah_info.append({"addtime":time_recording,"at":at_avg,"ah":ah_avg})
  650. # 字典排序
  651. pest_info_total = dict(sorted(pest_info_total.items(),key=lambda x:x[1],reverse=False))
  652. data = {"char_data":chart_info,"pest_total":pest_info_total}
  653. if len(d_id_list) == 1:
  654. data["at_ah_info"] = at_ah_info
  655. return data
  656. @kedong_deco(login_required=True)
  657. def pest_image_source(request):
  658. """
  659. 害虫统计页面
  660. 害虫溯源图片接口
  661. 参数:
  662. d_ids 必传 设备自增ID
  663. identify_model 必传 识别模型('A'为识别模型A,'B'为识别模型B)
  664. amend 必传 机器'0'或者人为'1',不传默认为'0'机器识别
  665. start_time 必传(string 秒级时间戳) 开始时间 (用于时间搜索)
  666. end_time 必传(string 秒级时间戳) 结束时间 (用于时间所有)
  667. pest_name 非必传 用于筛选项,有则查,无则全部,害虫名字
  668. page 非必传 页码 不传默认为1
  669. page_size 非必传 数据条数 默认为10
  670. 返回值:
  671. data": {
  672. "pest_image_data": [
  673. {
  674. "deviceId": "862285038174052",
  675. "deviceName": "测报灯",
  676. "pestName": "蓝目天蛾、黑绒绢金龟、瓢虫",
  677. "addtime": 1658246342,
  678. "location": "云南省昆明市呈贡区",
  679. "img_url": "https://bigdata-all.oss-cn-beijing.aliyuncs.com/Basics/cbd/620210630173657/2022/1/7/30.jpg",
  680. "indentify_photo": "http://bigdata-all.oss-accelerate.aliyuncs.com/Result/cbd/620210630173657/2022/1/7/30.jpg",
  681. "pest_dict": {
  682. "蓝目天蛾": "1",
  683. "黑绒绢金龟": "1",
  684. "瓢虫": "1"
  685. }
  686. }
  687. ],
  688. "total_count": 1,
  689. "current_count": 1
  690. }
  691. """
  692. parameters = request.POST
  693. d_ids = parameters.get("d_ids")
  694. start_time = int(parameters.get("start_time"))
  695. end_time = int(parameters.get("end_time"))
  696. select_name = parameters.get("pest_name")
  697. page = int(parameters.get("page","1"))
  698. page_size = int(parameters.get("page_size","10"))
  699. amend = parameters.get("amend","0")
  700. # 获取统计设备列表
  701. if d_ids:
  702. d_id_list = [int(d_id) for d_id in d_ids.split(",")]
  703. d_id_dicts = {}
  704. device_queryset = MongoDevice.objects.filter(id__in=d_id_list)
  705. for device_object in device_queryset:
  706. d_id_dicts[device_object.id] = {"location":device_object.province+device_object.city+device_object.district,
  707. "device_id":device_object.device_id,
  708. "device_code":device_object.device_code,
  709. "device_name":device_object.device_name if device_object.device_name else "测报灯"
  710. }
  711. else:
  712. raise PortError("d_ids","参数缺失")
  713. # 统计
  714. photo_queryset = MongoCBDphoto.objects.filter(device_id__in=list(d_id_dicts.keys()),photo_status=1,addtime__range=(start_time,end_time))
  715. if amend == "0":
  716. photo_queryset = photo_queryset.filter(~Q(indentify_result="")).order_by("-addtime")
  717. else:
  718. photo_queryset = photo_queryset.filter(~Q(indentify_result="") | ~Q(mark="")).order_by("-addtime")
  719. pest_image_data = []
  720. for photo_object in photo_queryset:
  721. # 单张照片结果
  722. indentify_result = photo_object.indentify_result
  723. mark = photo_object.mark
  724. pest_string = ""
  725. pest_dict = {}
  726. if amend == "1" and mark:
  727. if mark == "[]":
  728. continue
  729. else:
  730. mark = json.loads(mark)
  731. for index,label in enumerate(mark):
  732. pest_name = label.get("text")
  733. pest_num = 1
  734. if pest_name not in pest_string:
  735. if index != 0:
  736. pest_string += "、"
  737. pest_string += pest_name
  738. if pest_name in pest_dict:
  739. pest_dict[pest_name] += pest_num
  740. else:
  741. pest_dict[pest_name] = 1
  742. else:
  743. for index,result in enumerate(indentify_result.split("#")) :
  744. if index != 0:
  745. pest_string += "、"
  746. tuple_result = result.split(",")
  747. pest_name = insect_dict.get(tuple_result[0],"未命名")
  748. pest_string+=pest_name
  749. pest_dict[pest_name] = int(tuple_result[1])
  750. if select_name and select_name not in pest_string:
  751. continue
  752. addtime = photo_object.addtime
  753. __d_id = int(photo_object.device_id)
  754. device_code = d_id_dicts[__d_id]["device_code"]
  755. pest_image_data.append({"deviceId":d_id_dicts[__d_id]["device_id"],
  756. "deviceName":d_id_dicts[__d_id]["device_name"],
  757. "pestName":pest_string,
  758. "addtime":addtime,
  759. "location":d_id_dicts[__d_id]["location"],
  760. "img_url":photo_object.addr,
  761. "indentify_photo":photo_object.indentify_photo,
  762. "pest_dict":pest_dict
  763. })
  764. return_data = pest_image_data[(page-1)*page_size:page*page_size]
  765. return {"pest_image_data":return_data,"total_count":len(pest_image_data),"current_count":len(return_data)}
  766. @kedong_deco(login_required=True)
  767. def pest_base_data(request):
  768. """
  769. 害虫统计页面
  770. 虫害基础数据接口
  771. 参数:
  772. d_id 必传 设备自增ID
  773. identify_model 必传 识别模型('A'为识别模型A,'B'为识别模型B)
  774. amend 必传 机器'0'或者人为'1',不传默认为'0'机器识别
  775. start_time 必传(string 秒级时间戳) 开始时间 (用于时间搜索)
  776. end_time 必传(string 秒级时间戳) 结束时间 (用于时间所有)
  777. pest_name 非必传 用于筛选项,有则查,无则全部,害虫名字
  778. page 非必传 页码 不传默认为1
  779. page_size 非必传 数据条数 默认为10
  780. 返回值:
  781. "data": {
  782. "pest_image_data": [
  783. {
  784. "pest_name": "瓢虫",
  785. "pest_num": 1,
  786. "addtime": 1658246342
  787. }
  788. ],
  789. "total_count": 1,
  790. "current_count": 1
  791. }
  792. """
  793. parameters = request.POST
  794. d_ids = parameters.get("d_ids")
  795. start_time = int(parameters.get("start_time"))
  796. end_time = int(parameters.get("end_time"))
  797. select_name = parameters.get("pest_name")
  798. page = int(parameters.get("page","1"))
  799. page_size = int(parameters.get("page_size",10))
  800. amend = parameters.get("amend","0")
  801. # 获取统计设备列表
  802. if d_ids:
  803. d_id_list = [int(d_id) for d_id in d_ids.split(",")]
  804. else:
  805. raise PortError("d_ids","参数缺失")
  806. # 统计
  807. photo_queryset = MongoCBDphoto.objects.filter(device_id__in=d_id_list,photo_status=1,addtime__range=(start_time,end_time))
  808. if amend == "0":
  809. photo_queryset = photo_queryset.filter(~Q(indentify_result="")).order_by("-addtime")
  810. else:
  811. photo_queryset = photo_queryset.filter(~Q(indentify_result="") | ~Q(mark="")).order_by("-addtime")
  812. pest_base_data = []
  813. for photo_object in photo_queryset:
  814. # 单张照片结果
  815. indentify_result = photo_object.indentify_result
  816. mark = photo_object.mark
  817. addtime = photo_object.addtime
  818. pest_dict = {}
  819. if amend == "1" and mark:
  820. mark = json.loads(mark)
  821. for label in mark:
  822. pest_name = label.get("text")
  823. pest_num = 1
  824. if select_name and select_name not in pest_name:
  825. continue
  826. if pest_name in pest_dict:
  827. pest_dict[pest_name] += pest_num
  828. else:
  829. pest_dict[pest_name] = pest_num
  830. for label_key,label_value in pest_dict.items():
  831. pest_base_data.append(dict(pest_name=label_key,pest_num=label_value,addtime=addtime))
  832. else:
  833. for result in indentify_result.split("#"):
  834. tuple_result = result.split(",")
  835. pest_name = insect_dict.get(tuple_result[0],"未命名")
  836. if select_name and select_name not in pest_name:
  837. continue
  838. pest_num = int(tuple_result[1])
  839. pest_dict=dict(pest_name=pest_name,pest_num=pest_num,addtime=addtime)
  840. pest_base_data.append(pest_dict)
  841. return_data = pest_base_data[(page-1)*page_size:page*page_size]
  842. return {"pest_image_data":return_data,"total_count":len(pest_base_data),"current_count":len(return_data)}
  843. def pest_enumeration(request):
  844. """
  845. 虫情地图
  846. 指定时间段内害虫列举接口
  847. 参数:
  848. start_time 必传(秒级时间戳) 开始时间
  849. end_time 必传(秒级时间戳) 结束时间
  850. 返回:
  851. {
  852. "data": ["杨二尾舟蛾","劳氏粘虫", ...]
  853. }
  854. """
  855. parameters = request.POST
  856. start_time = parameters.get("start_time")
  857. end_time = parameters.get("end_time")
  858. if start_time:
  859. start_time = int(start_time)
  860. else:
  861. raise PortError("start_time","参数缺失")
  862. if end_time:
  863. end_time = int(end_time)
  864. else:
  865. raise PortError("end_time","参数缺失")
  866. pest_cursor = Pest_distribute.objects.filter(uptime__gte=start_time, uptime__lte=end_time).values("pest_name")
  867. pest_name_lists = [pest_obj["pest_name"] for pest_obj in pest_cursor]
  868. return pest_name_lists
  869. def pest_tendency(request):
  870. """
  871. 虫情地图
  872. 虫情趋势接口
  873. 参数:
  874. pest_name 必传(str) 害虫名称
  875. req 必传(str) 筛选条件('start':始见期,'end':终见期,'focus':高峰期)
  876. start_time 必传(秒级时间戳) 开始时间
  877. end_time 必传(秒级时间戳) 结束时间
  878. 返回:
  879. {
  880. "data": [
  881. {
  882. "province": "广东省",
  883. "city": "揭阳市",
  884. "uptime": 1659801600
  885. },
  886. {
  887. "province": "辽宁省",
  888. "city": "沈阳市",
  889. "uptime": 1659715200
  890. },
  891. ...
  892. ]
  893. }
  894. """
  895. parameters = request.POST
  896. pest_name = parameters.get("pest_name")
  897. start_time = parameters.get("start_time")
  898. end_time = parameters.get("end_time")
  899. if not pest_name:
  900. raise PortError("pest_name","参数缺失")
  901. if start_time:
  902. start_time = int(start_time)
  903. else:
  904. raise PortError("start_time","参数缺失")
  905. if end_time:
  906. end_time = int(end_time)
  907. else:
  908. raise PortError("end_time","参数缺失")
  909. req = parameters.get("req")
  910. if req == "start":
  911. req_sort = {"uptime": 1}
  912. elif req == "end":
  913. req_sort = {"uptime": -1}
  914. elif req == "focus":
  915. req_sort = {"avg_num": -1}
  916. else:
  917. raise PortError("req","参数异常")
  918. pest_cursor = Pest_distribute.objects.filter(
  919. pest_name=pest_name, uptime__gte=start_time, uptime_lte=end_time).values(
  920. "province", "city").annotate(pest_count=Max("uptime")).values("province", "city", "uptime").order_by('-uptime')
  921. data = [pest_obj for pest_obj in pest_cursor]
  922. return data
  923. def pest_distribution(request):
  924. """
  925. 虫情地图
  926. 虫情密度 地域分布接口
  927. 参数:
  928. pest_name 必传(str) 害虫名称
  929. start_time 必传(秒级时间戳) 开始时间
  930. end_time 必传(秒级时间戳) 结束时间
  931. 返回:
  932. {
  933. "data":[
  934. {
  935. "province": "江苏省",
  936. "city": "淮安市",
  937. "pest_count": 4.33
  938. },
  939. {
  940. "province": "四川省",
  941. "city": "达州市",
  942. "pest_count": 3.0
  943. },
  944. ...
  945. ]
  946. }
  947. """
  948. parameters = request.POST
  949. pest_name = parameters.get("pest_name")
  950. start_time = parameters.get("start_time")
  951. end_time = parameters.get("end_time")
  952. if not pest_name:
  953. raise PortError("pest_name","参数缺失")
  954. if start_time:
  955. start_time = int(start_time)
  956. else:
  957. raise PortError("start_time","参数缺失")
  958. if end_time:
  959. end_time = int(end_time)
  960. else:
  961. raise PortError("end_time","参数缺失")
  962. pest_cursor = Pest_distribute.objects.filter(
  963. pest_name=pest_name, uptime__gte=start_time, uptime_lte=end_time).values(
  964. "province", "city").annotate(pest_count=Sum("pest_count")).values(
  965. "province", "city", "pest_count")
  966. data = []
  967. for pest_obj in pest_cursor:
  968. pest_obj["pest_count"] = round(pest_obj["pest_count"],2)
  969. data.append(pest_obj)
  970. return data
  971. def pest_statistics(request):
  972. """
  973. 害虫统计页面
  974. 害虫变化趋势折线图
  975. 参数:
  976. d_id 必传 设备自增id
  977. start_time 非必传(string 时间戳) 开始时间 (用于时间搜索)
  978. end_time 非必传(string 时间戳) 结束时间 (用于时间搜索)
  979. pest_name 非必传(str) 害虫名称
  980. 返回值:
  981. "broken_line": [
  982. {
  983. "addtime": 1590230292, 时间
  984. "temperature": 39.8, 温度
  985. "humidity": 34.9, 湿度
  986. "_sums": 17 这个时间点的害虫总数
  987. "_sname": 蛾子 害虫名字
  988. },
  989. "date":[ 害虫搜索出来的数据
  990. {
  991. "addtime": 1590230292, 时间
  992. "temperature": 39.8, 温度
  993. "humidity": 34.9, 湿度
  994. "_sums": 17 这个时间点的害虫总数
  995. "_sname": 蛾子 害虫名字
  996. },
  997. ],....]
  998. "device_name":"这里是设备名称",
  999. "address": "这里是设备位置",
  1000. "disable":device.disable, #0 不识别,1识别 2,计数
  1001. """
  1002. post_info = request.POST
  1003. d_id = post_info.get("d_id")
  1004. identify_model = post_info.get("identify_model")
  1005. start_time = post_info.get("start_time")
  1006. end_time = post_info.get("end_time")
  1007. pest_name = post_info.get("pest_name","")
  1008. if not d_id:
  1009. raise PortError('device_id', "设备不能为空")
  1010. device = MongoDevice.objects.get(id=d_id)
  1011. province = device.province
  1012. city = device.city
  1013. district = device.district
  1014. device_name = device.device_name
  1015. myuser = request.myuser
  1016. if not myuser.user_type == 1 and device.device_expire == "1":
  1017. if identify_model == "B":
  1018. 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')
  1019. else:
  1020. 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')
  1021. if end_time and int(end_time) > int(device.device_expire_time):
  1022. end_time = device.device_expire_time
  1023. cbdphotos = cbdphotos.filter(addtime__range=(int(start_time),int(end_time)))
  1024. else:
  1025. if identify_model == "B":
  1026. cbdphotos = CBDphoto_B.objects.filter(~Q(indentify_photo=None),device_id=d_id,photo_status=1).order_by('-addtime')
  1027. else:
  1028. cbdphotos = MongoCBDphoto.objects.filter(~Q(indentify_photo=None),device_id=d_id,photo_status=1).order_by('-addtime')
  1029. if start_time:
  1030. cbdphotos = cbdphotos.filter(addtime__gte=int(start_time))
  1031. if end_time:
  1032. cbdphotos = cbdphotos.filter(addtime__lte=int(end_time))
  1033. page = post_info.get('page',1)
  1034. if page:
  1035. page = int(page)
  1036. page_size = post_info.get('page_size')
  1037. start = ''
  1038. end = ''
  1039. if page_size:
  1040. page_size = int(page_size)
  1041. if page and page_size:
  1042. start = max((page - 1), 0) * page_size
  1043. end = page * page_size
  1044. date = []
  1045. d_sums = {}
  1046. indentify_photos = {}
  1047. percentage = []
  1048. counts = ''
  1049. time_d_sums = []
  1050. nums = 0
  1051. nusm = 0
  1052. for c in cbdphotos:
  1053. photo_id = c.id
  1054. indentify_photo = c.indentify_photo
  1055. if not indentify_photo:
  1056. continue
  1057. if not indentify_photo.startswith('http'):
  1058. if str(indentify_photo).startswith('/'):
  1059. indentify_photo = config_dict['image_url']["discern"] + indentify_photo
  1060. else:
  1061. indentify_photo = config_dict['image_url']["discern"] + "/" + indentify_photo
  1062. if not pest_name:
  1063. time_d_sums.append({"pest": c.indentify_result,
  1064. "addtime": c.addtime,
  1065. "result_photo":indentify_photo,
  1066. "mark":c.mark,
  1067. })
  1068. if c.indentify_result != None and c.indentify_result != "":
  1069. sums = c.indentify_result.split('#')
  1070. for i in sums:
  1071. i_result = i.split(',')
  1072. if pest_name == insect_dict[i_result[0]]:
  1073. date.append({
  1074. "temperature": c.at,
  1075. "humidity": c.ah,
  1076. "addtime": c.addtime,
  1077. "_sums": i_result[1],
  1078. "_sname":insect_dict[i_result[0]],
  1079. })
  1080. if not pest_name:
  1081. _result = sums[0].split(',')
  1082. date.append({
  1083. "temperature": c.at,
  1084. "humidity": c.ah,
  1085. "addtime": c.addtime,
  1086. "_sums": _result[1],
  1087. "_sname": insect_dict[_result[0]]})
  1088. nums += int(_result[1])
  1089. d_sums.setdefault(i_result[0], []).append(int(i_result[1]))
  1090. indentify_photos.setdefault(i_result[0], []).append(photo_id)
  1091. # 增加用户手动标注的数据
  1092. # _nums = count + num
  1093. if c.mark:
  1094. mark = json.loads(c.mark)
  1095. for y in mark:
  1096. if pest_name == y["tagName"]:
  1097. nusm += 1
  1098. date.append({
  1099. "temperature": c.at,
  1100. "humidity": c.ah,
  1101. "addtime": c.addtime,
  1102. "_sums": nusm,
  1103. "_sname":y["tagName"]})
  1104. if not pest_name:
  1105. nusm += 1
  1106. date.append({
  1107. "temperature": c.at,
  1108. "humidity": c.ah,
  1109. "addtime": c.addtime,
  1110. "_sums": nusm,
  1111. "_sname":y["tagName"]})
  1112. d_sums.setdefault(y["tagName"], []).append(1)
  1113. indentify_photos.setdefault(y["tagName"], []).append(photo_id)
  1114. user_type = request.myuser.user_type
  1115. if user_type == 1:
  1116. disable = 1
  1117. else:
  1118. disable = device.disable
  1119. if not pest_name:
  1120. # user_type =
  1121. if disable == 0:
  1122. percentage = "设备不具备识别功能"
  1123. raise PortError('device_id', "此设备不具备识别功能")
  1124. elif disable == 1:
  1125. for k,v in d_sums.items():
  1126. try:
  1127. name_num = insect_dict[k]
  1128. except:
  1129. name_num = k
  1130. percentage.append({
  1131. "name_num":name_num,
  1132. "sum": sum(v),
  1133. "indentify_photos":indentify_photos[k],
  1134. "num":k})
  1135. #percentage = [{"name_num": insect_dict[k], "sum": sum(v),"indentify_photos":indentify_photos[k],"num":k} for k, v in d_sums.items()]
  1136. counts = len(percentage)
  1137. if start or end:
  1138. percentage = percentage[start:end]
  1139. time_d_sums = time_d_sums[start:end]
  1140. elif disable == 2:
  1141. percentage = nums
  1142. if start or end:
  1143. time_d_sums = time_d_sums[start:end]
  1144. data = {
  1145. "disable":disable, #0 不识别,1识别 2,计数
  1146. "percentage":percentage, # 统计
  1147. "time_d_sums":time_d_sums, # 时间详细
  1148. "device_name":device_name,
  1149. "address": province + city + district,
  1150. "counts":counts,
  1151. "date":date, #饼状图
  1152. }
  1153. return data
  1154. # import copy
  1155. import operator
  1156. def pest_statistics_total(request):
  1157. """
  1158. 害虫统计页面
  1159. 害虫变化趋势折线图
  1160. 参数:
  1161. start_time 非必传(string 时间戳) 开始时间 (用于时间搜索)
  1162. end_time 非必传(string 时间戳) 结束时间 (用于时间搜索)
  1163. pest_name 非必传(str) 害虫名称
  1164. 返回值:
  1165. "broken_line": [
  1166. {
  1167. "addtime": 1590230292, 时间
  1168. "at": 39.8, 温度
  1169. "ah": 34.9, 湿度
  1170. "_sums": 17 这个时间点的害虫总数
  1171. "_sname": 蛾子 害虫名字
  1172. },
  1173. "date":[ 害虫搜索出来的数据
  1174. {
  1175. "addtime": 1590230292, 时间
  1176. "at": 39.8, 温度
  1177. "ah": 34.9, 湿度
  1178. "_sums": 17 这个时间点的害虫总数
  1179. "_sname": 蛾子 害虫名字
  1180. },
  1181. ],....]
  1182. "device_name":"这里是设备名称",
  1183. "address": "这里是设备位置",
  1184. """
  1185. post_info = request.POST
  1186. start_time = post_info.get("start_time")
  1187. end_time = post_info.get("end_time")
  1188. pest_name = post_info.get("pest_name","")
  1189. myuser = request.myuser
  1190. devices = MongoDevice.devices(uid=myuser.uid,myuser=myuser)
  1191. if myuser.user_type != 4 or myuser.user_type != 1:
  1192. devices = devices.filter(disable=1)
  1193. #自动统计
  1194. date = []
  1195. d_sums = {}
  1196. percentage = []
  1197. time_d_sums = []
  1198. counts = ""
  1199. for i in devices:
  1200. if not myuser.user_type == 1 and i.device_expire == "1":
  1201. 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')
  1202. if end_time and int(end_time) > int(i.device_expire_time):
  1203. end_time = i.device_expire_time
  1204. cbd_data = cbd_data.filter(addtime__range=(int(start_time),int(end_time)))
  1205. else:
  1206. cbd_data = MongoCBDphoto.objects.filter(~Q(indentify_photo=None),device_id=i.id,photo_status=1).order_by('-id')
  1207. if start_time:
  1208. cbd_data = cbd_data.filter(addtime__range=(int(start_time),int(end_time)))
  1209. page = post_info.get('page',1)
  1210. if page:
  1211. page = int(page)
  1212. page_size = post_info.get('page_size')
  1213. start = ''
  1214. end = ''
  1215. if page_size:
  1216. page_size = int(page_size)
  1217. if page and page_size:
  1218. start = max((page - 1), 0) * page_size
  1219. end = page * page_size
  1220. counts = ''
  1221. for c in cbd_data:
  1222. indentify_photo = c.indentify_photo
  1223. if not indentify_photo:
  1224. continue
  1225. if not indentify_photo.startswith('http'):
  1226. if str(indentify_photo).startswith('/'):
  1227. indentify_photo = config_dict['image_url']["discern"] + indentify_photo
  1228. else:
  1229. indentify_photo = config_dict['image_url']["discern"] + "/" + indentify_photo
  1230. if not pest_name:
  1231. time_d_sums.append({"pest": c.indentify_result,
  1232. "addtime": c.addtime,
  1233. "result_photo":indentify_photo,
  1234. })
  1235. if c.indentify_result != None and c.indentify_result != "":
  1236. sums = c.indentify_result.split('#')
  1237. for i in sums:
  1238. i_result = i.split(',')
  1239. if pest_name == insect_dict[i_result[0]]:
  1240. date.append({
  1241. "temperature": c.at,
  1242. "humidity": c.ah,
  1243. "addtime": c.addtime,
  1244. "_sums": i_result[1],
  1245. "_sname":insect_dict[i_result[0]],
  1246. })
  1247. if not pest_name:
  1248. _result = sums[0].split(',')
  1249. date.append({
  1250. "temperature": c.at,
  1251. "humidity": c.ah,
  1252. "addtime": c.addtime,
  1253. "_sums": int(_result[1]),
  1254. "_sname": insect_dict[_result[0]],
  1255. })
  1256. d_sums.setdefault(i_result[0], []).append(int(i_result[1]))
  1257. if not pest_name:
  1258. percentage = [{"name_num": insect_dict[k], "sum": sum(v),"num":k} for k, v in d_sums.items()]
  1259. counts = len(percentage)
  1260. if start or end:
  1261. percentage = percentage[start:end]
  1262. time_d_sums = time_d_sums[start:end]
  1263. data = {}
  1264. if pest_name:
  1265. for item in date:
  1266. add_time, _sums, _sname,at,ah = item['addtime'], item['_sums'], item['_sname'],item["temperature"],item["humidity"]
  1267. key = '{}_{}_{}_{}'.format(add_time, _sname,at,ah)
  1268. if key in data:
  1269. data[key] += _sums
  1270. else:
  1271. data[key] = _sums
  1272. result = []
  1273. for key, value in data.items():
  1274. add_time, _sname,at,ah= key.split('_')
  1275. result.append({
  1276. "addtime": add_time,
  1277. "_sums": data[key],
  1278. "_sname": _sname,
  1279. "at" : at,
  1280. "ah": ah
  1281. })
  1282. else:
  1283. for item in date:
  1284. add_time, _sums, _sname, at, ah = item['addtime'], item['_sums'], item['_sname'],item["temperature"],item["humidity"]
  1285. key = '{}_{}_{}_{}'.format(_sname,add_time,at,ah)
  1286. if key in data:
  1287. data[key] += _sums
  1288. else:
  1289. data[key] = _sums
  1290. result = []
  1291. for key, value in data.items():
  1292. _sname,add_time,at,ah= key.split('_')
  1293. result.append({
  1294. "addtime": add_time,
  1295. "_sums": data[key],
  1296. "_sname": _sname,
  1297. "at" : at,
  1298. "ah": ah
  1299. })
  1300. # 降序
  1301. # list2 = sorted(result, key=operator.itemgetter('addtime'),reverse=True)
  1302. list2 = sorted(result, key=operator.itemgetter('addtime'))
  1303. data = {
  1304. "percentage":percentage, # 统计
  1305. "time_d_sums":time_d_sums, # 时间详细
  1306. # "address": province + city + district,
  1307. "counts":counts,
  1308. "date":list2, #饼状图
  1309. }
  1310. return data
  1311. def pest_contrast_total(request):
  1312. """
  1313. 某一害虫对比
  1314. 参数:
  1315. d_id 必传(str) 设备id
  1316. start_time 非必传(string 时间戳) 开始时间 (用于时间搜索)
  1317. end_time 非必传(string 时间戳) 结束时间 (用于时间搜索)
  1318. pest_name 非必传(str) 害虫名称
  1319. 返回值:
  1320. """
  1321. post_info = request.POST
  1322. start_time = post_info.get("start_time")
  1323. identify_model = post_info.get("identify_model")
  1324. end_time = post_info.get("end_time")
  1325. pest_name = post_info.get("pest_name","")
  1326. d_id = post_info.get("d_id")
  1327. if not d_id:
  1328. raise PortError('device_id', "设备不能为空")
  1329. device = Device.objects.get(id=d_id)
  1330. myuser = request.myuser
  1331. if not myuser.user_type == 1 and device.device_expire == "1":
  1332. if identify_model == "B":
  1333. 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")
  1334. else:
  1335. 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")
  1336. if end_time and int(end_time) > int(device.device_expire_time):
  1337. end_time = device.device_expire_time
  1338. cbd_data = cbd_data.filter(addtime__range=(int(start_time),int(end_time)))
  1339. else:
  1340. if identify_model == "B":
  1341. cbd_data = CBDphoto_B.objects.filter(~Q(indentify_photo=None),device_id=device.id,photo_status=1).order_by("-id")
  1342. else:
  1343. cbd_data = CBDphoto.objects.filter(~Q(indentify_photo=None),device_id=device.id,photo_status=1).order_by("-id")
  1344. if start_time:
  1345. cbd_data = cbd_data.filter(addtime__range=(int(start_time),int(end_time)))
  1346. # cbdphotos = CBDphoto.objects.filter(~Q(indentify_photo=None),device_id=d_id).order_by('-id')
  1347. # if start_time:
  1348. # cbdphotos = cbdphotos.filter(addtime__gte=int(start_time))
  1349. # if end_time:
  1350. # cbdphotos = cbdphotos.filter(addtime__lte=int(end_time))
  1351. date = []
  1352. d_sums = {}
  1353. indentify_photos = {}
  1354. percentage = []
  1355. for c in cbd_data:
  1356. photo_id = c.id
  1357. indentify_photo = c.indentify_photo
  1358. if not indentify_photo:
  1359. continue
  1360. elif not c.indentify_result:
  1361. continue
  1362. sums = c.indentify_result.split('#')
  1363. for i in sums:
  1364. i_result = i.split(',')
  1365. if pest_name == insect_dict[i_result[0]]:
  1366. date.append({
  1367. "temperature": c.at,
  1368. "humidity": c.ah,
  1369. "addtime": c.addtime,
  1370. "_sums": i_result[1],
  1371. "_sname":insect_dict[i_result[0]],
  1372. })
  1373. if not pest_name:
  1374. date.append({
  1375. "temperature": c.at,
  1376. "humidity": c.ah,
  1377. "addtime": c.addtime,
  1378. "_sums": int(i_result[1]),
  1379. "_sname": insect_dict[i_result[0]],
  1380. })
  1381. d_sums.setdefault(i_result[0], []).append(int(i_result[1]))
  1382. indentify_photos.setdefault(i_result[0], []).append(photo_id)
  1383. if not pest_name:
  1384. percentage = [{"name_num": insect_dict[k], "sum": sum(v),"indentify_photos":indentify_photos[k],"num":k} for k, v in d_sums.items()]
  1385. data = {}
  1386. if pest_name:
  1387. for item in date:
  1388. add_time, _sums, _sname,at,ah = item['addtime'], item['_sums'], item['_sname'],item["temperature"],item["humidity"]
  1389. key = '{}_{}_{}_{}'.format(add_time, _sname,at,ah)
  1390. if key in data:
  1391. data[key] += _sums
  1392. else:
  1393. data[key] = _sums
  1394. result = []
  1395. for key, value in data.items():
  1396. add_time, _sname,at,ah= key.split('_')
  1397. result.append({
  1398. "addtime": add_time,
  1399. "_sums": data[key],
  1400. "_sname": _sname,
  1401. "at" : at,
  1402. "ah": ah
  1403. })
  1404. else:
  1405. for item in date:
  1406. add_time, _sums, _sname, at, ah = item['addtime'], item['_sums'], item['_sname'],item["temperature"],item["humidity"]
  1407. key = '{}_{}_{}_{}'.format(_sname,add_time,at,ah)
  1408. if key in data:
  1409. data[key] += _sums
  1410. else:
  1411. data[key] = _sums
  1412. result = []
  1413. for key, value in data.items():
  1414. _sname,add_time,at,ah= key.split('_')
  1415. result.append({
  1416. "addtime": add_time,
  1417. "_sums": data[key],
  1418. "_sname": _sname,
  1419. "at" : at,
  1420. "ah": ah
  1421. })
  1422. # 降序
  1423. # list2 = sorted(result, key=operator.itemgetter('addtime'),reverse=True)
  1424. list2 = sorted(result, key=operator.itemgetter('addtime'))
  1425. data = {
  1426. "percentage":percentage,
  1427. "list2":list2
  1428. }
  1429. return data
  1430. def photo_result(request):
  1431. """
  1432. 害虫统计页面
  1433. 害虫变化趋势折线图
  1434. 参数:
  1435. photo_ids 必传 照片自增id
  1436. """
  1437. post_info = request.POST
  1438. photo_ids = post_info.get("photo_ids","")
  1439. if not photo_ids:
  1440. raise PortError('photo_ids', "不能为空")
  1441. photo_ids = [int(i) for i in eval(photo_ids)]
  1442. cbdphotos = MongoCBDphoto.objects.filter(id__in=photo_ids).order_by('-id')
  1443. data = []
  1444. for p in cbdphotos:
  1445. indentify_photo = p.indentify_photo
  1446. if not indentify_photo.startswith('http'):
  1447. if str(indentify_photo).startswith('/'):
  1448. indentify_photo = config_dict['image_url']["discern"] + indentify_photo
  1449. else:
  1450. indentify_photo = config_dict['image_url']["discern"] + "/" + indentify_photo
  1451. data.append(
  1452. {
  1453. "indentify_photo":indentify_photo,
  1454. "indentify_result":p.indentify_result,
  1455. }
  1456. )
  1457. return data
  1458. def pest_manual_statistics(request):
  1459. """
  1460. 病虫害手动统计接口/害虫名称搜索:
  1461. 参数:
  1462. device_id 必传(str) 设备id
  1463. start_time 非必传(时间戳) 开始时间
  1464. end_time 非必传(时间戳) 结束时间
  1465. pest_name 非必传(str) 害虫名
  1466. """
  1467. device_id = request.POST.get('device_id')
  1468. start_time = request.POST.get("start_time")
  1469. end_time = request.POST.get("end_time")
  1470. pest_name = request.POST.get("pest_name")
  1471. page = int(request.POST.get('page',1))
  1472. try:
  1473. device = MongoDevice.objects.get(id=device_id)
  1474. except:
  1475. raise PortError('device_id', "没有该设备")
  1476. if not device_id:
  1477. raise PortError('device_id', "没有传设备号")
  1478. myuser = request.myuser
  1479. if not myuser.user_type == 1 and device.device_expire == "1":
  1480. cbdphotos = Device_Desc.objects.filter(device_id=device_id)
  1481. if end_time and int(end_time) > int(device.device_expire_time):
  1482. end_time = device.device_expire_time
  1483. cbdphotos = cbdphotos.filter(addtime__range=(int(start_time),int(end_time)))
  1484. else:
  1485. cbdphotos = Device_Desc.objects.filter(device_id=device_id)
  1486. if start_time:
  1487. cbdphotos = cbdphotos.filter(add_time__gte=start_time)
  1488. if end_time:
  1489. cbdphotos = cbdphotos.filter(add_time__lte=end_time)
  1490. dat = [] # 害虫名称
  1491. data = [] # 饼状图
  1492. date = [] # 列表
  1493. pest = [] # 折线图
  1494. if cbdphotos:
  1495. for i in cbdphotos:
  1496. cbd_img_list = MongoCBDphoto.objects.filter(id=i.photo_id)
  1497. pest_num = 0
  1498. if i.pest_name not in dat:
  1499. dat.append(i.pest_name)
  1500. pest_list = cbdphotos.filter(pest_name=i.pest_name)
  1501. for y in pest_list:
  1502. pest_num += int(y.pest_num)
  1503. data.append({"pest_name":i.pest_name,"pest_num":pest_num})
  1504. image = ""
  1505. for x in cbd_img_list:
  1506. image = x.addr
  1507. if image.startswith("http"):
  1508. image = image
  1509. else:
  1510. image = config_dict["image_url"]["frond"] + image
  1511. date.append({
  1512. "pest_num":i.pest_num,
  1513. "pest_name":i.pest_name,
  1514. "crop_name":i.crop_name,
  1515. "pest_case":i.pest_case,
  1516. "add_time":i.add_time,
  1517. "image":image
  1518. })
  1519. dat_list = date[(10*(page-1)):(page*10)]
  1520. else:
  1521. dat_list = []
  1522. if dat:
  1523. if pest_name:
  1524. pest_list = cbdphotos.filter(pest_name=pest_name)
  1525. else:
  1526. pest_list = cbdphotos.filter(pest_name=dat[0])
  1527. pest_name = dat[0]
  1528. for ii in pest_list:
  1529. pests = {"pest_name":pest_name}
  1530. if pest_name == ii.pest_name:
  1531. pest.append({
  1532. "pest_num":ii.pest_num,
  1533. "add_time":ii.add_time})
  1534. pests["pest_list"] = pest
  1535. else:
  1536. pests = {}
  1537. nums = cbdphotos.count()
  1538. data = {"nums":nums,"dat":data,"date":dat_list,"pests":pests}
  1539. return data
  1540. from django.db.models import Q
  1541. import time
  1542. import pymysql
  1543. # 已弃用
  1544. # @kedong_deco(login_required=True)
  1545. def worm_list(request):
  1546. """
  1547. 害虫列表
  1548. 参数;
  1549. 暂无
  1550. 返回值:
  1551. "data": [
  1552. {
  1553. "name": "暗纹紫褐螟",
  1554. "num": "317"
  1555. },....
  1556. ]
  1557. """
  1558. insect_dict = ""
  1559. try:
  1560. dir_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))))
  1561. path = os.path.join(dir_path, "scripts/pest_dict.json")
  1562. with open(path,'r',encoding='utf-8') as f:
  1563. insect_dict = json.loads(f.read())
  1564. except Exception as e:
  1565. path = sys.path[0] + "/scripts/pest_dict.json"
  1566. with open(path,'r',encoding='utf-8') as f:
  1567. insect_dict = json.loads(f.read())
  1568. return insect_dict
  1569. @kedong_deco(login_required=True)
  1570. def cbd_pest_warning(request):
  1571. """
  1572. 测报灯-害虫预警
  1573. 2022-05-19 14:22 csx
  1574. 参数:
  1575. page 非必传(num) 页码,默认为1
  1576. page_size 非必传(num) 每页数量,默认为10
  1577. status 非必传(str) 为yes时 是设置一键已读
  1578. d_id 非必传(str) 传id时,为单个数据设置已读
  1579. device_id 非必传(str) 传设备号时,为当前设备的预警信息
  1580. 返回值:
  1581. {
  1582. "errorCode": 0,
  1583. "message": "",
  1584. "formError": {},
  1585. "data": {
  1586. "data": [
  1587. {
  1588. "device_id": "862167051501330", 设备号
  1589. "warning_content": 4, 害虫种类数
  1590. "warning_status": "1", 1目标种类预警 2、指定害虫数量预警 3 害虫数量总和预警 4综合预警
  1591. "upltime": 1652936123, 时间戳
  1592. "status": 0 0未读 1已读
  1593. },
  1594. {
  1595. "device_id": "862167051501330",
  1596. "warning_content": 411,
  1597. "warning_status": "3",
  1598. "upltime": 1652936123,
  1599. "status": 0
  1600. },
  1601. {
  1602. "device_id": "862167051501330",
  1603. "warning_content": {
  1604. "铜绿丽金龟": "1头",
  1605. "水龟虫": "48头",
  1606. "龙虱": "4头",
  1607. "负子蝽": "13头"
  1608. },
  1609. "warning_status": "4",
  1610. "upltime": 1652936123,
  1611. "status": 0
  1612. },
  1613. """
  1614. page = request.POST.get('page',1)
  1615. page_size = request.POST.get('page_size',10)
  1616. status = request.POST.get('status')
  1617. d_id = request.POST.get('d_id')
  1618. deviceid = request.POST.get("device_id")
  1619. devices = MongoDevice.objects.filter(device_type_id=3)
  1620. if deviceid:
  1621. devices = devices.filter(device_id__icontains=deviceid)
  1622. devices = devices.values("device_id")
  1623. device_list = [d['device_id'] for d in devices]
  1624. if page and page_size:
  1625. page_size = int(page_size)
  1626. page = int(page)
  1627. start = max((page - 1), 0) * page_size
  1628. end = page * page_size
  1629. pest_warn = DevicePestWarning.objects.filter(device_id__in=device_list)
  1630. if d_id:
  1631. pest_warn = DevicePestWarning.objects.filter(id=d_id).update(status=1)
  1632. return True
  1633. data = []
  1634. nums = pest_warn.count()
  1635. if nums:
  1636. if status:
  1637. if status == "yes":
  1638. pest_warn.update(status=1)
  1639. return True
  1640. else:
  1641. raise PortError('',"参数错误")
  1642. for x in pest_warn.order_by("-id")[start:end]:
  1643. data.append({
  1644. "d_id":x.id,
  1645. "device_id":x.device_id,
  1646. "warning_content":eval(x.warning_content),
  1647. "warning_status":x.warning_status,
  1648. "upltime":x.upltime,
  1649. "status":x.status
  1650. })
  1651. return {"data":data,"nusm":nums}
  1652. @kedong_deco(login_required=True)
  1653. def qxz_warning(request):
  1654. """
  1655. 气象站-通道要素预警
  1656. 2022-05-20 10:22 csx
  1657. 参数:
  1658. page 非必传(num) 页码,默认为1
  1659. page_size 非必传(num) 每页数量,默认为10
  1660. status 非必传(str) 为yes时 是设置一键已读
  1661. d_id 非必传(str) 传id时,为单个数据设置已读
  1662. 返回值:
  1663. {
  1664. "errorCode": 0,
  1665. "message": "",
  1666. "formError": {},
  1667. "data": {
  1668. "data": [
  1669. {
  1670. "d_id": 1, 数据id
  1671. "device_id": "866193059770251", 设备号
  1672. "warning_content": "大于预警", 预警描述
  1673. "ekey": "空气温度#℃", 要素描述 加单位
  1674. "set_value": "13", 用户设置预警值
  1675. "current_value": "19.3", 设备当前上传的数据值
  1676. "upltime": 1653012464, 保存时间
  1677. "status": 0 0 未读 1已读
  1678. },
  1679. {
  1680. "d_id": 2,
  1681. "device_id": "866193059770251",
  1682. "warning_content": "大于预警",
  1683. "ekey": "空气温度#℃",
  1684. "set_value": "13",
  1685. "current_value": "19.3",
  1686. "upltime": 1653012757,
  1687. "status": 0
  1688. },
  1689. """
  1690. page = request.POST.get('page','1')
  1691. page_size = request.POST.get('page_size','10')
  1692. status = request.POST.get('status')
  1693. device_type = request.POST.get('device_type',"5")
  1694. d_id = request.POST.get('d_id')
  1695. if device_type not in ("5","8"):
  1696. raise PortError("","设备类型超出")
  1697. if d_id:
  1698. warn = QXZThresholdWarning.objects.filter(id=d_id).update(status=1)
  1699. return True
  1700. devices = MongoDevice.objects.filter(device_type_id=device_type)
  1701. device_list = [device_id.device_id for device_id in devices]
  1702. if page and page_size:
  1703. if not page.isdigit() and not page_size.isdigit():
  1704. raise PortError("","参数错误")
  1705. page_size = int(page_size)
  1706. page = int(page)
  1707. else:
  1708. page = 1
  1709. page_size = 10
  1710. start = max((page - 1), 0) * page_size
  1711. end = page * page_size
  1712. warn = QXZThresholdWarning.objects.filter(device_id__in=device_list)
  1713. data = []
  1714. nums = warn.count()
  1715. if nums:
  1716. if status:
  1717. if status == "yes":
  1718. warn.update(status=1)
  1719. return True
  1720. else:
  1721. raise PortError('',"参数错误")
  1722. for x in warn.order_by("-id")[start:end]:
  1723. data.append({
  1724. "d_id":x.id,
  1725. "device_id":x.device_id,
  1726. "warning_content":x.warning_content,
  1727. "ekey":x.ekey,
  1728. "set_value":x.set_value,
  1729. "current_value":x.current_value,
  1730. "upltime":x.upltime,
  1731. "status":x.status
  1732. })
  1733. return {"data":data,"nusm":nums}
  1734. @kedong_deco(login_required=True)
  1735. def xycb_pest_chart(request):
  1736. """
  1737. 性诱1.0,3.0设备害虫折线图
  1738. 参数:
  1739. d_id 必传 设备id
  1740. start_time 必传(string 秒级时间戳) 开始时间
  1741. end_time 必传(string 秒级时间戳) 结束时间
  1742. device_type_id 必传 设备类型编号 4性诱测报1.0, 8性诱测报3.0
  1743. return
  1744. {
  1745. "total_num": 0,
  1746. "pest_data": [
  1747. {
  1748. "pest_num": 0,
  1749. "addtime": 1659024000
  1750. },
  1751. ]
  1752. }
  1753. """
  1754. post_info = request.POST
  1755. start_time = post_info.get('start_time')
  1756. end_time = post_info.get('end_time')
  1757. d_id = post_info.get("d_id")
  1758. device_type_id = post_info.get("device_type_id")
  1759. if d_id:
  1760. d_id = int(d_id)
  1761. else:
  1762. raise PortError('d_id', "请输入设备id")
  1763. if device_type_id:
  1764. device_type_id = int(device_type_id)
  1765. else:
  1766. raise PortError("device_type_id", "请输入设备类型编号")
  1767. if start_time:
  1768. start_time = int(start_time)
  1769. else:
  1770. raise PortError('start_time', "请输入设备start_time")
  1771. if end_time:
  1772. end_time = int(end_time)
  1773. else:
  1774. raise PortError('end_time', "请输入设备end_time")
  1775. try:
  1776. device = MongoDevice.objects.get(id=d_id)
  1777. device_expire = device.device_expire
  1778. device_expire_time = device.device_expire_time
  1779. except:
  1780. raise PortError('device_id', "暂无此设备")
  1781. myuser_type = request.myuser.user_type
  1782. if not myuser_type == 1 and not myuser_type == 5 and device_expire == "1":
  1783. if end_time > int(device_expire_time):
  1784. end_time = int(device_expire_time)
  1785. if end_time < start_time:
  1786. raise PortError("expire time", "设备已到期")
  1787. queryset = MongoXYCBData.objects.filter(device_id=d_id, addtime__gte=start_time, addtime__lte=end_time).order_by('-addtime')
  1788. pest_data = []
  1789. total_pest_num = 0
  1790. for item in queryset:
  1791. try:
  1792. device_data = json.loads((str(item.device_data)).replace("'", '"'))
  1793. infr_ct = device_data['infr_ct']
  1794. addtime = item.addtime
  1795. pest_data.append({
  1796. "pest_num": infr_ct,
  1797. "addtime": addtime
  1798. })
  1799. try:
  1800. infr_ct = int(infr_ct)
  1801. except Exception as e:
  1802. infr_ct = 0
  1803. total_pest_num += infr_ct
  1804. except Exception as e:
  1805. logger.error(f"Json 解析错误:{e}")
  1806. return {"total_num": 0, "pest_data": []}
  1807. return {"total_num": total_pest_num, "pest_data": pest_data}
  1808. @kedong_deco(login_required=True)
  1809. def set_decopy(request):
  1810. """
  1811. 设置诱芯接口
  1812. 参数:
  1813. device_type_id 必传 设备类型ID
  1814. device_id 必传 设备编号
  1815. decoy 必传 诱芯名称
  1816. expire_time 非必传 诱芯过期时间
  1817. """
  1818. post_info = request.POST
  1819. device_type_id = post_info.get("device_type_id")
  1820. device_id = post_info.get("device_id")
  1821. decoy = post_info.get("decoy")
  1822. expire_time = post_info.get("expire_time")
  1823. if not device_id:
  1824. raise PortError("device_id","参数缺失")
  1825. if not decoy:
  1826. raise PortError("decoy","参数缺失")
  1827. now_timestamp = int(time.time())
  1828. if device_type_id == "4" or device_type_id == "8":
  1829. try:
  1830. device_object = MongoDevice.objects.get(device_id=device_id)
  1831. except Exception as e:
  1832. raise PortError("device_id","未查找到该设备")
  1833. device_object.decoy = decoy
  1834. else:
  1835. raise PortError("device_type_id","参数缺失")
  1836. device_object.xy_uptime = now_timestamp
  1837. if expire_time:
  1838. device_object.xy_expire_time = int(expire_time)
  1839. device_object.save()
  1840. return {"status":True}