yf_yzl 2 éve
szülő
commit
ca98e18362

+ 6 - 14
formal

@@ -1,4 +1,5 @@
 {
+  "server_web": "http://60.14.40.10:8001",
   "bigdata": {
     "debug": 0,
     "mysql_host": "127.0.0.1",
@@ -7,20 +8,6 @@
     "mysql_password": "1qaz@WSXkedong",
     "mysql_db": "smartfarming"
   },
-  "mqtt_record_db": {
-    "debug": 0,
-    "mysql_host": "127.0.0.1",
-    "mysql_port": 3306,
-    "mysql_user": "kedong",
-    "mysql_password": "kedongDK@2023",
-    "mysql_db": "mqtt_record_db"
-  },
-  "mqtt":{
-    "ip": "111.111.111.111",
-    "port": 61883,
-    "user":"user",
-    "password": "f335bf402c655ee5fd2b5300905124e"
-  },
   "redis": {
     "ip": "127.0.0.1",
     "port": 6380,
@@ -73,7 +60,12 @@
     "lc_addr": "https://openapi.lechange.cn/openapi/bindDeviceLive",
     "lc_stream": "https://openapi.lechange.cn/openapi/getLiveStreamInfo",
     "lc_token": "https://openapi.lechange.cn/openapi/accessToken",
+    "lc_device_snap": "https://openapi.lechange.cn/openapi/setDeviceSnap",
+    "lc_device_snap_enhanced": "https://openapi.lechange.cn/openapi/setDeviceSnapEnhanced",
     "lc_controler": "https://openapi.lechange.cn/openapi/controlMovePTZ",
+    "lc_modify_live_plan": "https://openapi.lechange.cn/openapi/modifyLivePlan",
+    "lc_modify_live_plan_status": "https://openapi.lechange.cn/modifyLivePlanStatus", 
+    "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"
   }

+ 1 - 10
kedong/settings.py

@@ -93,16 +93,7 @@ DATABASES = {
         'HOST': CONFIG['bigdata']['mysql_host'],
         'PORT': CONFIG['bigdata']['mysql_port'],
         'OPTIONS': {'charset': 'utf8mb4'}
-    },
-    # "mqtt_record_db": {
-    #     'ENGINE': 'django.db.backends.mysql',
-    #     'NAME': CONFIG['mqtt_record_db']['mysql_db'],
-    #     'USER': CONFIG['mqtt_record_db']['mysql_user'],
-    #     'PASSWORD': CONFIG['mqtt_record_db']['mysql_password'],
-    #     'HOST': CONFIG['mqtt_record_db']['mysql_host'],
-    #     'PORT': CONFIG['mqtt_record_db']['mysql_port'],
-    #     'OPTIONS': {'charset': 'utf8mb4'}
-    # }
+    }
 }
 # redis连接
 # REDIS 订阅数据

+ 103 - 0
scripts/test/qx_default_conf.py

@@ -0,0 +1,103 @@
+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
+from smartfarming.models.weather import QXZdata_New, QXZ_Default_Conf
+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():
+    user = parse.quote_plus("root")
+    passwd = parse.quote_plus("yfkj@6020")
+    # 账号密码方式连接MongoDB | "mongodb://用户名:密码@公网ip:端口/"
+    myclient = pymongo.MongoClient("mongodb://{0}:{1}@8.136.98.49:57017/".format(user,passwd))
+    # myclient = pymongo.MongoClient("mongodb://127.0.0.1:12514/")
+    # 指定数据库
+    db = myclient.smartfarming
+    # 指定集合
+    collection = db.sa_device
+    collection1 = db.sa_qxz_conf
+
+    for k in qx_device:
+        data = {'device_id': k}
+        cursor = collection1.find(data,{'_id':0,'id':0})
+
+        for i in cursor:
+            qx_data = QXZ_Default_Conf.objects.create(
+                device_id = i['device_id'],
+                uptime = i['uptime'],
+                e1 = i['e1'],
+                e2 = i['e2'],
+                e3 = i['e3'],
+                e4 = i['e4'],
+                e5 = i['e5'],
+                e6 = i['e6'],
+                e7 = i['e7'],
+                e8 = i['e8'],
+                e9 = i['e9'],
+                e10 = i['e10'],
+                e11 = i['e11'],
+                e12 = i['e12'],
+                e13 = i['e13'],
+                e14 = i['e14'],
+                e15 = i['e15'],
+                e16 = i['e16'],
+                e17 = i['e17'],
+                e18 = i['e18'],
+                e19 = i['e19'],
+                e20 = i['e20'],
+                e21 = i['e21'],
+                e22 = i['e22'],
+                e23 = i['e23'],
+                e24 = i['e24'],
+                e25 = i['e25'],
+                e26 = i['e26'],
+                e27 = i['e27'],
+                e28 = i['e28'],
+                e29 = i['e29'],
+                e30 = i['e30']
+            )
+        print(f"设备: {k} 数据量  {cursor.count()}")
+    return True
+
+
+if __name__ == "__main__":
+    dsj_qxz_conf_info()

+ 89 - 0
scripts/test/qx_switch_conf.py

