yf_yzl 2 лет назад
Родитель
Сommit
ef8a170bcc
1 измененных файлов с 98 добавлено и 85 удалено
  1. 98 85
      scripts/cbd_msg.py

+ 98 - 85
scripts/cbd_msg.py

@@ -1,8 +1,9 @@
 import os
 import sys
 import time
+import logging
 import django
-import json
+import schedule
 from datetime import datetime, timedelta
 local_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 print(local_path)
@@ -17,96 +18,108 @@ from smartfarming.models.pest_count import MongoCBDPestWarning
 from smartfarming.api.views.forecast.all_dict import insect_dict
 
 
+logger = logging.getLogger("other")
 
-# 获取所有的预警配置
-msg_conf = MongoMsg_Conf.objects.all()
-for msg in msg_conf:
-    # 获取device_id  conf
-    device_id = msg.device_id
-    conf = eval(msg.conf) 
-    # 获取该device_id 下前一天的害虫情况
-    now = datetime.now()
-    now_stamp = int(time.time())
-    previous_day = now - timedelta(days=1)
-    start_time = datetime(previous_day.year, previous_day.month, previous_day.day, 0, 0, 0).timestamp()
-    end_time = datetime(now.year, now.month, now.day, 23, 59, 59).timestamp()
-    print("起始时间:", start_time)
-    print("结束时间:", end_time)
-    photo_data = MongoCBDphoto.objects.filter(addtime__range = [start_time, end_time]).values_list("indentify_result", flat=True)
-    # 把当天的害虫统计出来
-    indentify_result = {}
-    for p in photo_data:
-        tmp = p.split("#")
-        for tp in tmp:
-            k = tp.split(",")
-            if k[0] in indentify_result.keys():
-                indentify_result[k[0]] += int(k[1])
-            else:
-                indentify_result[k[0]] = int(k[1])
+def product_cbd_alarm():
+    # 获取所有的预警配置
+    msg_conf = MongoMsg_Conf.objects.all()
+    for msg in msg_conf:
+        # 获取device_id  conf
+        device_id = msg.device_id
+        conf = eval(msg.conf) 
+        # 获取该device_id 下前一天的害虫情况
+        now = datetime.now()
+        now_stamp = int(time.time())
+        previous_day = now - timedelta(days=1)
+        start_time = datetime(previous_day.year, previous_day.month, previous_day.day, 0, 0, 0).timestamp()
+        end_time = datetime(now.year, now.month, now.day, 23, 59, 59).timestamp()
+        photo_data = MongoCBDphoto.objects.filter(addtime__range = [start_time, end_time]).values_list("indentify_result", flat=True)
+        # 把当天的害虫统计出来
+        indentify_result = {}
+        for p in photo_data:
+            tmp = p.split("#")
+            for tp in tmp:
+                k = tp.split(",")
+                if k[0] in indentify_result.keys():
+                    indentify_result[k[0]] += int(k[1])
+                else:
+                    indentify_result[k[0]] = int(k[1])
 
-    # 定义预警变量
-    warning_result = ""
-    # 指定害虫数量预警
-    appointPest = conf.get("appointPest")
-    if appointPest == "on":
-        appointPestName = conf.get("appointPestName")
-        appointPestNum = conf.get("appointPestNum")
-        pest_cg = appointPestName.split("#")
-        pest_nu = appointPestNum.split("#")
-        for i in pest_cg:
-            if i in indentify_result.keys():
-                if indentify_result[i] > int(pest_nu[pest_cg.index(i)]):
-                    zh = insect_dict.get(i, "未知")
-                    warning_result += f"害虫{zh}数量{str(indentify_result[i])},"
-        # 写入数据库
-        if warning_result:
-            MongoCBDPestWarning.objects.create(
-                device_id = device_id,
-                warning_content = f"{warning_result}请注意防范",
-                warning_types = "2",
-                upltime = now_stamp
-            )        
-
-    # 害虫种类
-    pestCategory = conf.get("pestCategory")
-    if pestCategory == "on":
-        pestCategoryNum = conf.get("pestCategoryNum") 
-        pest_cg_count = len(indentify_result.keys())
-        if pest_cg_count > int(pestCategoryNum):
+        # 定义预警变量
+        warning_result = ""
+        # 指定害虫数量预警
+        appointPest = conf.get("appointPest")
+        if appointPest == "on":
+            appointPestName = conf.get("appointPestName")
+            appointPestNum = conf.get("appointPestNum")
+            pest_cg = appointPestName.split("#")
+            pest_nu = appointPestNum.split("#")
+            for i in pest_cg:
+                if i in indentify_result.keys():
+                    if indentify_result[i] > int(pest_nu[pest_cg.index(i)]):
+                        zh = insect_dict.get(i, "未知")
+                        warning_result += f"害虫{zh}数量{str(indentify_result[i])},"
             # 写入数据库
