worm_lamp.py 75 KB

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