@@ -0,0 +1,89 @@
+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
+from smartfarming.models.weather import (
+    MongoQXZ_Switch,
+    MongoQXZ_Auto_Switch,
+    MongoQXZ_Timing_Switch,
+    QXZ_Switch_Status
+)
+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():
+    user = parse.quote_plus("root")
+    passwd = parse.quote_plus("yfkj@6020")
+    # 账号密码方式连接MongoDB | "mongodb://用户名:密码@公网ip:端口/"
+    myclient = pymongo.MongoClient("mongodb://{0}:{1}@8.136.98.49:57017/".format(user,passwd))
+    # myclient = pymongo.MongoClient("mongodb://127.0.0.1:12514/")
+    # 指定数据库
+    db = myclient.smartfarming
+    # 指定集合
+    collection = db.sa_device
+    collection1 = db.sa_qxz_base_info
+
+    for k in qx_device:
+        data = {'device_id': k}
+        cursor = collection1.find(data,{'_id':0,'id':0})
+
+        for i in cursor:
+            qx_data, is_created = MongoQXZ_Base_Info.objects.get_or_create(
+                device_id = i.get("device_id"),
+                defaults={
+                    "volt": i.get("volt"),
+                    "rssi": i.get("rssi"),
+                    "iccid": i.get("iccid"),
+                    "lng": i.get("lng"),
+                    "lat": i.get("lat"),
+                    "led": i.get("led"),
+                    "ledinfo": i.get("ledinfo"),
+                    "dver": i.get("dver"),
+                    "uptime": i.get("uptime")                    
+                }
+            )
+        print(f"设备: {k} 数据量  {cursor.count()} {qx_data.id, is_created} ")
+    return True
+
+
+if __name__ == "__main__":
+    # dsj_qxz_conf_info()
+    pass 

+ 39 - 9
smartfarming/api/views/camera/camera_manage.py

@@ -17,7 +17,7 @@ from smartfarming.models.sim_card import MongoMsg_Conf
 from smartfarming.models.device import MongoDevice
 from smartfarming.models.camera import MongoCameraPhoto, MongoCameraData, MongoCameraAccount
 from smartfarming.serializers.device_serializers import DeviceSerializers
-from smartfarming.utils import bindDeviceLive, getLive, controlMove, modify_live_time, off_on_live, setDeviceSnap
+from smartfarming.utils import bindDeviceLive, getLive, controlMove, modify_live_time, off_on_live, setDeviceSnap, getKitToken
 from kedong.tools import RedisPool
 from kedong.decoration import kedong_deco, PortError
 
@@ -449,25 +449,26 @@ def camera_takephoto(request):
     appId = camera_query.app_key
     appSecret = camera_query.app_secret
     snap_url = setDeviceSnap(appId, appSecret, device_id, channelNo)
-    time.sleep(1) 
     print(snap_url)
     if snap_url:
         # 图片保存位置 
         config = settings.CONFIG
-        camera_path = config.get("media") + "/jiankong/" + device_id + "/" + time.strftime("%Y%m%d", time.localtime())
+        save_path = "/jiankong/" + device_id + "/" + time.strftime("%Y%m%d", time.localtime())
+        camera_path = config.get("media") + save_path
         os.makedirs(camera_path) if not os.path.exists(camera_path) else None
         stamp = int(time.time())
         unique_id = uuid.uuid4()
         combined_id = str(stamp) + "-" + str(unique_id)
-        camera_photos = camera_img_name = combined_id + ".jpg"
-        camera_path + "/" + camera_img_name
+        camera_photos = combined_id + ".jpg"
+        img_path = os.path.join(camera_path, camera_photos)
+        # 下载图片
         img_query = requests.get(snap_url)
         if img_query.status_code == 200:
-            img = Image.open(BytesIO(img_query.content)) #获取图片
-            img.save(camera_path) #报存到文件夹
+            img = Image.open(BytesIO(img_query.content))
+            img.save(img_path)
             camera_obj = MongoCameraPhoto.objects.create(
                 device_id=d_id,
-                addr=camera_photos,
+                addr=f"/media{save_path}/{camera_photos}",
                 photo_status=1,
                 addtime=int(time.time())
             )
@@ -497,4 +498,33 @@ def camera_photo(request):
     paginator = Paginator(queryset, page_size)
     page_obj = paginator.get_page(page_num)
     serializers = MongoCameraPhotoSerializers(page_obj, many=True)
-    return {"data": serializers.data, "counts": queryset.count()}
+    return {"data": serializers.data, "counts": queryset.count()}
+
+
+@kedong_deco(login_required=True)
+def get_camera_dh_token(request):
+    """ 
+    获取大华相机token 
+    参数:
+    device_id                必传(string)                   设备号
+    """
+    device_id = request.POST.get("device_id")
+    if not device_id:
+        raise PortError("","参数缺失")
+    camera_query = MongoCameraData.objects.filter(device_id=device_id).first()
+    if not camera_query:
+        raise PortError("","未找到此设备")
+    camera_account_query = MongoCameraAccount.objects.filter(id=camera_query.account_id).first()
+    if not camera_account_query:
+        raise PortError("","此设备未绑定监控账号")
+    if camera_account_query.account_type == 0:
+        raise PortError('', '海康监控暂不支持获取token')
+    if device_id.find("-") != -1:
+        channelNo = device_id.split("-")[1]
+        device_id = device_id.split("-")[0]
+    appId = camera_account_query.app_key
+    appSecret = camera_account_query.app_secret
+    like_token_data = getKitToken(appId, appSecret,device_id,channelNo)
+    return like_token_data
+
+

+ 102 - 1
smartfarming/api/views/device/device_manage.py

@@ -1,9 +1,26 @@
 import datetime
