worm_lamp.py 79 KB

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