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