+import time
 from smartfarming.models.device import MongoDevice, MongoSCDData, MongoDeviceType, MongoXYCBData
 from kedong.decoration import kedong_deco, PortError
 from smartfarming.utils import get_address_by_lntlat, get_weather_info
+from smartfarming.models.user import MongoOperateLogs
 
 
+def operation_log(uid,content,target_id,operation_type,ip):
+    """
+    uid                     必传              操作者id
+    content                 必传              操作内容
+    target_id               必传              被操作者id
+    operation_type          必传              对设备操作0 对用户操作传1
+
+    """
+    if not (uid or content or target_id or operation_type or ip):
+        raise PortError('log',"日志记录参数缺失")
+    try:
+        MongoOperateLogs(addtime=int(time.time()), uid=uid, content=content, target_id=target_id,operation_type=operation_type,ip=ip).save()
+    except Exception as e:
+        print("操作日志存储失败", e)
+
 
 @kedong_deco(login_required=False)
 def weathers(request):
@@ -242,4 +259,88 @@ def xycb_gis_info(request):
         "infr_ct": data_info.get('infr_ct', '0'),
         "csq": data_info.get('csq')
     }
-    return data
+    return data
+
+
+@kedong_deco(login_required=True)
+def get_spore_time(request):
+    """
+    获取孢子仪载玻片/培养夜时间
+    获取性诱设备优芯
+    参数:
+    device_type_id                  必传                         设备类型  7孢子仪 4性诱设备
+    d_id                            必传                         设备自增id
+
+    返回:
+    glass_slide_time 载玻片更换时间
+    cultivate_time 培养液更换时间
+    """
+    post_info = request.POST
+    device_type_id = post_info.get("device_type_id", '')
+    d_id = post_info.get("d_id", '')
+    if not d_id:
+        raise PortError('d_id', "参数缺失")
+    if not device_type_id:
+        raise PortError('device_type_id',"参数缺失")
+    devices = MongoDevice.objects.get(id=d_id, device_type_id=device_type_id)
+    if int(device_type_id) == 7:
+        glass_slide_time = devices.glass_slide_time
+        cultivate_time = devices.cultivate_time
+        if glass_slide_time == 0 or cultivate_time == 0:
+            glass_slide_time = ""
+            cultivate_time = ""
+        return {
+            "glass_slide_time":glass_slide_time,
+            "cultivate_time":cultivate_time,
+                }
+    elif int(device_type_id) == 4:
+        decoy = devices.decoy
+        return {
+            "decoy":decoy
+        }
+    
+
+
+@kedong_deco(login_required=True)
+def updata_spore_time(request):
+    """
+    更新孢子仪载玻片/培养夜时间
+    更新性诱设备诱芯
+    参数:
+    device_type_id                              必传                         设备类型  7孢子仪  4性诱设备
+    d_id                                        必传                         设备自增id
+    glass_slide_time                            必传                         载玻片更换时间
+    cultivate_time                              必传                         培养液更换时间
+    decoy                                       必传                         性诱设备诱芯
+
+    """
+    myuid = request.myuser.uid
+    user_type = request.user_type
+    post_info = request.POST
+    device_type_id = post_info.get("device_type_id", '')
+    d_id = post_info.get("d_id", '')
+    glass_slide_time = post_info.get("glass_slide_time", '')
+    cultivate_time = post_info.get("cultivate_time", '')
+    decoy = post_info.get("decoy", '')
+    if not d_id:
+        raise PortError('d_id', "参数缺失")
+    if not device_type_id:
+        raise PortError('device_type_id',"参数缺失")
+    try:
+        devices = MongoDevice.objects.get(id=d_id)
+    except:
+        raise PortError('',"未找到此设备")
+    if int(device_type_id) == 7:
+        devices.glass_slide_time = glass_slide_time
+        devices.cultivate_time = cultivate_time
+        devices.save()
+        content = "更新孢子仪,载玻片时间:%s,培养夜时间:%s"
+        operation_log(myuid, content % (glass_slide_time, cultivate_time), devices.device_id, 0, request.ip)
+    elif int(device_type_id) == 4:
+        if not decoy:
+            raise PortError('decoy',"参数缺失")
+        devices.decoy = decoy
+        devices.save()
+        content = "更新性诱设备诱芯:%s"
+        operation_log(myuid, content % decoy, devices.device_id, 0, request.ip)
+    return True

+ 307 - 9
smartfarming/api/views/weather/weather.py

@@ -16,6 +16,13 @@ from kedong.decoration import kedong_deco, PortError
 from smartfarming.models.device import MongoDevice, MongoCBDData
 from smartfarming.models.weather import MongoQXZ_Base_Info, QXZdata_New, MongoQXZ_Conf, QXZstatus_New, MongoQXZ_Alarm
 from smartfarming.api.views.weather.all_dict import qxz_dict
+from smartfarming.models.weather import (
+    MongoQXZ_Switch,
+    MongoQXZ_Auto_Switch,
+    MongoQXZ_Timing_Switch,
+    QXZ_Switch_Status,
+    QXZ_Default_Conf
+)
 
 config_dict = settings.CONFIG
 
@@ -901,12 +908,303 @@ def device_status_data(request):
     }
     return up_st
 
