cbd_msg.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. import os
  2. import sys
  3. import time
  4. import logging
  5. import django
  6. import schedule
  7. from datetime import datetime, timedelta
  8. local_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  9. print(local_path)
  10. if local_path not in sys.path:
  11. sys.path.append(local_path)
  12. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "kedong.settings")
  13. django.setup()
  14. from django.conf import settings
  15. from smartfarming.models.sim_card import MongoMsg_Conf
  16. from smartfarming.models.worm_forecast import MongoCBDphoto
  17. from smartfarming.models.pest_count import MongoCBDPestWarning
  18. from smartfarming.api.views.forecast.all_dict import insect_dict
  19. base_path = settings.BASE_DIR
  20. logger = logging.getLogger('test')
  21. logger.setLevel(level=logging.DEBUG)
  22. formatter = logging.Formatter('%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
  23. file_handler = logging.FileHandler(os.path.join(base_path, "logs/cbd_msg.log"))
  24. file_handler.setLevel(level=logging.INFO)
  25. file_handler.setFormatter(formatter)
  26. stream_handler = logging.StreamHandler()
  27. stream_handler.setLevel(logging.DEBUG)
  28. stream_handler.setFormatter(formatter)
  29. logger.addHandler(file_handler)
  30. logger.addHandler(stream_handler)
  31. def product_cbd_alarm():
  32. # 获取所有的预警配置
  33. msg_conf = MongoMsg_Conf.objects.all()
  34. for msg in msg_conf:
  35. # 获取device_id conf
  36. device_id = msg.device_id
  37. conf = eval(msg.conf)
  38. # 获取该device_id 下前一天的害虫情况
  39. now = datetime.now()
  40. now_stamp = int(time.time())
  41. previous_day = now - timedelta(days=1)
  42. start_time = datetime(previous_day.year, previous_day.month, previous_day.day, 0, 0, 0).timestamp()
  43. end_time = datetime(now.year, now.month, now.day, 23, 59, 59).timestamp()
  44. photo_data = MongoCBDphoto.objects.filter(addtime__range = [start_time, end_time]).values_list("indentify_result", flat=True)
  45. # 把当天的害虫统计出来
  46. indentify_result = {}
  47. for p in photo_data:
  48. tmp = p.split("#")
  49. for tp in tmp:
  50. k = tp.split(",")
  51. if k[0] in indentify_result.keys():
  52. indentify_result[k[0]] += int(k[1])
  53. else:
  54. indentify_result[k[0]] = int(k[1])
  55. # 定义预警变量
  56. warning_result = ""
  57. # 指定害虫数量预警
  58. appointPest = conf.get("appointPest")
  59. if appointPest == "on":
  60. appointPestName = conf.get("appointPestName")
  61. appointPestNum = conf.get("appointPestNum")
  62. pest_cg = appointPestName.split("#")
  63. pest_nu = appointPestNum.split("#")
  64. for i in pest_cg:
  65. if i in indentify_result.keys():
  66. if indentify_result[i] > int(pest_nu[pest_cg.index(i)]):
  67. zh = insect_dict.get(i, "未知")
  68. warning_result += f"害虫{zh}数量{str(indentify_result[i])},"
  69. # 写入数据库
  70. if warning_result:
  71. alarm_obj = MongoCBDPestWarning.objects.create(
  72. device_id = device_id,
  73. warning_content = f"{warning_result}请注意防范",
  74. warning_types = "2",
  75. upltime = now_stamp
  76. )
  77. logger.warning(f"指定害虫数量预警: {alarm_obj.id}")
  78. # 害虫种类
  79. pestCategory = conf.get("pestCategory")
  80. if pestCategory == "on":
  81. pestCategoryNum = conf.get("pestCategoryNum")
  82. pest_cg_count = len(indentify_result.keys())
  83. if pest_cg_count > int(pestCategoryNum):
  84. # 写入数据库
  85. alarm_obj = MongoCBDPestWarning.objects.create(
  86. device_id = device_id,
  87. warning_content = f"害虫种类{pest_cg_count},请注意防范",
  88. warning_types = "1",
  89. upltime = now_stamp
  90. )
  91. logger.warning(f"害虫种类: {alarm_obj.id}")
  92. # 害虫总数
  93. pestTotal = conf.get("pestTotal")
  94. if pestTotal == "on":
  95. pestTotalNum = conf.get("pestTotalNum")
  96. ct = 0
  97. for m, n in indentify_result.items():
  98. ct += int(n)
  99. if ct > int(pestTotalNum):
  100. # 写入数据库
  101. alarm_obj = MongoCBDPestWarning.objects.create(
  102. device_id = device_id,
  103. warning_content = f"害虫总数{str(ct)},请注意防范",
  104. warning_types = "3",
  105. upltime = now_stamp
  106. )
  107. logger.warning(f"害虫总数: {alarm_obj.id}")
  108. # 综合预警
  109. total_warning = ""
  110. pestWarn = conf.get("pestWarn")
  111. if pestWarn == "on":
  112. for m, n in indentify_result.items():
  113. total_warning += f"害虫{insect_dict.get(m)},数量{str(n)};"
  114. # 写入数据库
  115. alarm_obj = MongoCBDPestWarning.objects.create(
  116. device_id = device_id,
  117. warning_content = f"{total_warning}请注意防范!",
  118. warning_types = "4",
  119. upltime = now_stamp
  120. )
  121. logger.warning(f"综合预警: {alarm_obj.id}")
  122. # 每天的8点执行任务
  123. schedule.every().day.at("08:00").do(product_cbd_alarm)
  124. while True:
  125. schedule.run_pending()
  126. time.sleep(1)