-            MongoCBDPestWarning.objects.create(
-                device_id = device_id,
-                warning_content = f"害虫种类{pest_cg_count},请注意防范",
-                warning_types = "1",
-                upltime = now_stamp
-            )  
+            if warning_result:
+                alarm_obj = MongoCBDPestWarning.objects.create(
+                    device_id = device_id,
+                    warning_content = f"{warning_result}请注意防范",
+                    warning_types = "2",
+                    upltime = now_stamp
+                ) 
+                logger.warning(f"指定害虫数量预警: {alarm_obj.id}")      
+
+        # 害虫种类
+        pestCategory = conf.get("pestCategory")
+        if pestCategory == "on":
+            pestCategoryNum = conf.get("pestCategoryNum") 
+            pest_cg_count = len(indentify_result.keys())
+            if pest_cg_count > int(pestCategoryNum):
+                # 写入数据库
+                alarm_obj = MongoCBDPestWarning.objects.create(
+                    device_id = device_id,
+                    warning_content = f"害虫种类{pest_cg_count},请注意防范",
+                    warning_types = "1",
+                    upltime = now_stamp
+                )  
+                logger.warning(f"害虫种类: {alarm_obj.id}")   
 
-    # 害虫总数
-    pestTotal = conf.get("pestTotal")
-    if pestTotal == "on":
-        pestTotalNum = conf.get("pestTotalNum")
-        ct = 0
-        for m, n in indentify_result.items():
-            ct += int(n)
-        if ct > int(pestTotalNum):
+        # 害虫总数
+        pestTotal = conf.get("pestTotal")
+        if pestTotal == "on":
+            pestTotalNum = conf.get("pestTotalNum")
+            ct = 0
+            for m, n in indentify_result.items():
+                ct += int(n)
+            if ct > int(pestTotalNum):
+                # 写入数据库
+                alarm_obj = MongoCBDPestWarning.objects.create(
+                    device_id = device_id,
+                    warning_content = f"害虫总数{str(ct)},请注意防范",
+                    warning_types = "3",
+                    upltime = now_stamp
+                ) 
+                logger.warning(f"害虫总数: {alarm_obj.id}")   
+ 
+
+        # 综合预警
+        total_warning = ""
+        pestWarn = conf.get("pestWarn")
+        if pestWarn == "on":
+            for m, n in indentify_result.items():
+                total_warning += f"害虫{insect_dict.get(m)},数量{str(n)};" 
             # 写入数据库
-            MongoCBDPestWarning.objects.create(
+            alarm_obj = MongoCBDPestWarning.objects.create(
                 device_id = device_id,
-                warning_content = f"害虫总数{str(ct)},请注意防范",
-                warning_types = "3",
+                warning_content = f"{total_warning}请注意防范!",
+                warning_types = "4",
                 upltime = now_stamp
             )  
+            logger.warning(f"综合预警: {alarm_obj.id}")  
+
+# 每天的8点执行任务
+schedule.every().day.at("08:00").do(product_cbd_alarm)
 
-    # 综合预警
-    total_warning = ""
-    pestWarn = conf.get("pestWarn")
-    if pestWarn == "on":
-        for m, n in indentify_result.items():
-            total_warning += f"害虫{insect_dict.get(m)},数量{str(n)};" 
-        # 写入数据库
-        MongoCBDPestWarning.objects.create(
-            device_id = device_id,
-            warning_content = f"{total_warning}请注意防范!",
-            warning_types = "4",
-            upltime = now_stamp
-        )  
+while True:
+    schedule.run_pending()
+    time.sleep(1)