-# config = {
-#         'host': config_dict['bigdata']['django_mysql_host'],
-#         'port': int(config_dict['bigdata']['django_mysql_port']),
-#         'user': config_dict['bigdata']['django_mysql_user'],
-#         'password': config_dict['bigdata']['django_mysql_password'],
-#         'db': config_dict['bigdata']['django_mysql_db'],
-#         'charset': 'utf8mb4',
-#         'cursorclass': pymysql.cursors.DictCursor,
-#     }
+@kedong_deco(login_required=True)
+def qxz_switch_status(request):
+    """
+    气象站开关、阈值状态接口
+    参数:
+    device_id            必传(str)              设备号
+    
+    返回值:
+    {
+    qxz_switch: "[{'status': 0, 'JK': 0}, {'status': 0, 'JK': 1}]"                        开关状态
+    switch_name: "[{'name': '开关0', 'JK': 0}, {'name': '', 'JK': 1}]"                     开关名称
+    timing_list: "[{'JK': 0, 'Duration': 4, 'StartTime': 3}, {'JK': 1, 'Duration': 8, 'StartTime': 7}]"     定时控制
+    auto_list: [{'lower': 32767, 'JK': 0, 'method': 0, 'upper': 32767, 'eKey': 0}]"    阈值状态
+    }
+    """
+    device_id = request.POST.get("device_id")
+    data = []
+    try:
+        switch_obj = QXZ_Switch_Status.objects.get(device_id=device_id)
+        qxz_switch = switch_obj.qxz_switch
+    except:
+        qxz_switch = ""
+    try:
+        switch_name_obj = MongoQXZ_Switch.objects.get(device_id=device_id)
+        switch_name = switch_name_obj.qxz_switch_data
+    except:
+        switch_name = ""
+    try:
+        timing_list = MongoQXZ_Timing_Switch.objects.get(device_id=device_id).qxz_timing
+    except:
+        timing_list = ""
+    
+    try:
+        auto_list = MongoQXZ_Auto_Switch.objects.get(device_id=device_id).qxz_auto
+    except:
+        auto_list = ""
+    data = {'qxz_switch':qxz_switch, 'switch_name':switch_name, 'timing_list':timing_list,"auto_list":auto_list}
+    return data
+
+
+
+@kedong_deco(login_required=False)
+def qxz_element_conf(request):
+    """
+    气象站查看通道要素接口\保存通道要素接口:
+    参数:
+    device_id          必传(str)                设备号
+    status             必传(str)                当status等于see查看, 当status等于save保存
+    ekey               非必传(str)              通道号 如e1
+    conf               非必传(str)              通道标题,如大气温度#℃
+    
+    说明:当status等于see查看,只需要传device_id,当status等于save保存 需传device_id、conf、ekey
+    返回值:
+    当status等于see时:
+        "data": {
+        "default": {                                   原来值
+            "e1": "大气温度#℃",
+            "e2": "大气湿度#%RH",
+            "e3": "风速#m/s",
+            "e4": "风向#°",
+            "e5": "模拟气压#hpa",
+            "e6": "简易总辐射#w/㎡"
+        },
+        "conf": {                                      修改值
+            "e1": "大气温度#℃",
+            "e2": "大气湿度#%RH",
+            "e3": "风速#m/s",
+            "e4": "风向#°",
+            "e5": "模拟气压#hpa",
+            "e6": "简易总辐射#w/㎡"
+        }
+    },
+
+
+    当status等于save时:
+    {
+        "data" 0                  0 保存成功 1失败
+    }
+
+    """
+    device_id = request.POST.get("device_id")
+    status = request.POST.get("status")
+    ekey = request.POST.get("ekey")
+    conf = request.POST.get("conf")
+
+    if status == "see":
+        x = MongoQXZ_Conf.objects.get(device_id=device_id)
+        i = QXZ_Default_Conf.objects.get(device_id=device_id)
+        conf = {"e1":x.e1,"e2":x.e2,"e3":x.e3,"e4":x.e4,"e5":x.e5,
+                "e6":x.e6,"e7":x.e7,"e8":x.e8,"e9":x.e9,"e10":x.e10,
+                "e11":x.e11,"e12":x.e12,"e13":x.e13,"e14":x.e14,
+                "e15":x.e15,"e16":x.e16,"e17":x.e17,"e18":x.e18,
+                "e19":x.e19,"e20":x.e20,"e21":x.e21,"e22":x.e22,
+                "e23":x.e23,"e24":x.e24,"e25":x.e25,"e26":x.e26,
+                "e27":x.e27,"e28":x.e28,"e29":x.e29,"e30":x.e30}
+        default = {"e1":i.e1,"e2":i.e2,"e3":i.e3,"e4":i.e4,"e5":i.e5,
+                "e6":i.e6,"e7":i.e7,"e8":i.e8,"e9":i.e9,"e10":i.e10,
+                "e11":i.e11,"e12":i.e12,"e13":i.e13,"e14":i.e14,
+                "e15":i.e15,"e16":i.e16,"e17":i.e17,"e18":i.e18,
+                "e19":i.e19,"e20":i.e20,"e21":i.e21,"e22":i.e22,
+                "e23":i.e23,"e24":i.e24,"e25":i.e25,"e26":i.e26,
+                "e27":i.e27,"e28":i.e28,"e29":i.e29,"e30":i.e30}
+
+        for k in list(conf.keys()): 
+            if not conf[k]:
+                del conf[k]
+
+        for y in list(default.keys()): 
+            if not default[y]:
+                del default[y]
+        data = {"default":default,"conf":conf}
+    elif status == "save":
+        times = int(time.time())
+        conf_obj = MongoQXZ_Conf.objects.get(device_id=device_id)
+        if ekey == "e1":
+            con = (conf_obj.e1).split("#")
+            conf_obj.e1 = conf + "#"+ con[1]
+            conf_obj.update = times
+            conf_obj.save()
+            data = {"code": 0}
+        elif ekey == "e2":
+            con = (conf_obj.e2).split("#")
+            conf = conf + "#"+ con[1]
+            conf_obj.e2 = conf
+            conf_obj.update = times
+            conf_obj.save()
+            data = {"code": 0}
+        elif ekey == "e3":
+            con = (conf_obj.e3).split("#")
+            conf_obj.e3 = conf + "#"+ con[1]
+            conf_obj.update = times
+            conf_obj.save()
+            data = {"code": 0}
+        elif ekey == "e4":
+            con = (conf_obj.e4).split("#")
+            conf_obj.e4 = conf + "#"+ con[1]
+            conf_obj.update = times
+            conf_obj.save()
+            data = {"code": 0}
+        elif ekey == "e5":
+            con = (conf_obj.e5).split("#")
+            conf_obj.e5 = conf + "#"+ con[1]
+            conf_obj.update = times
+            conf_obj.save()
+            data = {"code": 0}
+        elif ekey == "e6":
+            con = (conf_obj.e6).split("#")
+            conf_obj.e6 = conf + "#"+ con[1]
+            conf_obj.update = times
+            conf_obj.save()
+            data = {"code": 0}
+        elif ekey == "e7":
+            con = (conf_obj.e7).split("#")
+            conf_obj.e7 = conf + "#"+ con[1]
+            conf_obj.update = times
+            conf_obj.save()
+            data = {"code": 0}
+        elif ekey == "e8":
+            con = (conf_obj.e8).split("#")
+            conf_obj.e8 = conf + "#"+ con[1]
+            conf_obj.update = times
+            conf_obj.save()
+            data = {"code": 0}
+        elif ekey == "e9":
+            con = (conf_obj.e9).split("#")
+            conf_obj.e9 = conf + "#"+ con[1]
+            conf_obj.update = times
+            conf_obj.save()
+            data = {"code": 0}
+        elif ekey == "e10":
+            con = (conf_obj.e10).split("#")
+            conf_obj.e10 = conf + "#"+ con[1]
+            conf_obj.update = times
+            conf_obj.save()
+            data = {"code": 0}
+        elif ekey == "e11":
+            con = (conf_obj.e11).split("#")
+            conf_obj.e11 = conf + "#"+ con[1]
+            conf_obj.update = times
+            conf_obj.save()
+            data = {"code": 0}
+        elif ekey == "e12":
+            con = (conf_obj.e12).split("#")
+            conf_obj.e12 = conf + "#"+ con[1]
+            conf_obj.update = times
+            conf_obj.save()
+            data = {"code": 0}
+        elif ekey == "e13":
+            con = (conf_obj.e13).split("#")
+            conf_obj.e13 = conf + "#"+ con[1]
+            conf_obj.update = times
+            conf_obj.save()
+            data = {"code": 0}
+        elif ekey == "e14":
+            con = (conf_obj.e14).split("#")
+            conf_obj.e14 = conf + "#"+ con[1]
+            conf_obj.update = times
+            conf_obj.save()
+            data = {"code": 0}
+        elif ekey == "e15":
+            con = (conf_obj.e15).split("#")
+            conf_obj.e15 = conf + "#"+ con[1]
+            conf_obj.update = times
+            conf_obj.save()
+            data = {"code": 0}
+        elif ekey == "e16":
+            con = (conf_obj.e16).split("#")
+            conf_obj.e16 = conf + "#"+ con[1]
+            conf_obj.update = times
+            conf_obj.save()
+            data = {"code": 0}
+        elif ekey == "e17":
+            con = (conf_obj.e17).split("#")
+            conf_obj.e17 = conf + "#"+ con[1]
+            conf_obj.update = times
+            conf_obj.save()
+            data = {"code": 0}
+        elif ekey == "e18":
+            con = (conf_obj.e18).split("#")
+            conf_obj.e18 = conf + "#"+ con[1]
+            conf_obj.update = times
+            conf_obj.save()
+            data = {"code": 0}
+        elif ekey == "e19":
+            con = (conf_obj.e19).split("#")
+            conf_obj.e19 = conf + "#"+ con[1]
+            conf_obj.update = times
+            conf_obj.save()
+            data = {"code": 0}
+        elif ekey == "e20":
+            con = (conf_obj.e20).split("#")
+            conf_obj.e20 = conf + "#"+ con[1]
+            conf_obj.update = times
+            conf_obj.save()
+            data = {"code": 0}
+        elif ekey == "e21":
+            con = (conf_obj.e21).split("#")
+            conf_obj.e21 = conf + "#"+ con[1]
+            conf_obj.update = times
+            conf_obj.save()
+            data = {"code": 0}
+        elif ekey == "e22":
+            con = (conf_obj.e22).split("#")
+            conf_obj.e22 = conf + "#"+ con[1]
+            conf_obj.update = times
+            conf_obj.save()
+            data = {"code": 0}
+        elif ekey == "e23":
+            con = (conf_obj.e23).split("#")
+            conf_obj.e23 = conf + "#"+ con[1]
+            conf_obj.update = times
+            conf_obj.save()
+            data = {"code": 0}
+        elif ekey == "e24":
+            con = (conf_obj.e24).split("#")
+            conf_obj.e24 = conf + "#"+ con[1]
+            conf_obj.update = times
+            conf_obj.save()
+            data = {"code": 0}
+        elif ekey == "e25":
+            con = (conf_obj.e25).split("#")
+            conf_obj.e25 = conf + "#"+ con[1]
+            conf_obj.update = times
+            conf_obj.save()
+            data = {"code": 0}
+        elif ekey == "e26":
+            con = (conf_obj.e26).split("#")
+            conf_obj.e26 = conf + "#"+ con[1]
+            conf_obj.update = times
+            conf_obj.save()
+            data = {"code": 0}
+        elif ekey == "e27":
+            con = (conf_obj.e27).split("#")
+            conf_obj.e27 = conf + "#"+ con[1]
+            conf_obj.update = times
+            conf_obj.save()
+            data = {"code": 0}
+        elif ekey == "e28":
+            con = (conf_obj.e28).split("#")
+            conf_obj.e28 = conf + "#"+ con[1]
+            conf_obj.update = times
+            conf_obj.save()
+            data = {"code": 0}
+        elif ekey == "e29":
+            con = (conf_obj.e29).split("#")
+            conf_obj.e29 = conf + "#"+ con[1]
+            conf_obj.update = times
+            conf_obj.save()
+            data = {"code": 0}
+        elif ekey == "e30":
+            con = (conf_obj.e30).split("#")
+            conf_obj.e30 = conf + "#"+ con[1]
+            conf_obj.update = times
+            conf_obj.save()
+            data = {"code": 0}
+        else:
+            data = {"code": 1}
+    else:
+        raise PortError("","参数超出范围")
+    return data

