Bladeren bron

更新数据

yf_yzl 2 jaren geleden
bovenliggende
commit
d5a22e9b15
3 gewijzigde bestanden met toevoegingen van 93 en 182 verwijderingen
  1. 0 181
      scripts/cbd_device.py
  2. 91 0
      scripts/cbd_msg.py
  3. 2 1
      smartfarming/api/views/camera/cameraserializers.py

+ 0 - 181
scripts/cbd_device.py

@@ -1,181 +0,0 @@
-# coding:utf-8
-import os
-import sys
-import time
-local_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
-if local_path not in sys.path:
-    sys.path.append(local_path)
-os.environ.setdefault("DJANGO_SETTINGS_MODULE", "kedong.settings")
-from django.conf import settings
-from kedong.tools import RedisPool
-from scripts.tools.utils import dashuju_pub_mqtt
-
-
-cbd_redis_pool = RedisPool().get_redis_pool(settings.redis_db["cbd"])
-
-
-def re_cbd_publish(payload):
-    if settings.DEBUG:
-        return None
-
-    imei_id = payload['imei_id']
-    at, ah = payload['at'], payload['ah']
-    try:
-        at = str(round(float(at)))
-    except ValueError as e:
-        at = "25"
-    try:
-        ah = str(round(float(ah)))
-    except ValueError as e:
-        print('at_error', e, payload)
-        ah = "30"
-
-    publics = "/yfkj/cbd/sub/#"
-
-    TASK_TOPIC = publics.replace("#", imei_id)
-    payload_1 = {"cmd": "sensor", "ext": {"new_hum": ah, "new_tem": at}}
-    dashuju_pub_mqtt(TASK_TOPIC, payload_1)
-
-
-def re_pub_cbd_publish(data):
-    if settings.DEBUG:
-        return None
-
-    imei_id = data['imei_id']
-    payload = data['payload']
-    TASK_TOPIC = ""
-    if TASK_TOPIC:
-        dashuju_pub_mqtt(TASK_TOPIC, payload)
-
-
-class CbdDeviceController(DeviceController):
-
-    def cbd_device(self, data):
-        table_name = "sa_device_cbd_data"
-        DEVICE_NAME = "测报灯"
-        DTYPE = 3
-        serverconf = ''
-        payload = data['payload']
-        imei_id = data['imei_id']
-
-        re_cbd_publish(data)
-        re_pub_cbd_publish(data)
-
-        ext = payload["ext"]
-        dver_num = ext.get("dver", "")
-        # 0-手动,1-GPS,2-基站
-        gps = ext["gps"]  
-        lng, lat = data['lng'], data['lat']
-
-        device_code = 0
-        try:
-            device_code = int(ext.get("vtype", 0))
-        except Exception as e:
-            pass
-
-        now_time = int(time.time())
-        device_config = {
-            "cmd": "paramconf",
-            "ext": {
-                "hst": ext.get("hst", "0"),
-                "collt": ext.get("collt", ""),
-                "et": ext.get("et", ""),
-                "datt": ext.get("dat_f", 30),
-                "shake_sec": ext.get("shake_sec", 1),
-                "tpl": ext.get("tpl", 5),
-                "shake": ext.get("shake", 0),
-                "tph": ext.get("tph", 0),
-                "ts": ext.get("ts", 0),
-                "st": ext.get("st", 0),
-                "htim": ext.get("htim", 0),
-                "tt": ext.get("tt", 0),
-                "ds": ext.get("ds", 0),
-                "ws": ext.get("ws", 0),
-            }
-        }
-
-        temp_dict = {
-            'device_id': imei_id, 
-            'device_type_id': DTYPE, 
-            'dver_num': dver_num,
-            'addtime': now_time, 
-            'uptime': now_time, 
-            'device_name': DEVICE_NAME,
-            'lng': lng, 
-            'lat': lat, 
-            'gps': gps, 
-            'serverconf': serverconf, 
-            'device_status': 1,
-            'device_code': device_code
-        }
-        return temp_dict, device_config, table_name
-
-    def xct_device(self, data):
-        """吸虫塔设备"""
-        table_name = "sa_device_xct_data"
-        DEVICE_NAME = "吸虫塔"
-        # 设备类型id
-        DTYPE = 12
-
-        serverconf = ''
-        payload = data['payload']
-        imei_id = data['imei_id']
-
-        re_cbd_publish(data)
-
-        ext = payload["ext"]
-        dver_num = ext["dver"]
-         # 0-手动,1-GPS,2-基站
-        gps = ext["gps"] 
-        lng, lat = data["lng"], data["lat"]
-        now_time = int(time.time())
-        device_config = {
-            "cmd": "paramconf",
-            "ext": {
-                "dat_f": ext.get("dat_f", 30),  # 数据上传时间
-                "shake_sec": ext["shake_sec"],  # 震动时间
-                "shake": ext["shake"],  # 震动开关, 1开启 0关闭
-                "ds": ext["ds"],  # 设备开关机,1开机,0关机
-                "dver": ext["dver"],  # 版本号
-                "st": ext["st"],
-                "et": ext["et"],
-            }
-        }
-        temp_dict = {
-            'device_id': imei_id, 'device_type_id': DTYPE, 'dver_num': dver_num,
-            'addtime': now_time, 'uptime': now_time, 'device_name': DEVICE_NAME,
-            'lng': lng, 'lat': lat, 'gps': gps, 'serverconf': serverconf, 'device_status': 1,
-            'device_code': DTYPE
-        }
-
-        return temp_dict, device_config, table_name
-
-    def make_device_config(self, data):
-        payload = data['payload']
-        ext = payload["ext"]
-        try:
-            vtype = int(ext["vtype"])
-            if vtype == 6:
-                return self.xct_device(data)
-        except Exception as e:
-            pass
-        return self.cbd_device(data)
-
-
-if __name__ == "__main__":
-    # 正常消息订阅
-    PUBLICS = "/yfkj/cbd/pub/#"
-    # 离线消息订阅
-    OFFLINE = "/yfkj/cbd/offline/#"
-    cbd = CbdDeviceController()
-    key = "/yfkj/cbd"
-    while True:
-        try:
-            data = cbd_redis_pool.bpop(key)
-            now_time = int(time.time())
-            create_time = data['create_time']
-            if now_time - create_time > 3600:
-                continue
-            cbd.device_controller(data)
-        except Exception as e:
-            print(e)

