Kaynağa Gözat

设备控制更新

yf_yzl 2 yıl önce
ebeveyn
işleme
4fc893f052

+ 13 - 0
kedong/settings.py

@@ -206,6 +206,14 @@ LOGGING = {
             'encoding': 'utf-8',
             'formatter': 'verbose'
         },
+        'control':{  # 记录 控制设备的 日志
+            'class': 'logging.handlers.TimedRotatingFileHandler',
+            'filename': 'logs/control.log',
+            'when': 'midnight',
+            'backupCount': 30,
+            'encoding': 'utf-8',
+            'formatter': 'verbose'
+        }
     },
     'loggers': {
         'django': {  # 默认的日志器
@@ -228,6 +236,11 @@ LOGGING = {
             'level': 'WARNING',
             'propagate': True,
         },
+        'control': {  # 自定义的日志器
+            'handlers': ['control'],
+            'level': 'WARNING',
+            'propagate': True,
+        },
     },
     'formatters': {
         'simple': {

+ 1 - 1
scripts/test/cbd_photo.py

@@ -44,7 +44,7 @@ def dsj_qxz_conf_info():
     for i in scd_device:
         device_info = collection.find_one({'device_id':i})
         device_id = device_info['id']
-        data = {'device_id': str(device_id),'uptime':{'$gte':1689006195}}
+        data = {'device_id': str(device_id),'uptime':{'$gte':1690166400}}
         cursor = collection1.find(data,{'_id':0,'id':0})
         device_id = MongoDevice.objects.get(device_id=i).id 
         for i in cursor:

+ 65 - 0
scripts/test/qx_ctrl_config.py

@@ -0,0 +1,65 @@
+import os
+import sys
+import time
+import django
+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.device import MongoDevice, MongoDeviceConfig
+import json
+import requests
+import pymongo
+from urllib import parse
+
+
+my_client = pymongo.MongoClient(host="8.136.98.49", port=27017, username="root", password="yfkj@6020")
+my_col = my_client['smartfarming']['sa_device']
+
+qx_device = {
+"861551055315402",
+"861551056086671",
+"861551056088693",
+"861551056088479",
+"861551056088719",
+"861551055313365",
+"861551056086614",
+"861551056093800",
+"861551056095367",
+"861551056102502",
+"861551056096621",
+"861551056101785",
+"861551056086549",
+"861551055354120",
+"861551055353536",
+"861551056092018",
+"861551055319586",
+"861551056088875",
+"861551055324651",
+"861551055313423"
+}
+
+
+def dsj_qxz_conf_info():
+    # 初始化气象站与墒情站时间间隔配置
+    cmd = '{"cmd": "config", "ext": {"interval": 1}}'
+    for k in qx_device:
+        in_d_id = MongoDevice.objects.get(device_id=k).id
+        config, is_created = MongoDeviceConfig.objects.get_or_create(
+                d_id=in_d_id,
+                defaults={
+                    "device_config": cmd,
+                    "cmd": "config",
+                    "addtime": int(time.time()),
+                    "uptime": int(time.time())
+                }
+            )
+        print(f"设备: {k} 是否新建  {is_created} ")
+    return True
+
+
+if __name__ == "__main__":
+    dsj_qxz_conf_info()

+ 4 - 2
smartfarming/api/views/camera/camera_manage.py

@@ -450,7 +450,9 @@ def camera_takephoto(request):
     appSecret = camera_query.app_secret
     snap_url = setDeviceSnap(appId, appSecret, device_id, channelNo)
     print(snap_url)
-    time.sleep(1)
+    # snap_url = "https://lechangecloud.oss-cn-hangzhou.aliyuncs.com/lechange/snappic/8H09715PHA657EC_img/Alarm/0/9d9913c5112c4587a391b6c454110c5a.jpg?Expires=1690882790&OSSAccessKeyId=LTAIP4igXeEjYBoG&Signature=RK97RSfcLjyA84Fv8aFOtA%2BvGao%3D"
+    # snap_url = "https://lechangecloud.oss-cn-hangzhou.aliyuncs.com/lechange/snappic/8H09715PHA24E37_img/Alarm/0/ab85f10f33a34f068dc55a4a64e51584.jpg?Expires=1690883565&OSSAccessKeyId=LTAIP4igXeEjYBoG&Signature=%2FP1Bxksx0lagn24gkwaXWcS9Dno%3D"
+    time.sleep(5)
     if snap_url:
         # 图片保存位置 
         config = settings.CONFIG
@@ -463,7 +465,7 @@ def camera_takephoto(request):
         camera_photos = combined_id + ".jpg"
         img_path = os.path.join(camera_path, camera_photos)
         # 下载图片
-        img_query = requests.get(snap_url)
+        img_query = requests.get(snap_url, timeout=5)
         if img_query.status_code == 200:
             img = Image.open(BytesIO(img_query.content))
             img.save(img_path)

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

@@ -17,6 +17,7 @@ class MongoCameraPhotoSerializers(serializers.ModelSerializer):
 class MongoDeviceCameraSerializers(serializers.ModelSerializer):
     status = serializers.SerializerMethodField()
     sim = serializers.SerializerMethodField()
+    d_id = serializers.SerializerMethodField()
     photo_num = serializers.SerializerMethodField()
     camera_playback = serializers.SerializerMethodField()
 
@@ -36,6 +37,9 @@ class MongoDeviceCameraSerializers(serializers.ModelSerializer):
 
     def get_sim(self, obj):
         return obj.simid
+    
+    def get_d_id(self, obj):
+        return obj.id
 
     class Meta:
         model = MongoDevice
@@ -45,5 +49,6 @@ class MongoDeviceCameraSerializers(serializers.ModelSerializer):
             "status",
             "camera_playback",
             "sim",
-            "photo_num"
+            "photo_num",
+            "d_id"
         ]

+ 106 - 342
smartfarming/api/views/forecast/forecast_system.py

@@ -6,7 +6,8 @@ import json
 import time
 import os
 import requests
-import random
+import datetime
+import uuid 
 import ast
 from django.conf import settings
 
@@ -15,6 +16,8 @@ from smartfarming.models.sim_card import MongoMsg_Conf
 from smartfarming.models.device import MongoDevice
 from smartfarming.models.worm_forecast import MongoCBDphoto, MongoCBDphoto_B, MongoCBDphoto_C
 from kedong.decoration import kedong_deco, PortError
+from .common import *
+from django.db.models import Q
 config_dict = settings.CONFIG
 
 
@@ -240,12 +243,6 @@ def device_photo_list(request):
     return {"disable":device.disable,"data":data,"num":num}
 
 
-
-
-from .common import *
-from django.db.models import Q
-
-
 @kedong_deco(login_required=True)
 def equip_photo_del(request):
     """
@@ -322,343 +319,110 @@ def cbd_msg_conf(request):
 
 
 
-def disable_cbd_discern(request):
-    """
-    禁用测报灯害虫识别功能
-
-    device_id            必传(str)                    设备号
-    ret                  必传(str)                    ret=disable时禁用识别功能, ret=enable,时启用识别统计功能, ret =count 计数功能
-
-    """
-    device_id = request.POST.get("device_id")
-    ret = request.POST.get("ret")
-
-    try:
-        device_list = Device.objects.get(device_id=device_id)
-    except:
-        raise PortError("device_id", "找不到该设备")
-    if ret == "disable":
-        device_list.disable = 0
-        device_list.save()
-    elif ret == "enable":
-        device_list.disable = 1
-        device_list.save()
-    elif ret == "count":
-        device_list.disable = 2
-        device_list.save()
-    else:
-        raise PortError("device_id", "参数超出范围")
-    return True
-
-
-
-def cbd_pest_type_ranking(request):
-    """
-    筛选最近识别害虫列表接口
-    参数:
-    start_time      非必传          开始时间 时间戳
-    end_time        非必传          结束时间 时间戳、
-    page            非必传          页数
-    page_size       非必传          一页默认10条数据
-    ret             必传            为num害虫排名,  为type列表详情数据, 
-    identify_model  必传            识别模型A,识别模型B
-
-    type时返回值:
-     "data": {
-        "num": 2,                                       条数
-        "cbd_photo_data": [
-            {
-                "device_id": "867814040006799",         设备号
-                "pest_num": 18,                         害虫种类数据
-                "pest_name": [
-                    {
-                        "pest_name": "水龟虫",          害虫种类
-                        "num": 518                      害虫总数
-                    },
-                    {
-                        "pest_name": "蝼蛄",
-                        "num": 128
-                    },
-        num 时返回值:
-        "data": [
-            {
-                "水龟虫": 539      害虫名称    害虫数量
-            },
-            {
-                "蝼蛄": 153
-            },
-            {
-                "铜绿丽金龟": 62
-            },
-            {
-                "负子蝽": 42
-            },
-            {
-                "暗黑鳃金龟": 21
-            },
-            {
-                "夜蛾": 15
-            }
-        ],
-    """
-    page = int(request.POST.get("page",1))
-    page_size = int(request.POST.get("page_size",10))
-    start_time = request.POST.get("start_time")
-    end_time = request.POST.get("end_time")
+@kedong_deco(login_required=True)
+def equip_photo_discern(request):
+    # 测报灯、吸虫塔、色诱测报害虫重新图片识别\详情\手动标注接口
+    img_id = request.POST.get("img_id")
     ret = request.POST.get("ret")
-    recive_pest_name = request.POST.get("pest_name")
-    identify_model = request.POST.get("identify_model","A")
-    if identify_model=="A":
-        models = CBDphoto
-    elif identify_model=="B":
-        models = CBDphoto_B
-    myuser = request.myuser
-    pest_num_data = []
-    date = []
-    devices = Device.devices(uid=myuser.uid, myuser=myuser)
-    print("user_type",myuser.user_type)
-    if myuser.user_type != 4 or myuser.user_type != 1:
-        devices = devices.filter(disable=1)
-    for i in devices:
-        if not myuser.user_type == 1 and i.device_expire == "1":
-            cbd_data = models.objects.filter(~Q(indentify_photo=None),device_id=i.id,photo_status=1,addtime__lte=int(i.device_expire_time)).values()
-            if end_time and int(end_time) > int(i.device_expire_time):
-                end_time = i.device_expire_time
-                cbd_data = cbd_data.filter(addtime__range=(int(start_time),int(end_time)))
-        else:
-            cbd_data = models.objects.filter(~Q(indentify_photo=None),device_id=i.id,photo_status=1).values()
-            if start_time:
-                cbd_data = cbd_data.filter(addtime__range=(int(start_time),int(end_time)))
-        for x in cbd_data:
-            if x["indentify_result"]:
-                xx_result =  x["indentify_result"].split("#")
-                print(xx_result)
-                for yy in xx_result:
-                    yy_result = yy.split(",")
+    if ret == "again":
+        # 手动标注
+        # 获取该图片对象
+        photo_obj = MongoCBDphoto.objects.filter(id=img_id)
+        photo_obj = photo_obj.first() if photo_obj else None 
+        date = []
+        if photo_obj:
+            # 当图片对象存在
+            addr = photo_obj.addr
+            if addr:
+                # 该图片对应设备的信息
+                device = MongoDevice.objects.filter(id=img_id)
+                device = device.first() if device else None 
+                # 获取图片本地路径
+                img_content_url = f'{config_dict.get("image_url").get("image")}/media'
+                media = f'{config_dict.get("media")}'
+                if addr.startswith("http"):
+                    addr = addr.replace(img_content_url,media)
+                else:
+                    addr = addr.replace("/media",media)
+                print(addr, "--------")
+                pass 
+                # 重新调用识别接口
+                identify_url = config_dict.get("image_url").get("identify_url")
+                if device.lng and device.lat:
+                    request_data = {
+                        "longitude": device.lng,
+                        "latitude": device.lat
+                    }
+                else:
+                    request_data = {
+                        "longitude": "126.40548",
+                        "latitude": "47.82857"
+                    }
+                if os.path.exists(addr):
+                    imageFile = {
+                        "imageFile": ('pic.jpg', open(addr, "rb"), 'image/jpeg')
+                    }
+                    res = requests.post(url=identify_url, data=request_data, files=imageFile, timeout=(10, 20))
+                    image_result = json.loads(res.text)
                     try:
-                        date.append({
-                                "device_id": i.device_id,
-                                "device_name": i.device_name,
-                                "device_add": i.province+i.city+i.district,
-                                "pest_num" : int(yy_result[1]),
-                                "pest_name" : insect_dict[yy_result[0]]})
-                    except:
-                        continue
-    data = {}
-    pest = {}
-    if ret == "type":
-        for item in date:
-            device_id, pest_name,pest_num,device_name,device_add= item['device_id'], item['pest_name'],item['pest_num'],item['device_name'],item['device_add']
-            key = '{},{},{}'.format(device_id,device_name,device_add)
-            if key in data:
-                data[key] += [pest_name]
-            else:
-                data[key] = [pest_name]
-            keys = '{},{}'.format(device_id,pest_name)
-            if keys in pest:
-                pest[keys] += pest_num
-
-            else:
-                pest[keys] = pest_num
-        sort_data = sorted(data.items(), key=lambda d:len(d[1]), reverse = True )
-        for y in sort_data:
-            device_id,device_name, device_addr = y[0].split(',')
-            pest_data = []
-            for x in y[1]:
-                x = {"pest_name":x,"num":pest[device_id +","+x]}
-                if x not in pest_data:
-                    pest_data.append(x)
-            sorted_x = sorted(pest_data, key=operator.itemgetter('num'),reverse = True)
-            if recive_pest_name:
-                for pt_name in sorted_x:
-                    if recive_pest_name in pt_name["pest_name"]:
-                        pest_num_data.append({
-                            "device_id" : device_id,
-                            "pest_num": len(pest_data),
-                            "pest_name": sorted_x,
-                            "device_name" : device_name,
-                            "device_addr": device_addr
-                        })
-                    else:
-                        pass
-            else:
-                pest_num_data.append({
-                    "device_id" : device_id,
-                    "pest_num": len(pest_data),
-                    "pest_name": sorted_x,
-                    "device_name" : device_name,
-                    "device_addr": device_addr
-                })
-        num = len(pest_num_data)
-        cbd_photo_data = pest_num_data[(page_size*(page-1)):(page*page_size)]
-        cbd_pset = {"num":num,"cbd_photo_data":cbd_photo_data}
-        return cbd_pset
-    elif ret == "num":
-        for item in date:
-            pest_num,pest_name = item['pest_num'],item["pest_name"]
-            key = '{}'.format(pest_name)
-            if key in data:
-                data[key] += pest_num
-            else:
-                data[key] = pest_num
-        sort_data = sorted(data.items(), key=lambda d:d[1], reverse = True )[:6]
-        for y in sort_data:
-            pest_num_data.append({
-                y[0] : y[1]
-            })
-        return pest_num_data
+                        if image_result.get("returnResult").get("returnStatus") != "0":
+                            returnString = image_result["returnResult"]["returnString"]
+                            returnImageUrl = image_result["returnResult"]["returnImageUrl"]
+                            returnCode = image_result["returnResult"].get("returnCode","")
+                            remote_content = requests.get(returnImageUrl).content
+                            indentify_photo = photo_obj.indentify_photo
+                            # 如果第一次识别图片存在
+                            if photo_obj:
+                                if indentify_photo.startswith("http"):
+                                    indentify_photo = indentify_photo.replace(img_content_url,media)
+                                else:
+                                    indentify_photo = indentify_photo.replace("/media",media)
+                            else:
+                                # 如果第一次识别图片不存在
+                                inden_path = os.path.join(media, f"result/cbd/{device.device_id}")
+                                os.makedirs(inden_path) if not os.path.exists(inden_path) else None 
+                                stamp = int(datetime.now().timestamp())
+                                unique_id = uuid.uuid4()
+                                combined_id = str(stamp) + "-" + str(unique_id)
+                                indentify_photo = os.path.join(inden_path, f"{combined_id}.jpg")
+                            # 把原本地图片覆盖
+                            with open(indentify_photo, "wb") as f:
+                                f.write(remote_content)
+                            # 更新结果
+                            cbd_img = indentify_photo.replace(media, img_content_url)
+                            photo_obj.indentify_photo = cbd_img
+                            photo_obj.indentify_result = returnString
+                            photo_obj.label = returnCode
+                            photo_obj.save()
+                            pest_list = returnString.split("#")
+                            for i in pest_list:
+                                if i:
+                                    res = i.split(",")
+                                    nums = res[1] #数量
+                                    number = res[0] #编号
+                                    try:
+                                        result_list = insect_dict[number]
+                                    except:
+                                        result_list = attract_discern[number]
+                                    date.append({"nums":nums,"result_list":result_list,"number":number})
+                            dat = {"image":cbd_img,"result":date, "label": returnCode}
+                            print(dat)
+                            return dat
+                        else:
+                            return {"code": 2, "msg": "无识别结果"}
+                    except Exception as e:
+                        return {"code": 2, "msg": "无识别结果"}
     else:
-        raise PortError("ret", "参数超出范围")
-        
-
-
-
-
-
-def cbd_pest_line_chart(request):
-    """
-    筛选总设备害虫折线图
-    参数:
-    start_time              非必传(string 时间戳)           开始时间    (用于时间搜索)
-    end_time                非必传(string 时间戳)           结束时间    (用于时间搜索)
-    pest_name               非必传(str)                     害虫名称
-    ret                     必传                            等于day_month 24小时数据、近一个月数据, 等于:half_year 半年、一年数据
-    identify_model          必传                            识别模型A,识别模型B
-    
-    等于day_month返回值:
-     "data": [
-        {
-            "addtime": "2021-03-09 11:28:08",                   时间
-            "pest_name": "夜蛾",                                害虫名
-            "pest_num": 5                                       数量
-        },
-        {
-            "addtime": "2021-03-09 18:51:07",
-            "pest_name": "夜蛾",
-            "pest_num": 4
-        },
-    等于half_year返回值:
-     "data": [
-        {
-            "addtime": "2021-03",                           月份
-            "pest_name": "夜蛾",                            害虫名
-            "pest_num": 54                                  数量
-        },
-        {
-            "addtime": "2021-04",
-            "pest_name": "夜蛾",
-            "pest_num": 44
-        }
-    ],
-    "pest_name":{
-        "水龟虫":20
-    }
-    """
-
-    start_time = request.POST.get("start_time")
-    end_time = request.POST.get("end_time")
-    ret = request.POST.get("ret")
-    pest_name = request.POST.get("pest_name")
-    identify_model = request.POST.get("identify_model","A")
-    if identify_model=="A":
-        models = CBDphoto
-    elif identify_model=="B":
-        models = CBDphoto_B
-    myuser = request.myuser
-    print(myuser.uid)
-    date = [] 
-    devices = Device.devices(uid=myuser.uid, myuser=myuser)
-    if myuser.user_type != 4 or myuser.user_type != 1:
-        devices = devices.filter(disable=1)
-    for i in devices:
-        if not myuser.user_type == 1 and i.device_expire == "1":
-            cbd_data = models.objects.filter(~Q(indentify_photo=None),device_id=i.id,photo_status=1).filter(addtime__lte=int(i.device_expire_time))
-            if end_time:
-                if int(end_time) > int(i.device_expire_time):
-                    end_time = i.device_expire_time
-                cbd_data = cbd_data.filter(addtime__range=(int(start_time),int(end_time)))
-        else:
-            cbd_data = models.objects.filter(~Q(indentify_photo=None),device_id=i.id,photo_status=1)
-            if start_time:
-                cbd_data = cbd_data.filter(addtime__range=(int(start_time),int(end_time)))
-        for x in cbd_data:
-            photo_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(x.addtime))
-            if x.indentify_result:
-                xx_result =  x.indentify_result.split("#")
-                for yy in xx_result:
-                    yy_result = yy.split(",")
-                    try:
-                        if pest_name == insect_dict[yy_result[0]]:
-                            date.append({
-                                    "photo_time" : photo_time,
-                                    "pest_num" : int(yy_result[1]),
-                                    "pest_name" : insect_dict[yy_result[0]]})
-                        if not pest_name:
-                            date.append({
-                                    "photo_time" : photo_time,
-                                    "pest_num" : int(yy_result[1]),
-                                    "pest_name" : insect_dict[yy_result[0]]})
-                    except:
-                        continue
-    data = {}
-    if ret == "day_month":
-        print("24小时数据---近一个月数据")
-        for item in date:
-            photo_time, pest_name, pest_num = item['photo_time'], item['pest_name'], item['pest_num']
-            key = '{},{}'.format(photo_time, pest_name)
-            if key in data:
-                data[key] += pest_num
-            else:
-                data[key] = pest_num
-        result = []
-        for key, value in data.items():
-            photo_time,pest_name = key.split(',')
-            result.append({
-                "addtime" : photo_time,
-                "pest_name" : pest_name,
-                "pest_num" : data[key]
+        return {"code": 2, "msg": "参数范围越界"}
 
-            })
-        list2 = sorted(result, key=operator.itemgetter('addtime'))
-    elif ret == "half_year":
-        print("近半年_近一年")
-        for item in date:
-            photo_time, pest_name, pest_num = item['photo_time'], item['pest_name'], item['pest_num']
-            addtime = photo_time.split("-")[0] + "-" + photo_time.split("-")[1]
-            key = '{},{}'.format(addtime, pest_name)
-            if key in data:
-                data[key] += pest_num
-            else:
-                data[key] = pest_num
-        result = []
-        for key, value in data.items():
-            addtime,pest_name = key.split(',')
-            result.append({
-                "addtime" : addtime,
-                "pest_name" : pest_name,
-                "pest_num" : data[key]
-
-            })
-        list2 = sorted(result, key=operator.itemgetter('addtime'))
-    else:
-        raise PortError("ret", "参数超出范围")
-    datp = {}
-    pest_num_data = []
-    for item in date:
-        pest_num,pest_name = item['pest_num'],item["pest_name"]
-        key = '{}'.format(pest_name)
-        if key in datp:
-            datp[key] += pest_num
-        else:
-            datp[key] = pest_num
-    sort_data = sorted(datp.items(), key=lambda d:d[1], reverse = True )[:6]
-    for y in sort_data:
-        pest_num_data.append({
-            y[0] : y[1]
-        })
-    da = {
-        "data":list2,
-        "pest_name":pest_num_data
-    }
-    return da
 
+@kedong_deco(login_required=True)
+def cbdphoto_receive(request):
+    # 测报灯/色诱/吸虫塔/害虫图片手动添加标注接口:
+    img_id = request.POST.get('img_id')
+    mark = request.POST.get('mark')
+    photo_obj = MongoCBDphoto.objects.get(id=img_id)
+    photo_obj.is_mark = 1
+    photo_obj.mark = mark
+    photo_obj.save()
+    return json.loads(mark)

+ 69 - 192
smartfarming/api/views/forecast/send_control.py

@@ -1,19 +1,20 @@
 import requests
 import json
+import logging
 from requests.auth import HTTPBasicAuth
+from django.conf import settings
 from smartfarming.api.views.forecast.all_dict import insect_dict,get_siminfo,get_simsinfo
 from kedong.decoration import kedong_deco, PortError
 from smartfarming.models.device import MongoDeviceConfig, MongoDevice
+from smartfarming.models.weather import MongoQXZ_Base_Info
+
+logger = logging.getLogger("control")
+config_dict = settings.CONFIG
 
 
 @kedong_deco(login_required=True)
 def device_control_info(request):
-    """
-    设备控制信息/ 设备操作当前状态
-    参数:
-    d_id                   必传                         设备自增id
-    cmd                    必传                         netconf/paramconf/config/。。。用来标记获取什么类型的配置信息
-    """
+    # 设备控制信息/ 设备操作当前状态
     post_info = request.POST
     d_id = post_info.get("d_id", '')
     cmd = post_info.get("cmd", '')
@@ -21,8 +22,9 @@ def device_control_info(request):
         raise PortError('cmd',"参数缺失")
     if not d_id:
         raise PortError('d_id', "参数缺失")
-    if MongoDeviceConfig.objects.filter(d_id=d_id,cmd=cmd).exists():
-        d_config = MongoDeviceConfig.objects.get(d_id=d_id,cmd=cmd)
+    device_config = MongoDeviceConfig.objects.filter(d_id=d_id,cmd=cmd)
+    if device_config.exists():
+        d_config = device_config.first()
         try:
             config = json.loads(d_config.device_config)
         except:
@@ -33,6 +35,9 @@ def device_control_info(request):
             d_config = config
         return d_config
     else:
+        device = MongoDevice.objects.filter(id=d_id, device_type_id__in = [5, 8])
+        if device:
+            device = device.first()
         raise PortError(d_id, "配置未上传")
     
 
@@ -108,7 +113,20 @@ def device_control(request):
             payload["cmd"] = "config"
             payload["ext"] = {"interval":interval}
             cmds = {"topic": topic, "payload": payload, "qos": 1}
-        return True
+            logger.warning(f"设备下发的指令:{cmds}")
+            response = requests.post(
+                "%s" % config_dict['mqtt_config']["http"], 
+                json=cmds,timeout=(3),
+                auth=HTTPBasicAuth(config_dict['mqtt_config']["user"], 
+                config_dict['mqtt_config']["secret_key"])
+            )
+            logger.warning(f"设备的返回值:{response}")
+            # response_code = 200
+            response_code = response.status_code
+            if response_code == 200:
+                return True
+            else:
+                return False
     elif int(device_type_id) == 7:
         topic = "/yfkj/bzy/s2c/%s"%device.device_id
     
@@ -129,11 +147,20 @@ def device_control(request):
     payload = json.dumps(payload)
     cmds = {"topic":topic,"payload":payload,"qos":1}
     content = "设备类型:%s,下发:%s"
-    # TODO 大数据平台转发
-    print(cmds)
-    response_code = 200
+    # mqtt 协议
+    logger.warning(f"设备下发的指令:{cmds}")
+    response = requests.post(
+        "%s" % config_dict['mqtt_config']["http"], 
+        json=cmds,timeout=(3),
+        auth=HTTPBasicAuth(config_dict['mqtt_config']["user"], 
+        config_dict['mqtt_config']["secret_key"])
+    )
+    logger.warning(f"设备的返回值:{response}")
+    response_code = response.status_code
     if response_code == 200:
         return True
+    else:
+        return False
 
 
 @kedong_deco(login_required=True)
@@ -166,11 +193,9 @@ def get_device_config(request):
         raise PortError('d_id', "参数缺失")
     devices = MongoDevice.objects.all()
     device = devices.get(id=int(d_id))
-
     myuser_type = request.user_type
     if not myuser_type == 1 and device.device_expire == "1":
         raise PortError('', "该设备已到期")
-
     control_type = post_info.get("control_type", '')
     if not control_type:
         raise PortError('control_type',"参数缺失")
@@ -202,9 +227,25 @@ def get_device_config(request):
         payload = {"cmd":"read","ext":"data"}
     elif int(device_type_id) == 8:
         topic = "/yfkj/xyv3/s2c/%s" % device.device_id
-    # TODO 暂时处理调用http接口
-    code = 200
-    if code == 200:
+    
+    cmd = {
+        "topic": topic, 
+        "payload": json.dumps(payload), 
+        "qos": 1
+    }   
+    # mqtt 协议 
+    logger.warning(f"设备下发的指令:{cmd}")
+    response = requests.post(
+        "%s"%config_dict['mqtt_config']["http"], 
+        json=cmd,
+        auth=HTTPBasicAuth(
+            config_dict['mqtt_config']["user"], 
+            config_dict['mqtt_config']["secret_key"]
+            )
+    )
+    logger.warning(f"设备的返回值:{response}")
+    response_code = response.status_code
+    if response_code == 200:
         return True
     else:
         return False
@@ -214,39 +255,6 @@ def get_device_config(request):
 def admin_device_control(request):
     """
     单个按钮管理员操作  设备控制
-    参数:
-    device_type_id              必传                         设备类型  2杀虫灯,3测报灯,4智能性诱,5气象站,6监控设备,7孢子仪, 9糖醋测报灯 14色诱测报灯 8性诱3.0 12吸虫塔
-    d_id                        必传                         设备自增id
-    cmd                         必传                         设备控制参数  poweroff关机
-                                                                        poweron开机
-                                                                        reboot重启
-                                                                        update升级
-                                                                        coldoff制冷关闭
-                                                                        coldon制冷开启
-                                                                        takephoto拍照
-                                                                        autotakephoto 对焦拍照
-                                                                        boot1 屏幕禁用
-                                                                        boot0 屏幕取消禁用
-                                                                        turnset 设置定时卷粘虫板时间
-                                                                        turn 卷粘虫带/转仓
-                                                                        photoset 拍照时刻
-                                                                        repower 重新上电
-                                                                        data    数据上传
-                                                                        mqttconf  mqtt网络配置
-                                                                        close_shake 关闭震动
-                                                                        open_shake  开启震动
-                                                                        clearworm   清网
-                                                                        dtu_reboot  重启
-                                                                        dtu_update  升级
-                                                                        test        杀虫灯一键测试
-                                                                        big_data    平台转换到大数据平台
-                                                                        yfwlw       平台转发到四情平台
-                                                                        location 手动定位,传lat、lng 参数
-                                                                        imei 修改设备号, 传 imei 参数设备号
-                                                                        photo_num  拍照数量 传num 参数 拍照数
-    parm                        非必传                     当某些控制操作需要参数限制的时候 必传  (比如设置定时时间10分钟  传 10)
-
-
     """
     #测报灯  下发主题  /yfkj/cbd/sub/+imei
     #杀虫灯  下发主题  /yfkj/scd/sub/+imei
@@ -404,150 +412,19 @@ def admin_device_control(request):
             payload = {"cmd":"rtu_takephoto"}
     payload = json.dumps(payload)
     data = {"topic":topic,"payload":payload,"qos":1}
-    # TODO 调用大数据平台接口
-    response_code = 200
+    logger.warning(f"设备下发的指令:{data}")
+    response = requests.post(
+        "%s" % config_dict['mqtt_config']["http"], 
+        json=data,
+        auth=HTTPBasicAuth(
+                config_dict['mqtt_config']["user"], 
+                config_dict['mqtt_config']["secret_key"]
+            )
+        )
+    logger.warning(f"设备的返回值:{response}")
+    response_code = response.status_code
     if response_code == 200:
         return True
     else:
         return False
 
-
-
-def tccbd_device_control(request):
-    """
-    糖醋测报单个按钮操作/设备设置
-    参数:
-    device_type_id              必传                         设备类型   9 糖醋测报灯
-    d_id                        必传                         设备自增id
-    cmd                         必传                         设备控制参数  reboot重启
-                                                                        update升级
-                                                                        takephoto拍照
-                                                                        boot1 屏幕禁用
-                                                                        status 查询最新状态
-                                                                        paramconf 查询配置信息
-                                                                        
-
-                                                                        set 下发设置所需参数
-                                                                        st 定时开始时间
-                                                                        et 定时结束时间
-                                                                        collt 收集时间
-                                                                        htim 糖醋液发挥时间
-                                                                        datt 数据上传时间间隔
-                                                                        pump_sec 水泵打开时间
-                                                                        shake_sec 电磁阀打开时间
-                                                                        jp 加液排水时间
-
-
-    """
-    
-    post_info = request.POST
-    device_type_id = post_info.get("device_type_id", '')
-    d_id = post_info.get("d_id", '')
-    cmd = post_info.get("cmd", '')
-    devices = Device.objects.all()
-    device_id = devices.get(id=int(d_id)).device_id
-    if not cmd:
-        raise PortError('cmd', "参数缺失")
-    if  int(device_type_id) == 9:
-        if cmd == "takephoto":
-            payload = {"ext": {"type": "takephoto"}, "cmd": "ctrl"}
-        elif cmd == "reboot":
-            payload = {"cmd":"reboot","ext":""}
-        elif cmd == "update":
-            payload = {"cmd":"update","ext":""}
-        elif cmd == "status":
-            payload = {"cmd": "read", "ext": {"type": "status"}}
-        elif cmd == "paramconf":
-            payload = {"cmd": "read", "ext": {"type": "paramconf"}}
-        elif cmd == "boot1":
-            payload = {"cmd": "paramconf","ext": {"st": 20,"et": 5,"collt": 10,"htim": 0,"datt": 20,"pump_sec": 20,"shake_sec": 20,"boot": 1}}
-        elif cmd == "set":
-            st = post_info.get('st') #定时开始时间
-            et = post_info.get('et')#定时结束时间
-            collt = post_info.get('collt') #收集时间
-            htim = post_info.get('htim') #糖醋液发挥时间
-            datt = post_info.get('datt') #数据上传时间间隔
-            pump_sec = post_info.get('pump_sec')    #pump_sec水泵打开时间
-            shake_sec = post_info.get('shake_sec') #电磁阀打开时间
-            jp = post_info.get("jp")  # 加液排水时间
-            payload = {"cmd": "paramconf","ext": {"st": int(st),"et": int(et),"collt": int(collt),"htim": int(htim),"datt": int(datt),"pump_sec": int(pump_sec),"shake_sec": int(shake_sec),"jp":int(jp),"boot": 0}}
-
-        topic = "/yfkj/tccbd/sub/%s" % device_id
-        payload = json.dumps(payload)
-        data = {"topic":topic,"payload":payload,"qos":1}
-        res = requests.post("%s" % config_dict['mqtt_config']["http"], json=data,
-                            auth=HTTPBasicAuth(config_dict['mqtt_config']["user"], config_dict['mqtt_config']["secret_key"]))
-        if res.status_code == 200:
-            return True
-    else:
-        raise PortError('cmd', "设备类型错误")
-
-
-
-
-def device_sim(request):
-    """
-    设备查询sim卡接口
-    d_id                        必传                         设备自增id
-    iccid                       非必传                       用户填写的iccid
-    type                        必传                         sim卡类型 sim  hksim 海康sim  change修改 iccid
-    
-    """
-    post_info = request.POST
-    _device_id = post_info.get("d_id")
-    iccid = post_info.get("iccid")
-
-    types = post_info.get("type")
-
-    if not _device_id:
-        raise PortError('d_id', "未传设备id")
-
-    if iccid and not iccid.isalnum():
-        # if not iccid.isalnum():
-        raise PortError('iccid', "不能输入特殊字符")
-
-    data = []
-    try:
-        device = Device.objects.get(id=_device_id)
-    except:
-        raise PortError('d_id', "没有该设备")
-    if types == "hksim":
-        data.append({"iccid":device.simid})
-    elif types == "sim":
-        if device.device_type_id == 7:
-            models = BZYData
-        elif device.device_type_id == 4:
-            models = XYCBData
-        elif device.device_type_id == 2:
-            models = SCDData
-        elif device.device_type_id == 3:
-            models = CBDData
-        elif device.device_type_id == 8:
-            models = XYThreeData
-        elif device.device_type_id == 14:
-            models = SYCBData
-        elif device.device_type_id == 12:
-            models = XCTData
-        else:
-            raise PortError('d_id', "暂无该设备类型")
-        
-        # if device.device_type_id == 12:
-        #     models = XCTData
-
-        decic = models.objects.filter(device_id=_device_id).order_by('-id')[:1]
-        # decic = DeviceData.objects.filter(device_id=_device_id).order_by('-addtime')[:1]
-        for  i in decic:
-            try:
-                iccid = eval(i.device_data)["iccid"]
-            except:
-                iccid = ""
-            data.append({"iccid":iccid})
-    elif types == "change":
-        device.simid = iccid
-        device.save()
-        data.append({"iccid":iccid})
-    else:
-        raise PortError('d_id', "参数有误")
-    return data
-
-

+ 1 - 1
smartfarming/models/weather.py

@@ -117,7 +117,7 @@ class MongoQXZ_Conf(models.Model):
 class MongoQXZ_Alarm(models.Model):
     id = models.AutoField(primary_key=True)
     device_id = models.CharField(max_length=50, default='') # 设备id
-    conf = models.TextField(u'短信配置', blank=True, null=True)
+    conf = models.TextField(u'配置', blank=True, null=True)
     phone = models.CharField(u'手机号',max_length=20, blank=True)
     upl_time = models.IntegerField(u'上报时间',default=0)
 

+ 2 - 1
smartfarming/serializers/ascend_serializers.py

@@ -69,6 +69,7 @@ class MongoLandInfoSerializers(serializers.ModelSerializer):
         queryset = LandPlanInfo.objects.filter(land_id=land_id).order_by("-addtime").first()
         status = queryset.status
         plan_id = queryset.plan_id
+        plan_time = queryset.plan_time
         plan_obj = MongoPlantInfo.objects.filter(id=plan_id)
         if plan_obj:
             plan_obj = plan_obj.first()
@@ -79,7 +80,7 @@ class MongoLandInfoSerializers(serializers.ModelSerializer):
             plan_name = ""
             pickcode = ""
         if queryset:
-            return {"pl_id": queryset.id, "plan_id": plan_id, "plan_name": plan_name,"pickcode": pickcode, "status": status}
+            return {"pl_id": queryset.id, "plan_id": plan_id, "plan_name": plan_name,"plan_time": plan_time, "pickcode": pickcode, "status": status}
         else:
             return {}
 

+ 4 - 2
smartfarming/urls.py

@@ -54,7 +54,8 @@ from smartfarming.views.device import (
     DeviceListAPIView,
     DeviceChangeAPIView,
     DeviceListAPIView,
-    QxzDeviceAddAPIViw
+    QxzDeviceAddAPIViw,
+    CbdPhotoAPIView
 )
 
 from smartfarming.views.knowledge import (
@@ -132,6 +133,7 @@ urlpatterns = [
     path("weekend_delete", PlanWeekendDelete.as_view()),  # 生成周期删除
     path("device_add", CbdScdXyDeviceSaveAPIView.as_view()),  # 增加设备及数据接口  【提供给大数据平台】
     path("qxz_add", QxzDeviceAddAPIViw.as_view()),  # 增加气象站数据接口  【提供给大数据平台】
+    path("cbd_photo", CbdPhotoAPIView.as_view()),  # 测报灯图片  【提供给大数据平台】
     path("device_info", DeviceListInfoAPIView.as_view()), # 设备信息列表
     path("device", DeviceListAPIView.as_view()), # 设备列表(用于一张图)
     path("device_update", DeviceChangeAPIView.as_view()), # 设备更新
@@ -143,7 +145,7 @@ urlpatterns = [
 
     path("pest", PestBankAPIView.as_view()),  # 虫害列表
 
-    path("plan_info", LandPlanInfoAPIView.as_view()), # 种植作物列表及统计
+    path("plan_info", LandPlanInfoAPIView.as_view()), # 种植作物列表及统计  采收分析
     path("plan_name", PlanNameAPIView.as_view()), # 作物名称数组
     path("land_area_plan_count", PlanAreaAPIView.as_view()),  # 种植面积与作物个数统计
     path("device_status", DeviceCountAPIView.as_view()), # 统计设备在线或离线统计

+ 1 - 1
smartfarming/utils.py

@@ -438,7 +438,7 @@ def off_on_live(appId,appSecret,liveToken,status):
 def setDeviceSnap(appId,appSecret,deviceId,channelId="0"):
     # 抓图接口
     url = config.get("camera").get("lc_device_snap_enhanced")
-    url = config.get("camera").get("lc_device_snap")
+    # url = config.get("camera").get("lc_device_snap")
     time,nonce,sign,token = device_config(appId, appSecret)
     if not token:
         return {"msg": "抓图失败"}

+ 11 - 13
smartfarming/views/counts_views.py

@@ -30,30 +30,27 @@ class LandPlanInfoAPIView(APIView):
         page_num = int(request_data.get("pagenum")) if request_data.get("pagenum") else 1
         page_size = int(request_data.get("pagesize")) if request_data.get("pagesize") else 10
         start_timestamp, end_timestatmp = 0, 0
+        queryset = LandPlanInfo.objects.filter(is_delete=1).exclude(recovery_time=0).order_by("-addtime")
         if year:
             start_timestamp = datetime.datetime(int(year), 1,1,0,0).timestamp()
-            end_timestatmp = datetime.datetime(int(year), 12,31,23,59).timestamp()
-        plan_ids_head = []
-        if plan :
-            plan_ids_head = MongoPlantInfo.objects.filter(plantname__icontains=plan).values_list("id", flat=True)
-        if plan_ids_head and year:
-            queryset = LandPlanInfo.objects.filter(Q(plan_id__in = plan_ids_head) & Q(addtime__gte=start_timestamp, addtime__lte=end_timestatmp)).exclude(recovery_time=0).filter(is_delete=1).order_by("-addtime")
-        elif year:
-            queryset = LandPlanInfo.objects.filter(addtime__gte=start_timestamp, addtime__lte=end_timestatmp).filter(is_delete=1).exclude(recovery_time=0).order_by("-addtime")
-        elif plan_ids_head:
-            queryset = LandPlanInfo.objects.filter(plan_id__in = plan_ids_head).filter(is_delete=1).exclude(recovery_time=0).order_by("-addtime")
-        else:
-            queryset = LandPlanInfo.objects.filter(is_delete=1).exclude(recovery_time=0).order_by("-addtime")
+            end_timestatmp = datetime.datetime(int(year), 12,31,23,59).timestamp()            
+            queryset = queryset.filter(addtime__gte=start_timestamp, addtime__lte=end_timestatmp)
+        if plan:
+            ids_lst = MongoPlantInfo.objects.filter(plantname__icontains=plan).values_list("id", flat=True)
+            queryset = queryset.filter(plan_ids__in = ids_lst)
         total_obj = queryset.count()
         paginator = Paginator(queryset, page_size)
         page_obj = paginator.get_page(page_num)
         serializers = LandPlanInfoSerializers(page_obj, many=True)
         # 折线图
+        # 获取最近5年年份列表
+        current_year = datetime.datetime.now().year
+        year_list = [year for year in range(current_year, current_year - 6, -1)]        
         year_value = LandPlanInfo.objects.all().exclude(recovery_time=0).values_list("addtime", flat=True).order_by("-addtime")
         years = []
         for year in year_value:
             y = datetime.datetime.fromtimestamp(year).year
-            if y not in years:
+            if y not in years and y in year_list:
                 years.append(y)
         years.reverse()
         # 获取最近5年的作物ID
@@ -69,6 +66,7 @@ class LandPlanInfoAPIView(APIView):
                 plan_totals = LandPlanInfo.objects.filter(
                     addtime__gte=start_timestamp, 
                     addtime__lte=end_timestatmp).exclude(recovery_time=0).values("plan_id").annotate(total=Sum("recovery_kg")).order_by("plan_id").values_list("plan_id", "total")
+                # 作物 id:总质量
                 inners = {}
                 for k in plan_totals:
                     inners[str(k[0])] = k[1]

+ 150 - 78
smartfarming/views/device.py

@@ -8,7 +8,8 @@ import logging
 from smartfarming.utils import get_addr_by_lag_lng
 from smartfarming.serializers.device_serializers import DeviceSerializers
 from smartfarming.models.device import MongoDevice, MongoCBDData, MongoSCDData, MongoXYCBData
-from smartfarming.models.weather import MongoQXZ_Base_Info, MongoQXZ_Info_Record, MongoQXZ_Conf, QXZdata_New
+from smartfarming.models.worm_forecast import MongoCBDphoto
+from smartfarming.models.weather import MongoQXZ_Base_Info, MongoQXZ_Alarm_Log_New, MongoQXZ_Conf, QXZdata_New, MongoQXZ_Alarm
 from django.db.models import Q
 
 from smartfarming.qxz import data_deal
@@ -30,83 +31,120 @@ class CbdScdXyDeviceSaveAPIView(APIView):
 
     def post(self, request):
         # 测报灯 杀虫灯 性诱 设备及数据入库
-        data = request.data 
-        topic = data.get("topic")
-        payload = data.get("payload")
-        cmd = payload.get("cmd")
-        topic_msg = topic.split("/")
-        now = int(time.time())
-        if topic_msg and len(topic_msg) == 5 and cmd:
-            device_id = topic_msg[-1]
-            try:
-                device_type = topic_msg[2]
-                device_type_id = device_type_en.get(device_type)
-                if device_type_id == 2:
-                    model = MongoSCDData
-                elif device_type_id == 3:
-                    model = MongoCBDData
-                elif device_type_id == 8:
-                    model = MongoXYCBData
-                # 在设备信息表中查找是否有数据,如果没有数据则增加
-                device_name = device_type_zh.get(device_type_id)
-                device, is_created = MongoDevice.objects.get_or_create(
-                    device_id = device_id,
-                    defaults={
-                        "device_id": device_id,
-                        "device_type_id": device_type_id,
-                        "device_name": device_name,
-                        "addtime": now
-                    }
-                )
-                if is_created:
-                    logger.info(f"{device_type} 设备 {device_id} 入库成功")
-                # 获取数据并更新设备
-                if cmd == "data":
-                    ext = payload.get("ext")
-                    if ext:
-                        # 增加设备数据
-                        model.objects.create(
-                            device_id = device_id,
-                            device_data = str(ext),
-                            addtime = now
-                        )
-                        lng = ext.get("lng")
-                        lat = ext.get("lat")
-                        dver_num = ext.get("dver")
-                        device.device_status = 1
-                        device.uptime = now
-                        if dver_num:
-                            device.dver_num = dver_num
-                        if lng and lat and dver_num:
-                            device.lng = lng
-                            device.lat = lat
-                            # 根据经纬度获取省市级
-                            is_success, province, city, district = get_addr_by_lag_lng(lat, lng)
-                            if is_success:
-                                # 更新地理位置坐标
-                                device.province = province
-                                device.city = city
-                                device.district = district
+        try:
+            data = request.data 
+            logger.info(f"测报灯 杀虫灯 性诱 设备及数据入库原数据: {data}")
+            topic = data.get("topic")
+            payload = data.get("payload")
+            cmd = payload.get("cmd")
+            topic_msg = topic.split("/")
+            now = int(time.time())
+            if topic_msg and len(topic_msg) == 5 and cmd:
+                device_id = topic_msg[-1]
+                try:
+                    device_type = topic_msg[2]
+                    device_type_id = device_type_en.get(device_type)
+                    if device_type_id == 2:
+                        model = MongoSCDData
+                    elif device_type_id == 3:
+                        model = MongoCBDData
+                    elif device_type_id == 8:
+                        model = MongoXYCBData
+                    # 在设备信息表中查找是否有数据,如果没有数据则增加
+                    device_name = device_type_zh.get(device_type_id)
+                    device, is_created = MongoDevice.objects.get_or_create(
+                        device_id = device_id,
+                        defaults={
+                            "device_id": device_id,
+                            "device_type_id": device_type_id,
+                            "device_name": device_name,
+                            "addtime": now
+                        }
+                    )
+                    if is_created:
+                        logger.info(f"{device_type} 设备 {device_id} 入库成功")
+                    # 获取数据并更新设备
+                    if cmd == "data":
+                        ext = payload.get("ext")
+                        if ext:
+                            # 增加设备数据
+                            model.objects.create(
+                                device_id = device_id,
+                                device_data = str(ext),
+                                addtime = now
+                            )
+                            lng = ext.get("lng")
+                            lat = ext.get("lat")
+                            dver_num = ext.get("dver")
+                            device.device_status = 1
+                            device.uptime = now
+                            if dver_num:
+                                device.dver_num = dver_num
+                            if lng and lat and dver_num:
+                                device.lng = lng
+                                device.lat = lat
+                                # 根据经纬度获取省市级
+                                is_success, province, city, district = get_addr_by_lag_lng(lat, lng)
+                                if is_success:
+                                    # 更新地理位置坐标
+                                    device.province = province
+                                    device.city = city
+                                    device.district = district
+                                device.save()
+                    elif cmd == "offline":
+                        ext = data.get("ext")
+                        if ext:
+                            # 增加设备数据
+                            model.objects.create(
+                                device_id=device_id,
+                                device_data = str(ext),
+                                addtime=now
+                            )
+                            # 更新设备状态
+                            device = MongoDevice.objects.filter(device_id=device_id).first()
+                            device.device_status = 0
                             device.save()
-                elif cmd == "offline":
-                    ext = data.get("ext")
-                    if ext:
-                        # 增加设备数据
-                        model.objects.create(
-                            device_id=device_id,
-                            device_data = str(ext),
-                            addtime=now
-                        )
-                        # 更新设备状态
-                        device = MongoDevice.objects.filter(device_id=device_id).first()
-                        device.device_status = 0
-                        device.save()
-                return Response({"code": 0, "msg": "success"})
-            except Exception as e:
-                logger.error(f"测报灯设备 {device_id} 处理上报数据或增加设备失败,错误原因:{e.args}")
-                return Response({"code": 2, "msg": f"处理测报灯上报数据失败 {device_id}"}) 
-        else:
-            return Response({"code": 2, "msg": "请核对数据结构"}) 
+                    return Response({"code": 0, "msg": "success"})
+                except Exception as e:
+                    logger.error(f"测报灯设备 {device_id} 处理上报数据或增加设备失败,错误原因:{e.args}")
+                    return Response({"code": 2, "msg": f"处理测报灯上报数据失败 {device_id}"}) 
+            else:
+                return Response({"code": 2, "msg": "请核对数据结构"}) 
+        except Exception as e:
+            logger.error(f"测报灯、杀虫灯、性诱设备 {e.args}")
+            return Response({"code": 2, "msg": "failer"}) 
+        
+
+class CbdPhotoAPIView(APIView):
+
+    def post(self, request):
+        try:
+            request_data = request.data
+            logger.info(f"测报灯图片数据入库原数据: {request_data}")
+            device_id = request_data.get("imei")
+            device = MongoDevice.objects.filter(device_id=device_id)
+            if device:
+                device = device.first()
+                d_id = device.id 
+                data = {
+                    "device_id": d_id,
+                    "addr": request_data.get("Image"),
+                    "indentify_photo": request_data.get("Result_image"),
+                    "indentify_result": request_data.get("Result"),
+                    "label": request_data.get("Result_code"),
+                    "photo_status": 1,
+                    "uptime": int(time.time()),
+                    "addtime": int(time.time())
+                }
+                photo = MongoCBDphoto(**data)
+                photo.save()
+                return Response({"code": 0, "msg": "success"}) 
+            else:
+                return Response({"code": 2, "msg": "该设备不存在本机器"})
+        except Exception as e:
+            logger.error(f"测报灯图片 {e.args}")
+            return Response({"code": 2, "msg": "failer"})
+        
         
 class QxzDeviceAddAPIViw(APIView):
     permission_classes = []
@@ -115,17 +153,51 @@ class QxzDeviceAddAPIViw(APIView):
         # 气象站上传数据
         try:
             request_data = request.data 
+            logger.info(f"气象站数据入库原数据: {request_data}")
             device_id = request_data.get("StationID")
             uptime = request_data.get("MonitorTime")
             data = request_data.get("data")
             terminalStatus = request_data.get("terminalStatus")
             cmd = request_data.get("cmd")
+            # 获取该设备的预警配置数据
+            alarm = MongoQXZ_Alarm.objects.filter(device_id=device_id)
+            qxz_e_conf = MongoQXZ_Conf.objects.filter(device_id=device_id)
             if data:
                 qx_ek = {}
+                result_tp_fin = ""
                 for i in data:
                     tp_value = i.get("eValue")
                     if tp_value:
-                        qx_ek[i.get("eKey")] = tp_value
+                        ek = i.get("eKey")
+                        qx_ek[ek] = tp_value
+                        if alarm:
+                            # 先查看配置文件中是否有配置  -- "0#6" 表示大于6则报警  "1#5" 表示小于5报警  "0#" 表示不配置
+                            alarm = alarm.first()
+                            alarm_config = eval(alarm.conf)
+                            dat = alarm_config.get("dat")
+                            for m, n in dat:
+                                n_sp = n.split("#")
+                                if n_sp[1]:
+                                    if ek == m:
+                                        # 查询具体含义
+                                        zh = qxz_e_conf.m 
+                                        zh_k = zh.split("#")
+                                        result = ""
+                                        if n_sp == "0":
+                                            if float(tp_value) > float(n_sp[1]):
+                                                # 组织预警信息
+                                                result = f"为{tp_value},大于{n_sp[1]}"
+                                        elif n_sp == "1":
+                                            if float(tp_value) < float(n_sp[1]):
+                                                result = f"为{tp_value},小于{n_sp[1]}"
+                                        if result:
+                                            result_tp = f"{zh_k[0]}{result}{zh_k[1]},"
+                                            result_tp_fin += result_tp
+                if result_tp_fin:
+                    alarm_new = MongoQXZ_Alarm_Log_New()
+                    alarm_new.warning_content = result_tp_fin
+                    alarm_new.save()
+                    logger.info(f"{device_id}  产生预警")
                 if data:
                     # 30分钟上报一次的数据
                     qx_ek["device_id"] = device_id

+ 9 - 1
test

@@ -56,8 +56,10 @@
     },
     "image_url": {
       "image":"http://192.168.0.36:8000",
-      "discern": "http://192.168.0.36:8000"
+      "discern": "http://192.168.0.36:8000",
+      "identify_url": "http://60.166.14.184:9143/upload"
     },
+
     "camera": {
       "lc_addr": "https://openapi.lechange.cn/openapi/bindDeviceLive",
       "lc_stream": "https://openapi.lechange.cn/openapi/getLiveStreamInfo",
@@ -71,5 +73,11 @@
       "lc_kit_token": "https://openapi.lechange.cn/openapi/getKitToken", 
       "ys_open": "https://open.ys7.com/api/lapp/live/video/open",
       "ys_get": "https://open.ys7.com/api/lapp/live/address/get"
+    },
+    "mqtt_config":{
+      "http": "http://8.136.98.49:8080/api/v4/mqtt/publish",
+      "mqttIp": "8.136.98.49",
+      "user":"mq_yfkj",
+      "secret_key" : "Mjk2NjEyMDM4MDk3MjYyNjY3MzAyNzAyOTg5NDY1MzU0MjE"
     }
 }