+ 1 - 1
smartfarming/models/ascend.py

@@ -316,7 +316,7 @@ class CountryModel(models.Model):
     introduce = models.TextField("简介", default="")
     content = models.TextField("正文", default="")
     uptime = models.IntegerField("添加时间", default=0)
-    cover_img = models.CharField("封面", max_length=64, default="")
+    cover_img = models.CharField("封面", max_length=128, default="")
     is_delete = models.IntegerField("是否删除", default=1)
     
 

+ 55 - 1
smartfarming/models/weather.py

@@ -155,6 +155,17 @@ class MongoQXZ_Alarm_Log_New(models.Model):
         db_table = "sa_qxz_alarm_log_new"
 
 
+# 气象站开关配置表
+class QXZ_Switch_Status(models.Model):
+
+    id = models.AutoField(primary_key=True)
+    device_id = models.CharField(max_length=50, default='') # 设备id
+    upl_time = models.IntegerField(u'上报时间', default=0)
+    qxz_switch = models.TextField(u'气象站开关', blank=True, null=True)
+
+    class Meta:
+        db_table = "sa_qxz_switch_status"
+
 
 # 气象站开关配置表
 class MongoQXZ_Switch(models.Model):
@@ -275,4 +286,47 @@ class QXZThresholdWarning(models.Model):
 
     class Meta:
         db_table = "sa_device_threshold_warning"