+ 91 - 0
scripts/cbd_msg.py

@@ -0,0 +1,91 @@
+import os
+import sys
+import time
+import django
+import json
+from datetime import datetime, timedelta
+local_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+print(local_path)
+if local_path not in sys.path:
+    sys.path.append(local_path)
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "kedong.settings")
+django.setup()
+from django.conf import settings
+from smartfarming.models.sim_card import MongoMsg_Conf
+from smartfarming.models.worm_forecast import MongoCBDphoto
+from smartfarming.models.pest_count import MongoCBDPestWarning
+from smartfarming.api.views.forecast.all_dict import insect_dict
+
+
+
+# 获取所有的预警配置
+msg_conf = MongoMsg_Conf.objects.all()
+for msg in msg_conf:
+    # 获取device_id  conf
+    device_id = msg_conf.device_id
+    conf = json.load(msg_conf.conf) 
+    # 获取该device_id 下前一天的害虫情况
+    now = datetime.now()
+    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("#")
+        if tmp[0] in indentify_result.keys():
+            indentify_result[tmp[0]] += int(tmp[1])
+        else:
+            indentify_result[tmp[0]] = int(tmp[1])
+
+    # 定义预警变量
+    warning_result = ""
+    # 指定害虫数量预警
+    appointPest = conf.get("appointPest")
+    if appointPest == "on":
+        appointPestName = conf.get("appointPestName")
+        appointPestNum = conf.get("appointPestNum")
+        pest_cg = appointPestName.split("#")
+        pest_nu = appointPestName.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])},"
+
+    # 害虫种类
+    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 += f"害虫种类{pest_cg_count},"
+
+    # 害虫总数
+    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):
+            warning_result += f"害虫总数{str(ct)},"
+
+    # 综合预警
+    pestWarn = conf.get("pestWarn")
+    if pestWarn == "on":
+        for m, n in indentify_result.items():
+            warning_result += f"{insect_dict.get(m)},数量{str(n)}," 
+    if warning_result:
+        warning_result += "请注意防范"
+    # 写入数据库
+    MongoCBDPestWarning.objects.create(
+        
+    )
+
+
+
+

+ 2 - 1
smartfarming/api/views/camera/cameraserializers.py

@@ -50,5 +50,6 @@ class MongoDeviceCameraSerializers(serializers.ModelSerializer):
             "camera_playback",
             "sim",
             "photo_num",
-            "d_id"
+            "d_id",
+            "jk_live_img"
         ]