worm_lamp.py 74 KB

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