-        
+        
+
+
+
+# 新气象站默认配置表
+class QXZ_Default_Conf(models.Model):
+
+    id = models.AutoField(primary_key=True)
+    device_id = models.CharField(max_length=50, default='')  # 设备id
+    e1 = models.CharField(u'通道1', max_length=30, blank=True, null=True)
+    e2 = models.CharField(u'通道2', max_length=30, blank=True, null=True)
+    e3 = models.CharField(u'通道3', max_length=30, blank=True, null=True)
+    e4 = models.CharField(u'通道4', max_length=30, blank=True, null=True)
+    e5 = models.CharField(u'通道5', max_length=30, blank=True, null=True)
+    e6 = models.CharField(u'通道6', max_length=30, blank=True, null=True)
+    e7 = models.CharField(u'通道7', max_length=30, blank=True, null=True)
+    e8 = models.CharField(u'通道8', max_length=30, blank=True, null=True)
+    e9 = models.CharField(u'通道9', max_length=30, blank=True, null=True)
+    e10 = models.CharField(u'通道10', max_length=30, blank=True, null=True)
+    e11 = models.CharField(u'通道11', max_length=30, blank=True, null=True)
+    e12 = models.CharField(u'通道12', max_length=30, blank=True, null=True)
+    e13 = models.CharField(u'通道13', max_length=30, blank=True, null=True)
+    e14 = models.CharField(u'通道14', max_length=30, blank=True, null=True)
+    e15 = models.CharField(u'通道15', max_length=30, blank=True, null=True)
+    e16 = models.CharField(u'通道16', max_length=30, blank=True, null=True)
+    e17 = models.CharField(u'通道17', max_length=30, blank=True, null=True)
+    e18 = models.CharField(u'通道18', max_length=30, blank=True, null=True)
+    e19 = models.CharField(u'通道19', max_length=30, blank=True, null=True)
+    e20 = models.CharField(u'通道20', max_length=30, blank=True, null=True)
+    e21 = models.CharField(u'通道21', max_length=30, blank=True, null=True)
+    e22 = models.CharField(u'通道22', max_length=30, blank=True, null=True)
+    e23 = models.CharField(u'通道23', max_length=30, blank=True, null=True)
+    e24 = models.CharField(u'通道24', max_length=30, blank=True, null=True)
+    e25 = models.CharField(u'通道25', max_length=30, blank=True, null=True)
+    e26 = models.CharField(u'通道26', max_length=30, blank=True, null=True)
+    e27 = models.CharField(u'通道27', max_length=30, blank=True, null=True)
+    e28 = models.CharField(u'通道28', max_length=30, blank=True, null=True)
+    e29 = models.CharField(u'通道29', max_length=30, blank=True, null=True)
+    e30 = models.CharField(u'通道30', max_length=30, blank=True, null=True)
+    # upl_time = models.DateTimeField(u'数据上传时间', default=timezone.now)
+    uptime = models.IntegerField(default=0)  # 修改时间
+
+    class Meta:
+        db_table = "sa_qxz_default_conf"

+ 19 - 15
smartfarming/serializers/ascend_serializers.py

@@ -7,27 +7,31 @@ from smartfarming.serializers.pests_serializers import PestBankSerializers
 from smartfarming.models.pests_bank import MongoPestBank
 
 
+def count_base_area():
+    BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+    try:
+        with open(os.path.join(BASE_DIR, "gcj02.json"), 'r', encoding="utf-8") as f:
+            base = json.load(f)
+        features = base.get("features")
+        base_size = 0
+        base_lng_lat = []
+        for f in features:
+            attributes = f.get("attributes", {})
+            base_size += float(attributes.get("亩"))
+            base_lng_lat.append(f.get("geometry", {}).get("rings", [])[0])
+        return base_size, base_lng_lat
+    except Exception as e:
+        print(e)
+        return 0, []
+
+
 class BaseSerializers(serializers.ModelSerializer):
 
     base_area = serializers.SerializerMethodField()
     base_lng_lat = serializers.SerializerMethodField()
 
     def base_info(self):
-        BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-        try:
-            with open(os.path.join(BASE_DIR, "gcj02.json"), 'r', encoding="utf-8") as f:
-                base = json.load(f)
-            features = base.get("features")
-            base_size = 0
-            base_lng_lat = []
-            for f in features:
-                attributes = f.get("attributes", {})
-                base_size += float(attributes.get("亩"))
-                base_lng_lat.append(f.get("geometry", {}).get("rings", [])[0])
-            return base_size, base_lng_lat
-        except Exception as e:
-            print(e)
-            return 0, []
+        return count_base_area()
         
     def get_base_area(self, obj):
         base_size, _ = self.base_info()

+ 6 - 1
smartfarming/urls.py

@@ -84,7 +84,9 @@ from smartfarming.views.counts_views import (
     RecentPestCountAPIView,
     AlermNewsAPIView,
     QxzCameraList,
-    QxzCameraUpdate
+    QxzCameraUpdate,
+    APPAlarmAPIView,
+    KeDongOverAPIView
 )
 from smartfarming.views.weather import WeatherAPIView,QxzListAPIView,QxzShangAPIView
 
@@ -170,6 +172,9 @@ urlpatterns = [
     path("qx_ca_lst", QxzCameraList.as_view()),  # 气象摄像列表
     path("qx_ca_update", QxzCameraUpdate.as_view()),  # 气象摄像位置更新
 
+    path("app_alarm", APPAlarmAPIView.as_view()), # 气象站与测报预警
+    path("app_count", KeDongOverAPIView.as_view()), # app 我的 页面  统计信息
+
 
     url(r'^pest_image_source_export$', PestImageSourceExport.as_view()), # 测报灯数据导出
     url(r'^pest_base_data_export$', PestBaseDataExport.as_view()), # 虫害基础数据导出

+ 16 - 0
smartfarming/utils.py

@@ -458,6 +458,22 @@ def get_weather(ip):
     response = json.loads(res.text)
     return response.get("data")
 
+
+def getKitToken(appId,appSecret,deviceId,channelId="0"):
+    # 获取录像回放所需要的token
+    url = config.get("camera").get("lc_kit_token")
+    time,nonce,sign,token = device_config(appId, appSecret)
+    if not token:
+        return {"result":{"code":"1"}}
+    data = {
+        "system":{"ver":"1.0","appId":appId,"sign":sign,"time":time,"nonce":nonce},
+        "id":nonce,
+        "params":{"type":0,"deviceId":deviceId,"channelId":channelId,"token":token}
+    }
+    like_token_data = requests.post(url,json=data)
+    return like_token_data.json()
+
+
 if __name__ == "__main__":
     t = get_recent_month(1)
     print(t)

+ 32 - 8
smartfarming/views/counts_views.py

@@ -13,10 +13,11 @@ from smartfarming.models.worm_forecast import MongoCBDphoto
 from smartfarming.models.pest_count import MongoCBDPestWarning
 from smartfarming.models.weather import MongoQXZ_Alarm_Log_New
 from smartfarming.serializers.ascend_serializers import LandPlanInfoSerializers
-from smartfarming.serializers.pests_serializers import PestBankSerializers, MongoQXZAlarmLogNewSerializers
+from smartfarming.serializers.pests_serializers import MongoCBDPestWarningSerializers, MongoQXZAlarmLogNewSerializers
 from smartfarming.utils import get_recent_month, get_weather
 from smartfarming.api.views.forecast.all_dict import insect_dict
 from smartfarming.models.device import MongoDevice
+from smartfarming.models.ascend import MongoBase
 
 
 class LandPlanInfoAPIView(APIView):
@@ -233,12 +234,24 @@ class AlermNewsAPIView(APIView):
 class APPAlarmAPIView(APIView):
 
     def post(self, request):
-        # todo 
-        pest_query = MongoCBDPestWarning.objects.all().order_by("-upltime")
-
-        
-
-
+        # 气象站与测报预警
+        request_data = request.data 
+        type_id = request_data.get("type_id")
+        data = {}
+        if type_id == "3":
+            # 虫情
+            query = MongoCBDPestWarning.objects.all().order_by("-upltime")
+            pest_serializers = MongoCBDPestWarningSerializers(query, many=True)
+            data = pest_serializers.data 
+        elif type_id == "5":
+            query = MongoQXZ_Alarm_Log_New.objects.all().order_by("-upl_time")
+            qxz_serializers = MongoQXZAlarmLogNewSerializers(query, many=True)
+            data = qxz_serializers.data
+        elif type_id == "8":
+            query = MongoQXZ_Alarm_Log_New.objects.all().order_by("-upl_time")
+            qxz_serializers = MongoQXZAlarmLogNewSerializers(query, many=True)
+            data = qxz_serializers.data
+        return Response({"code": 0, "msg": "success", "data": data})
         
 
 class QxzCameraList(APIView):
@@ -268,4 +281,15 @@ class QxzCameraUpdate(APIView):
                 ca_obj.save()
             return Response({"code": 0,"msg":"success"})
         except Exception as e:
-            return Response({"code": 2,"msg":"失败"})
+            return Response({"code": 2,"msg":"失败"})
+        
+    
+class KeDongOverAPIView(APIView):
+
+    def post(self, request): 
+        # 我的信息
+        country_count = CountryModel.objects.all().count()
+        area = MongoBase.objects.all().first().base_area
+        device = MongoDevice.objects.all().count()
+        return Response({"code": 0,"msg":"success", "data": {"country_count": country_count, "area": area, "device": device}})
+

+ 4 - 1
smartfarming/views/home_land.py

@@ -10,7 +10,8 @@ from smartfarming.serializers.ascend_serializers import (
     MongoAreaJobSerializers,
     CountryModelSerializers,
     PlanWeekendSerializers,
-    MongoPlanWeekendSerializers
+    MongoPlanWeekendSerializers,
+    count_base_area
 )
 
 
@@ -18,6 +19,8 @@ class BaseAPIView(APIView):
 
     def post(self, request):
         # 基地列表
+        size, lng_lat = count_base_area()
+        MongoBase.objects.update(base_area="%.2f" % size)
         query = MongoBase.objects.all().first()
         serializers = BaseSerializers(query)
         return Response({"code": 0, "msg": "success", "data": serializers.data})

+ 7 - 5
smartfarming/views/upload_file.py

@@ -6,19 +6,21 @@ from kedong.settings import MEDIA_ROOT
 import uuid
 import uuid
 from datetime import datetime
+from django.conf import settings
 
 
+config = settings.CONFIG
+
 class FileUploadView(APIView):
     # 上传图片
     def post(self, request):
+        server_web = config.get("server_web")
         path = request.data.get("model", "others")
         local_path = os.path.join(MEDIA_ROOT, path)
         os.mkdir(local_path) if not os.path.exists(local_path) else None 
         file_obj = request.data['file']
-        if file_obj.size > 1024 * 1024 * 10:
-            return Response({"code": 2, "msg": "请上传小于10M图片"})
-        # if (file_obj.name).split(".")[-1] not in ["jpeg", "jpg", 'png', 'bmp', 'tif','gif', 'flv', 'mp4']:
-        #     return Response({"code": 2, "msg": "请上传 jpeg jpg png 图片格式"})
+        if file_obj.size > 1024 * 1024 * 200:
+            return Response({"code": 2, "msg": "请上传小于200M文件"})
         try:
             stamp = int(datetime.now().timestamp())
             unique_id = uuid.uuid4()
@@ -27,7 +29,7 @@ class FileUploadView(APIView):
             with open(f"{local_path}/{file_name}", 'wb') as f:
                 for chunk in file_obj.chunks():
                     f.write(chunk)
-            return Response({"url": f'/media/{path}/{file_name}', "code": 0, "msg": "success"})
+            return Response({"url": f'{server_web}/media/{path}/{file_name}', "code": 0, "msg": "success"})
         except Exception as e:
             return Response({"code": 2, "msg": "图片保存失败,请检查或重试"})
 

+ 3 - 15
test

@@ -1,4 +1,5 @@
 {
+  "server_web": "http://192.168.0.36:8000",
     "bigdata": {
       "debug": 0,
       "mysql_host": "127.0.0.1",
@@ -7,20 +8,6 @@
       "mysql_password": "123456",
       "mysql_db": "smarfarming"
     },
-    "mqtt_record_db": {
-      "debug": 0,
-      "mysql_host": "127.0.0.1",
-      "mysql_port": 3306,
-      "mysql_user": "kedong",
-      "mysql_password": "kedongDK@2023",
-      "mysql_db": "mqtt_record_db"
-    },
-    "mqtt":{
-      "ip": "8.136.98.49",
-      "port": 61883,
-      "user":"user",
-      "password": "f335bf402c655ee5fd2b5300905124e"
-    },
     "redis": {
       "ip": "114.55.0.7",
       "port": 61881,
@@ -79,7 +66,8 @@
       "lc_device_snap_enhanced": "https://openapi.lechange.cn/openapi/setDeviceSnapEnhanced",
       "lc_controler": "https://openapi.lechange.cn/openapi/controlMovePTZ",
       "lc_modify_live_plan": "https://openapi.lechange.cn/openapi/modifyLivePlan",
-      "lc_modify_live_plan_status": "https://openapi.lechange.cn/modifyLivePlanStatus",  
+      "lc_modify_live_plan_status": "https://openapi.lechange.cn/modifyLivePlanStatus", 
+      "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"
     }