Kaynağa Gözat

PC端基本完成

yf_yzl 2 yıl önce
ebeveyn
işleme
c4e627e719

+ 73 - 6
formal

@@ -3,13 +3,80 @@
     "debug": 0,
     "mysql_host": "127.0.0.1",
     "mysql_port": 3306,
-    "mysql_user": "kedong",
-    "mysql_password": "%RDX2wsx9ijn%TGB",
+    "mysql_user": "root",
+    "mysql_password": "123456",
     "mysql_db": "smarfarming"
   },
-  "mqtt_config":{
-    "ip": "127.0.0.1",
-    "port": 1883,
-    "user":"mq_yfkj"
+  "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": "114.55.0.7",
+    "port": 61881,
+    "password": "yf6021",
+    "url": "redis://:yf6021@114.55.0.7:61881/"
+  },
+  "redis_db": {
+    "bigdata_pub": 11,
+    "bigdata_sub": 12,
+    "captcha": 4,
+    "scd": 2,
+    "cbd": 3,
+    "jiankong": 1
+
+  },
+  "dashuju_pub_key":"dashuju_pub_redis_key",
+  "ftp_config": {
+    "/data/ftp/photo/dh_cbd/": ["dh_cbd_users", "yf123456", "/data/ftp/photo/dh_cbd/"],
+    "/data/ftp/photo/bzy/test/": ["bzy_user", "YFkj@6O2O", "/data/ftp/photo/bzy/test/"],
+    "/data/ftp/photo/cbd/": ["cbd_user", "YFkj@6O2O", "/data/ftp/photo/cbd/"],
+    "/data/ftp/photo/jk/": ["jk_user", "yf123456", "/data/ftp/photo/jk/"],
+    "/data/ftp/photo/color/": ["color_attract", "yf_123456", "/data/ftp/photo/color/"],
+    "/data/ftp/photo/xyv3/": ["xyv3_user", "ftp_20220110", "/data/ftp/photo/xyv3/"],
+    "/data/ftp/photo/xct/": ["xct_user", "yf_123456", "/data/ftp/photo/xct/"]
+  },
+  "ftp": {
+    "ip": "0.0.0.0",
+    "port": 21
+  },
+  "media": "/pic/kedong/kdimgs",
+  "device_type_en": {
+    "cbd": 3,
+    "scd": 2,
+    "qxz": 5,
+    "sqz": 9,
+    "xycb": 8,
+    "jk": 6
+  },
+  "device_type_zh": {
+     "3": "测报灯",
+     "2": "杀虫灯",
+     "5": "气象站",
+     "8": "墒情站",
+     "4": "性诱测报",
+     "6": "监控"
+  },
+  "image_url": {
+    "image":"http://60.14.40.10:8000",
+    "discern": "http://60.14.40.10:8000"
+  },
+  "camera": {
+    "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_controler": "https://openapi.lechange.cn/openapi/controlMovePTZ",
+    "ys_open": "https://open.ys7.com/api/lapp/live/video/open",
+    "ys_get": "https://open.ys7.com/api/lapp/live/address/get"
   }
 }

+ 0 - 0
smartfarming/api/views/basemanager/__init__.py


+ 158 - 0
smartfarming/api/views/basemanager/device.py

@@ -0,0 +1,158 @@
+from json import JSONDecodeError
+import json
+import datetime
+from django.conf import settings
+from kedong.decoration import kedong_deco, PortError
+from smartfarming.models.device import MongoDevice, MongoCBDData, DevicePestWarning
+from smartfarming.models.worm_forecast import MongoCBDphoto
+from smartfarming.models.pest_count import MongoCBDPestWarning
+from smartfarming.models.weather import QXZThresholdWarning, QXZstatus_New, MongoQXZ_Conf
+
+
+@kedong_deco(login_required=True)
+def get_cbd_info(request):
+    """
+     获取基地绑定设备列表
+        参数:
+            device_id       必须      设备编码
+
+        返回值:
+        {
+            "data": {
+                'device_id': "1111111111111",           设备id
+                'device_name': "abc",                   设备名称
+                'address': "dizhi",                      设备地址
+                'uptime': "2022-01-01 12:12",           上报时间
+                "upds": 1,              上仓门状态 1打开,0关闭
+                "tpl": 5,               低温保护阈值温度
+                "dver": "1.0.0",        设备固件版本
+                "gs": 0,                通道状态 1落虫,0排水
+                "hs": 0,                加热状态 1加热,0正常
+                "dnds": 0,              下仓门状态 1打开,0关闭
+                "is_online": 0,         在线状态
+                "csq": 29,              信号强度
+                "tph": 70,              高温保护阈值温度
+                "ts": 0                 定时模式 0光控,1时控
+                "tps": 1                温控状态 1 温控,0 正常
+                "lps": 0                光控状态 1 光控,0 正常
+                "hrt": 22               加热仓实时温度
+                'img_list': img_list,                   图片列表
+                'warning_info': {                       警报信息
+                    "warning_status": 1,                预警类型, 1目标种类预警 2、指定害虫数量预警  3 害虫数量总和预警 4综合预警
+                    "warning_content": 'xxxxxx"         预警内容
+                }
+            },
+            "errorCode": 0,
+            "message": ,
+            "formError": {}
+        }
+
+    """
+    config_dict = settings.CONFIG
+    device_id = request.POST.get('device_id', '').strip()
+    device_info = MongoDevice.objects.get(device_id=device_id)
+    d_id = device_info.id
+    device_data = MongoCBDData.objects.filter(device_id=device_id).order_by('-id').first()
+    if device_data:
+        try:
+            device_data = json.loads(device_data.device_data)
+        except JSONDecodeError as e:
+            device_data = eval(device_data.device_data)
+        except:
+            raise PortError("device_id", "暂无数据")
+    else:
+        raise PortError("device_id", "暂无数据")
+
+    device_addr = f'{device_info.province}{device_info.city}{device_info.district}'
+    photo_list = MongoCBDphoto.objects.filter(device_id=d_id, photo_status=1).order_by("-id")
+    up_date = datetime.datetime.utcfromtimestamp(device_info.uptime)
+
+    http_img_url = config_dict["image_url"]["image"]
+    img_list = []
+    for p in photo_list[:3]:
+        img_url = p.indentify_photo
+        if not img_url:
+            img_url = p.addr
+        if not img_url.startswith('http'):
+            img_url = http_img_url + img_url
+
+        img_list.append(img_url)
+    warning_content = MongoCBDPestWarning.objects.filter(device_id=device_id).order_by("-id").values_list("warning_content", flat=True)
+    warning_info = {}
+    warning_info['warning_content'] = [i for i in warning_content]
+    
+
+    tmp_device_id = device_info.device_id
+    device_name = device_info.device_name
+
+    result = {
+        'device_id': tmp_device_id,
+        'device_name': device_name or tmp_device_id,
+        'uptime': up_date.strftime("%Y-%m-%d %H:%M:%S"),
+        'img_list': img_list,
+        'warning_info': warning_info,
+        "is_online": device_info.device_status,
+        "ts": device_data.get("ts", 1),
+        "hs": device_data["hs"],
+        "upds": device_data["upds"],
+        "dnds": device_data["dnds"],
+        "csq": device_data["csq"],
+        "dver": device_data["dver"],
+        "tph": device_data["tph"],
+        "tpl": device_data["tpl"],
+        "tps": device_data["tps"],
+        "lps": device_data["lps"],
+        "hrt": device_data["hrt"],
+        "rps": device_data["rps"],
+        "ds": device_data.get("ds", 1),
+        "address": device_addr,
+    }
+    return result
+
+
+
+@kedong_deco(login_required=True)
+def get_qxz_or_sq_info(request):
+    """
+    气象站或者墒情站数据详情接口
+    """
+    device_id = request.POST.get('device_id', '').strip()
+    device_info = MongoDevice.objects.get(device_id=device_id)
+    device_addr = f'{device_info.province}{device_info.city}{device_info.district}'
+    up_date = datetime.datetime.utcfromtimestamp(device_info.uptime)
+
+    warning_queryset = QXZThresholdWarning.objects.filter(device_id=device_id, status=0).order_by("-id")
+    warning_info = {}
+    try:
+        warn = warning_queryset[0]
+        warning_info['set_value'] = warn.set_value
+        warning_info['current_value'] = warn.current_value
+        warning_info['ekey'] = warn.ekey
+        warning_info['warning_content'] = warn.warning_content
+    except Exception as e:
+        pass
+
+    conf, dat = {}, {}
+    try:
+        qxz_status = QXZstatus_New.objects.filter(device_id=device_id).order_by('-id')[0]
+        qxz_conf = MongoQXZ_Conf.objects.get(device_id=device_id)
+        for i in range(1, 31):
+            k = f'e{i}'
+            conf[k] = getattr(qxz_conf, k)
+            dat[k] = getattr(qxz_status, k)
+    except Exception as e:
+        pass
+
+    temp_device_id = device_info.device_id
+    device_name = device_info.device_name
+    result = {
+        'device_id': temp_device_id,
+        'device_name': device_name or temp_device_id,
+        'address': device_addr,
+        'uptime': up_date.strftime("%Y-%m-%d %H:%M:%S"),
+        'device_status': "在线" if device_info.device_status == 1 else "离线",
+        'warning_info': warning_info,
+        'conf': conf,
+        'dat': dat,
+    }
+    return result

+ 12 - 40
smartfarming/api/views/camera/camera_manage.py

@@ -49,20 +49,15 @@ def list_camera(request):
 
     """
     _list = []
-    myuser = request.myuser
     post_info = request.POST
     device_id = post_info.get('device_id')
     page = int(post_info.get('page', 1))
     page_size = int(post_info.get('page_size', 10))
-
     search_dict = {
         "device_type_id": 6
     }
     if device_id:
         search_dict["device_id"] = re.compile(fr"^.*{device_id}.*$")
-
-    # total_num, data_list = MongoDevice.get_device_list(myuser, match=search_dict, page_num=page, page_size=page_size)
-
     queryset = MongoDevice.objects.filter(device_type_id=6).order_by("-uptime")
     total_num = queryset.count()
     paginator = Paginator(queryset, page_size)
@@ -74,7 +69,6 @@ def list_camera(request):
     for x in data_list:
         device_id = x.get("device_id")
         device_id_list.append(device_id)
-
         _list.append({
             "device_name": x.get("device_name"),
             "device_id": device_id,
@@ -83,11 +77,9 @@ def list_camera(request):
             "camera_playback": "",
             "sim": x.get("simid")
         })
-
     photo_queryset = MongoCameraPhoto.objects.filter(device_id__in=device_id_list, photo_status=1).values('device_id').annotate(count=Count('device_id'))
     phote_dict = {p['device_id']: "1" for p in photo_queryset}
     playback_dict = {y['device_id']: y["camera_playback"] for y in MongoCameraData.objects.filter(device_id__in=device_id_list).values('device_id','camera_playback')}
-
     for item in _list:
         item["photo_num"] = phote_dict.get(device_id, "0")
         item["camera_playback"] = playback_dict.get(device_id,"0")
@@ -116,7 +108,6 @@ def addr_camera_list(request):
     }
 
     """
-
     try:
         if 'HTTP_X_FORWARDED_FOR' in request.META:
             ip = request.META['HTTP_X_FORWARDED_FOR']
@@ -124,36 +115,7 @@ def addr_camera_list(request):
             ip = request.META['HTTP_X_REAL_IP']
     except Exception as KeyError:
         ip = request.META['REMOTE_ADDR']
-
-
-
     device_id = request.POST.get('device_id')
-    # try:
-    #     ic = InterfaceCallLog()
-    #     ic.ip = ip
-    #     ic.device_id = device_id
-    #     ic.interface = "addr_camera_list"
-    #     ic.meta = str(request.META)
-    #     ic.save()
-    # except Exception as e:
-    #     pass
-
-    # if device_id in jk_list.keys():
-    #     if redis_pool.get(device_id):
-    #         url_path = redis_pool.get(device_id)
-    #     else:
-    #         cameraIndexCode = jk_list.get(device_id,"")
-    #         url = "http://223.151.55.58:8082/zhcg-serve/hkVideo/api/getPreviewURLsByHls?cameraIndexCode={}&streamType=0".format(cameraIndexCode)
-    #         try:
-    #            url_path = (requests.get(url,timeout=5).json())["data"]["url"]
-    #         except:
-    #             url_path = "" 
-    #         # 设置播放地址到期时间5分钟
-    #         redis_pool.set(device_id,url_path,300)
-    #     # 因为其他设备返回的数值是字符串的,所以进行拼接
-    #     data =  "{'hls':'%s','hlsHd':'%s','rtmp':'%s','rtmpHd':'%s'}"%(url_path,url_path,url_path,url_path)
-    #     return data
-
     try:
         addr = MongoCameraData.objects.get(device_id=device_id).device_info
     except:
@@ -200,7 +162,12 @@ def ctrl_camera(request):
                 raise PortError("movenum","暂不支持其它指令")
             appId = camera_query.app_key
             appSecret = camera_query.app_secret
-            controlMove(appId,appSecret,device_id,dire,channelNo)
+            result = controlMove(appId,appSecret,device_id,dire,channelNo)
+            code = result.get("result").get("code")
+            if code == "0":
+                return True 
+            else:
+                return {"errorCode": 2, "msg": result.get("result").get("msg")}
         else:
             accessToken = camera_query.token
             ctrl_url = 'https://open.ys7.com/api/lapp/device/ptz/start'
@@ -214,7 +181,12 @@ def ctrl_camera(request):
             dire = "10"
             appId = camera_query.app_key
             appSecret = camera_query.app_secret
-            controlMove(appId,appSecret,device_id,dire,channelNo)
+            result = controlMove(appId,appSecret,device_id,dire,channelNo)
+            code = result.get("result").get("code")
+            if code == "0":
+                return True 
+            else:
+                return {"errorCode": 2, "msg": result.get("result").get("msg")}
         else:
             accessToken = camera_query.token
             ctrl_url = 'https://open.ys7.com/api/lapp/device/ptz/stop'

+ 150 - 2
smartfarming/api/views/device/device_manage.py

@@ -1,5 +1,5 @@
 import datetime
-from smartfarming.models.device import MongoDevice
+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
 
@@ -94,4 +94,152 @@ def weathers(request):
         "air_level": weather_info.get('air_level', ''),
         "air_tips": weather_info.get('air_tips', ''),
     })
-    return result
+    return result
+
+
+@kedong_deco(login_required=True)
+def scd_gis_info(request):
+    """
+        杀虫灯GIS展示信息
+        参数
+        device_id             必传(str)               设备ID
+
+        返回值:
+         "data": {
+            "address": "河南省新乡市原阳县",         设备地址
+            "uptime": "2022-01-02 12:12:12",      最新上传时间
+            "device_name": "xxxxxx",              设备名称
+            "device_id":"xxxxxxxxxxx",             设备ID
+            'device_status': "在线",                设备状态
+            "at": "30",                             温度
+            "ah": "50",                             湿度
+            "ws_status": "待机",                   工作状态
+            "rps_status": "正常",                  雨控状态
+            "tt": "4",                              定时时长
+            "ct": "0",                              电击次数
+            "csq": "0"                              信号强度
+            }
+
+        """
+    device_id = request.POST.get('device_id')
+    try:
+        device_info = MongoDevice.objects.get(device_id=device_id)
+    except Exception as e:
+        raise PortError("device_id", "设备id参数异常")
+
+    device_name = device_info.device_name
+    if not device_name:
+        device_name = MongoDeviceType.objects.get(id=4).type_name
+
+    up_date = datetime.datetime.utcfromtimestamp(device_info.uptime)
+
+    try:
+        queryset = MongoSCDData.objects.filter(device_id=device_info.id).order_by('-id')[0]
+        data_info = eval(queryset.device_data)
+    except Exception as e:
+        data_info = {}
+
+    ws = data_info.get('ws', '0')
+    ws_status = "待机"
+    if ws == "1":
+        ws_status = "工作"
+    elif ws == "2":
+        ws_status = "充电"
+
+    tt = data_info.get('tt', '0')
+    if tt == '0':
+        tt = '常亮'
+
+    rps_status = "正常" if data_info.get("rps", "0") == "0" else "保护"
+
+    data = {
+        "address": f"{device_info.province}{device_info.city}{device_info.district}",
+        "uptime": up_date.strftime("%Y-%m-%d %H:%M:%S"),
+        "device_name": device_name,
+        "device_id": device_info.device_id,
+        'device_status': "在线" if device_info.device_status == 1 else "离线",
+        "ws_status": ws_status,
+        "rps_status": rps_status,
+        "tt": tt,
+        "at": data_info.get('at', ''),
+        "ah": data_info.get('ah', ''),
+        "ct": data_info.get('ct', '0'),
+        "csq": data_info.get('csq', '0')
+    }
+    return data
+
+
+
+@kedong_deco(login_required=True)
+def xycb_gis_info(request):
+    """
+        性诱测报GIS展示信息
+        参数
+        device_id             必传(str)               设备ID
+
+        返回值:
+         "data": {
+            "address": "河南省新乡市原阳县",         设备地址
+            "uptime": "2022-01-02 12:12:12",      最新上传时间
+            "device_name": "xxxxxx",              设备名称
+            "device_id":"xxxxxxxxxxx",             设备ID
+            'device_status': "在线",                设备状态
+            "at": "30",                             温度
+            "ah": "50",                             湿度
+            "ws_status": "待机",                   工作状态
+            "cs_status": "非充电",                        充电状态
+            "bs_status": "正常",                    电池状态
+            "infr_ct": "0",                         击虫次数
+            "csq": "0"                              信号强度
+            }
+
+        """
+    device_id = request.POST.get('device_id')
+    try:
+        device_info = MongoDevice.objects.get(device_id=device_id)
+    except Exception as e:
+        raise PortError("device_id", "设备id参数异常")
+
+    device_name = device_info.device_name
+    if not device_name:
+        device_name = MongoDeviceType.objects.get(id=4).type_name
+
+    up_date = datetime.datetime.utcfromtimestamp(device_info.uptime)
+
+    try:
+        queryset = MongoXYCBData.objects.filter(device_id=device_info.id).order_by('-id')[0]
+        data_info = eval(queryset.device_data)
+    except Exception as e:
+        data_info = {}
+
+    ws = data_info.get('ws', '0')
+    ws_status = "待机"
+    if ws == "1":
+        ws_status = "工作"
+    elif ws == "2":
+        ws_status = "充电"
+
+    bs = data_info.get('bs', '0')
+    bs_status = '正常'
+    if bs == '1':
+        bs_status = '欠压'
+    elif bs == '2':
+        bs_status = '过压'
+
+    cs_status = '非充电' if data_info.get('cs', '0') == '0' else '充电'
+
+    data = {
+        "address": f"{device_info.province}{device_info.city}{device_info.district}",
+        "uptime": up_date.strftime("%Y-%m-%d %H:%M:%S"),
+        "device_name": device_name,
+        "device_id": device_info.device_id,
+        'device_status': "在线" if device_info.device_status == 1 else "离线",
+        "at": data_info.get('at', ''),
+        "ah": data_info.get('ah', ''),
+        "ws_status": ws_status,
+        "cs_status": cs_status,
+        "bs_status": bs_status,
+        "infr_ct": data_info.get('infr_ct', '0'),
+        "csq": data_info.get('csq')
+    }
+    return data

+ 0 - 13
smartfarming/api/views/forecast/all_dict.py

@@ -1109,19 +1109,6 @@ def expire_time(times):
         status = 0
         
     return status
-    
-    
-
-
-
-# 杜娟巫溪测报灯
-cbd_list = [
-    "867038039309101",
-    "867038039299773",
-    "867038039288347",
-    "867038039340080",
-    "867038039321510",
-]
 
 
 #色诱识别害虫标记

+ 11 - 4
smartfarming/urls.py

@@ -18,7 +18,8 @@ from smartfarming.views.user import (
     PerAPIView,
     CaptchaView,
     HomeThemeModelAPIView,
-    HomeThemeModelListAPIView
+    HomeThemeModelListAPIView,
+    APPUserLogin
 )
 
 from smartfarming.views.home_land import (
@@ -49,7 +50,8 @@ from smartfarming.views.home_land import (
 from smartfarming.views.device import (
     CbdScdXyDeviceSaveAPIView,
     DeviceListAPIView,
-    DeviceChangeAPIView
+    DeviceChangeAPIView,
+    DeviceListAPIView
 )
 
 from smartfarming.views.knowledge import (
@@ -70,12 +72,13 @@ from smartfarming.views.knowledge import (
 
 
 from smartfarming.views.pests_bank import PestBankAPIView
-from smartfarming.views.pest_image import PestImageSourceExport, PestBaseDataExport, QxzDataExport
+from smartfarming.views.pest_image import PestImageSourceExport, PestBaseDataExport, QxzDataExport, CbdExport
 from smartfarming.views.counts_views import (
     LandPlanInfoAPIView, 
     PlanNameAPIView, 
     PlanAreaAPIView, 
-    DeviceCountAPIView
+    DeviceCountAPIView,
+    RecentPestCountAPIView
 )
 from smartfarming.views.weather import WeatherAPIView,QxzListAPIView,QxzShangAPIView
 
@@ -97,6 +100,7 @@ urlpatterns = [
     path('theme', HomeThemeModelListAPIView.as_view()),  # 主题列表 
     path('theme_add', HomeThemeModelAPIView.as_view()),  # 修改主题 
     path("upload_file", FileUploadView.as_view()),  # 上传图片
+    path("app_login", APPUserLogin.as_view()), # 用户APP登录 
     
     path("base", BaseAPIView.as_view()),  # 基地列表
     path("base_update", BaseUpdateAPIView.as_view()),  # 基地修改
@@ -132,6 +136,8 @@ urlpatterns = [
     path("weather", WeatherAPIView.as_view()), # 天气接口
     path("shang", QxzListAPIView.as_view()), # 墒情列表接口
     path("shang_detail", QxzShangAPIView.as_view()), # 墒情详情
+    path("pest_month", RecentPestCountAPIView.as_view()), # 最近一个月害虫统计
+    path("land_deivce", DeviceListAPIView.as_view()),  # 设备绑定地块
 
 
     path("knowledge", KnowledgeCategoryAPIView.as_view()),  # 知识分类列表
@@ -152,4 +158,5 @@ urlpatterns = [
     url(r'^pest_image_source_export$', PestImageSourceExport.as_view()), # 测报灯数据导出
     url(r'^pest_base_data_export$', PestBaseDataExport.as_view()), # 虫害基础数据导出
     url(r'^qxz_data_export$', QxzDataExport.as_view()), # 气象站数据导出
+    url(r'^cbd_export$', CbdExport.as_view()), # 杀虫 性诱测报数据导出
 ]

+ 29 - 9
smartfarming/views/counts_views.py

@@ -1,17 +1,18 @@
+from django.core.paginator import Paginator
+import time
+import datetime
+from operator import itemgetter
+from django.db.models import Q, Sum, Count
+from django.conf import settings
 from rest_framework.views import APIView
 from rest_framework.response import Response
 from smartfarming.models.ascend import MongoBase, MongoLandInfo, MongoPlantInfo, MongoAreaJob, LandPlanInfo, CountryModel, PlanWeekend
 from smartfarming.models.user import DeviceUser
 from smartfarming.models.device import MongoDevice
 from smartfarming.models.worm_forecast import MongoCBDphoto
-from smartfarming.serializers.ascend_serializers import (
-    LandPlanInfoSerializers
-)
-from django.core.paginator import Paginator
-import time
-import datetime
-from django.db.models import Q, Sum, Count
-from django.conf import settings
+from smartfarming.serializers.ascend_serializers import LandPlanInfoSerializers
+from smartfarming.utils import get_recent_month
+from smartfarming.api.views.forecast.all_dict import insect_dict
 
 
 class LandPlanInfoAPIView(APIView):
@@ -158,4 +159,23 @@ class RecentPestCountAPIView(APIView):
 
     def post(self, request):
         # 统计最近一个月的害虫排名
-        MongoCBDphoto
+        start = get_recent_month(1)
+        data = MongoCBDphoto.objects.filter(uptime__gte=start).values_list("indentify_result", flat=True)
+        try:
+            pest_count = {}
+            for i in data:
+                tp_lst = i.split("#")
+                for k in tp_lst:
+                    pest = k.split(",")
+                    p_0 = pest[0]
+                    p_1 = pest[1]
+                    p_name = insect_dict.get(p_0)
+                    if p_name not in pest_count.keys():
+                        pest_count[p_name] = int(p_1)
+                    else:
+                        pest_count[p_name] += int(p_1)
+            result = sorted(pest_count.items(), key=itemgetter(1), reverse=False)
+            result = {m[0]:m[1] for m in result[-10:]}
+            return Response({"code": 0, "msg": "success", "data": result})
+        except Exception as e:
+            return Response({"code": 2, "msg": "数据有误,请核查"})

+ 89 - 0
smartfarming/views/device.py

@@ -13,6 +13,11 @@ from django.db.models import Q
 
 from smartfarming.qxz import data_deal
 
+from collections import Counter, defaultdict
+from smartfarming.models.device import MongoDevice, DevicePestWarning, MongoDeviceType
+from kedong.decoration import kedong_deco, PortError
+from django.core.paginator import Paginator
+
 
 logger = logging.getLogger("myapp")
 device_type_en = (settings.CONFIG).get("device_type_en")
@@ -199,3 +204,87 @@ class DeviceChangeAPIView(APIView):
         return Response({"code": 0, "msg": "success"})
 
 
+class DeviceListAPIView(APIView):
+
+    def post(self, request):
+        queryset = MongoDevice.objects.order_by('-id')
+        type_dict = {d.id: d.type_name for d in MongoDeviceType.objects.all()}
+        result = []
+        offline_list = []
+        type_counter = Counter()
+        device_dict = defaultdict(list)
+        for item in queryset:
+            device_info = item
+            device_type_id = device_info.device_type_id
+            device_status = device_info.device_status
+            is_offline = False if device_status == 1 else True
+            device_id = device_info.device_id
+            if is_offline:
+                offline_list.append(device_id)
+            type_counter[device_type_id] += 1
+
+            device_dict[device_type_id].append(device_id)
+
+            coordinates = ""
+            lng = device_info.lng
+            lat = device_info.lat
+            if not (lng and lat):
+                continue
+            coordinates = f"[{str(float(lng))},{str(float(lat))}]"
+
+            device_name = device_info.device_name
+            result.append({
+                'ld_id': item.id,
+                'device_id': device_id,
+                'device_name': device_name or device_id,
+                'tpye_name': type_dict[device_info.device_type_id],
+                'device_type_id': device_type_id,
+                'coordinates': coordinates,
+                'offline': False if device_status == 1 else True,
+                'is_warning': False
+            })
+
+        statistic_list = []
+        for k, v in type_counter.items():
+            statistic_list.append({
+                'type_id': k,
+                'type_count': v,
+                'type_name': type_dict[k]
+            })
+
+        warning_model_dict = {
+            3: DevicePestWarning
+        }
+        warning_list = []
+        for k, v in device_dict.items():
+            try:
+                model_obj = warning_model_dict[k]
+            except KeyError as e:
+                continue
+
+            war_list = [d.device_id for d in model_obj.objects.filter(device_id__in=v, status=0)]
+            if war_list:
+                warning_list.extend(war_list)
+
+        for item in result:
+            device_id = item['device_id']
+            if device_id in warning_list:
+                item['is_warning'] = True
+        warn_and_off = set(warning_list) & set(offline_list)
+        data = {
+            "statistic": statistic_list,
+            'offline': {
+                'count': len(offline_list),
+                'result': offline_list
+            },
+            "waring": {
+                'count': len(warning_list),
+                'result': warning_list
+            },
+            "warn_and_off": {
+                'count': len(warn_and_off),
+                'result': warning_list
+            },
+            "data": result
+        }
+        return Response({"code": 0, "message": "success", "data": data})

+ 57 - 378
smartfarming/views/pest_image.py

@@ -10,7 +10,7 @@ from django.utils.encoding import escape_uri_path
 from django.conf import settings
 from django.db.models import Q
 from smartfarming.models.worm_forecast import MongoCBDphoto
-from smartfarming.models.device import MongoDevice
+from smartfarming.models.device import MongoDevice, MongoXYCBData, MongoSCDData
 from smartfarming.models.weather import QXZdata_New, MongoQXZ_Conf
 from smartfarming.api.views.forecast.all_dict import insect_dict
 from kedong.decoration import kedong_deco, PortError
@@ -271,7 +271,7 @@ class QxzDataExport(ListView):
         return response
     
 
-class cbd_export(ListView):
+class CbdExport(ListView):
     """
     设备数据导出接口
     device_id      设备号(str)
@@ -281,187 +281,60 @@ class cbd_export(ListView):
     device_type    设备类型
     """
     def get(self,request):
-        print("cbd_export,日志数据导出")
         device_id = request.GET.get("device_id")
         start_time = request.GET.get("start_time")
         end_time = request.GET.get("end_time")
         filename = request.GET.get("filename")
         device_type = request.GET.get("device_type")
-        username = request.GET.get("username")
-        recent_request = REDIS.get(username)
-        table_headers = request.GET.get("table_header", "")
-        table_headers_lt = table_headers.split("|")
-        if recent_request:
-            seconds = int(time.time()) - int(recent_request)
-            data = {"code":"400","type":"{}秒后重试或等待文件下载完毕".format(60-seconds)}
-            data = json.dumps(data,ensure_ascii=False)
-            return HttpResponse(data)
-        else:
-            REDIS.setex(username,60,int(time.time()))
+        # username = request.GET.get("username")
         book = xlwt.Workbook() 
         sheet = book.add_sheet('Sheet1',cell_overwrite_ok=True) # 添加一个sheet页
         try:
-            devices = Device.objects.get(id=device_id)
+            devices = MongoDevice.objects.get(id=device_id)
         except:
             data = {"code":"401","type":"未找到该设备"}
             data = json.dumps(data,ensure_ascii=False)
             return HttpResponse(data)
-        
-        try:
-            device_user = DeviceUser.objects.get(real_name=username)
-        except:
-            data = {"code":"402","type":"未找到该用户"}
-            data = json.dumps(data,ensure_ascii=False)
-            return HttpResponse(data)
 
-        if device_type == "7":
-            models = MongoBZYData
-        elif device_type == "4":
-            models = MongoXYCBData
+        if device_type == "4":
+            models =  MongoXYCBData
         elif device_type == "2":
-            models = MongoSCDData
-        elif device_type == "3":
-            models = MongoCBDData
-        elif device_type == "14":
-            models = MongoSYCBData
-        elif device_type == "12":
-            models = MongoXCTData
-        elif device_type == "8":
-            models = MongoXYThreeData
-
+            models =  MongoSCDData
         else:
             data = {"code":"403","type":"暂不支持该设备类型"}
             data = json.dumps(data,ensure_ascii=False)
             return HttpResponse(data)
 
         if device_id:
-            # device_data = DeviceData.objects.filter(device_id=device_id)
             device_data = models.objects.filter(device_id=device_id).order_by("-id")
-            print(device_data.count())
         else:
             data = {"code":"400","type":"参数为空"}
             data = json.dumps(data,ensure_ascii=False)
             return HttpResponse(data)
-        user_type = device_user.user_type
-
-        if user_type == 1:
-            if start_time:
-                device_data = device_data.filter(addtime__range=(int(start_time), int(end_time)))
-        else:
-            if devices.device_expire == "1":
-                print("不是管理员")
-                device_data = device_data.filter(addtime__lte=int(devices.device_expire_time))
-
-                if end_time and int(end_time) > int(devices.device_expire_time):
-                    end_time = devices.device_expire_time
-                    device_data = device_data.filter(addtime__range=(int(start_time), int(end_time)))
-            else:
-                if start_time and end_time:
-                    device_data = device_data.filter(addtime__range=(int(start_time), int(end_time)))
-
-        # if not myuser_type == 1 and devices.device_expire == "1":
-        #     print("不是管理员")
-        #     device_data =  device_data.filter(addtime__lte=int(devices.device_expire_time))
-        #
-        #     if end_time and int(end_time) > int(devices.device_expire_time):
-        #             end_time = devices.device_expire_time
-        #             device_data = device_data.filter(addtime__range=(int(start_time), int(end_time)))
-        # else:
-        #
-        #
 
+        if start_time:
+            device_data = device_data.filter(addtime__range=(int(start_time), int(end_time)))
+                
         sta2 = []
         if device_data:
-            for  x in device_data:
+            for x in device_data:
                 times = time.localtime(x.addtime)
                 times = time.strftime("%Y-%m-%d %H:%M:%S",times)
-                sta2.append({"data": ast.literal_eval(x.device_data),
+                sta2.append({"data": eval(x.device_data),
                     "upl_time":times})
         else:
             sheet.write(1+1,0,"暂无数据")
-        # 测报灯
-        if device_type == "3":
-            title = ["设备ID","环境温度(℃)","环境湿度(%)","加热仓温度(℃)","雨控状态",
-                        "温控状态","光控状态","信号强度","电流mA","灯管状态", "电压V","上报时间","经度","纬度"]
-            for i in range(len(title)): # 遍历列
-                sheet.write(0,i,title[i]) # 将title数组中的字段写入到0行i列中
-            for x in range(len(sta2)): # 遍历列表
-                try:
-                    if sta2[x]["data"]["rps"] == "0":
-                        rps = "正常"
-                    else:
-                        rps = "雨控"
-                    if sta2[x]["data"]["tps"] == "0":
-                        tps = "正常"
-                    else:
-                        tps = "温控"
-                    if sta2[x]["data"]["lps"] == "0":
-                        lps = "正常"
-                    else:
-                        lps = "光控"
-                    try:
-                        lat = sta2[x]["data"]["lat"]
-                        lng = sta2[x]["data"]["lng"]
-                    except:
-                        lat = 0
-                        lng = 0
-                    try:
-                        ws = sta2[x]["data"]["ws"]
-                        if ws == "" or ws == "0":
-                            ws = True
-                        else:
-                            ws = False
-                    except:
-                        ws = False
-                    if ws:
-                        lamp = "待机"
-                    else:
-                        if sta2[x]["data"]["lamp"] == "0":
-                            lamp = "工作"
-                        else:
-                            lamp = "异常"
-
-                    sheet.write(x+1,0,devices.device_id) # 将equip_id写入到第x+1行,第0列中
-                    sheet.write(x+1,1,sta2[x]["data"]["at"])  # 环境温度
-                    sheet.write(x+1,2,sta2[x]["data"]["ah"])    # 环境湿度
-                    sheet.write(x+1,3,sta2[x]["data"]["hrt"])   # 加热仓温度
-                    sheet.write(x+1,4,rps)     # 雨控状态
-                    sheet.write(x+1,5,tps)     # 温控状态
-                    sheet.write(x+1,6,lps)     # 光控状态
-                    sheet.write(x+1,7,sta2[x]["data"]["csq"])     # 信号强度
-                    sheet.write(x+1,8,sta2[x]["data"]["current"])    # 电流
-                    sheet.write(x+1,9,lamp)    # 灯管状态
-                    sheet.write(x+1,10,sta2[x]["data"]["vbat"])    # 电压
-                    sheet.write(x+1,11,sta2[x]["upl_time"])    # 上报时间
-                    sheet.write(x+1,12,lng)    # 经度
-                    sheet.write(x+1,13,lat)    # 纬度
-                except:
-                    continue
-        # 性诱性诱测报 
-        elif device_type == "4":
-            print(f"+++++++++++++性诱测报+++++++++++++")
-            t_dict = {
-                "ds": "设备开关",
-                "ws": "工作状态",
-                "at": "环境温度(℃)",
-                "ah": "环境湿度(%)",
-                "cv": "充电电压(V)",
-                "bv": "电池电压(V)",
-                "cs": "充电状态",
-                "bs": "电池状态",
-                "infr_ct": "诱虫次数",
-                "csq": "信号强度",
-                "addtime": "上报时间"
-            }
-            title = []
-            for k in table_headers_lt:
-                title.append(t_dict.get(k))
-            title.insert(0, "设备ID")
-            # title = ["设备ID","设备开关","工作状态","环境温度(℃)","环境湿度(%)","红外计数","高压计数","充电电压(V)","电池电压(V)",
-            #             "充电状态","电池状态","信号强度","版本号","上报时间","经度","纬度"]
-            for i in range(len(title)): # 遍历列
-                sheet.write(0,i,title[i]) # 将title数组中的字段写入到0行i列中
-            for x in range(len(sta2)): # 遍历列表
+        
+        # 性诱性诱测报
+        if device_type == "4":
+            title = [
+                "设备ID", "设备开关", "工作状态", "环境温度(℃)", "环境湿度(%)",
+                "充电电压(V)", "电池电压(V)", "充电状态", "电池状态", "诱虫次数",
+                "信号强度", "上报时间"
+            ]
+            for i in range(len(title)):  # 遍历列
+                sheet.write(0, i, title[i])  # 将title数组中的字段写入到0行i列中
+            for x in range(len(sta2)):  # 遍历列表
                 try:
                     x_d = sta2[x]["data"]
                     ds = "关机" if x_d["ds"] == 0 else "开机"
@@ -518,158 +391,42 @@ class cbd_export(ListView):
                         "上报时间": sta2[x]["upl_time"]
                     }
                     for i, v in enumerate(title):
-                        sheet.write(x+1, i, table_value.get(v))
+                        sheet.write(x + 1, i, table_value.get(v))
                 except:
                     continue
         # 杀虫灯
         elif device_type == "2":
-            title = ["设备ID","设备开关","工作状态","雨控状态","温控状态","倾倒状态","电击次数","定时时长(h)",
-            "环境温度(℃)","环境湿度(%)","充电电压(V)","电池电压(V)","上报时间","经度","纬度"]
-            for i in range(len(title)): # 遍历列
-                sheet.write(0,i,title[i]) # 将title数组中的字段写入到0行i列中
-            for x in range(len(sta2)): # 遍历列表
-                print(sta2[x]["upl_time"])
+            title = ["设备ID", "设备开关", "工作状态", "雨控状态", "温控状态", "倾倒状态", "电击次数", "定时时长(h)",
+                     "环境温度(℃)", "环境湿度(%)", "充电电压(V)", "电池电压(V)","信号强度", "上报时间", "经度", "纬度"]
+            for i in range(len(title)):  # 遍历列
+                sheet.write(0, i, title[i])  # 将title数组中的字段写入到0行i列中
+            for x in range(len(sta2)):  # 遍历列表
                 try:
-                    if int(sta2[x]["data"]["ds"]) == "0":
+                    if int(sta2[x]["data"]["ds"]) == 0:
                         ds = "关机"
                     else:
                         ds = "开机"
-                    if int(sta2[x]["data"]["ws"]) == "0":
+                    if int(sta2[x]["data"]["ws"]) == 0:
                         ws = "待机"
-                    elif int(sta2[x]["data"]["ws"]) == "2":
+                    elif int(sta2[x]["data"]["ws"]) == 2:
                         ws = "充电"
                     else:
                         ws = "工作"
 
-                    if int(sta2[x]["data"]["rps"]) == "0":
+                    if int(sta2[x]["data"]["rps"]) == 0:
                         rps = "正常"
                     else:
                         rps = "雨控"
 
-                    if int(sta2[x]["data"]["tps"]) == "0":
+                    if int(sta2[x]["data"]["tps"]) == 0:
                         tps = "正常"
                     else:
                         tps = "温控"
-                    
-                    if int(sta2[x]["data"]["dps"]) == "0":
+
+                    if int(sta2[x]["data"]["dps"]) == 0:
                         dps = "正常"
                     else:
                         dps = "保护"
-                    
-                    try:
-                        lat = sta2[x]["data"]["lat"]
-                        lng = sta2[x]["data"]["lng"]
-                    except:
-                        lat = 0
-                        lng = 0
-                    sheet.write(x+1,0,devices.device_id) # 将equip_id写入到第x+1行,第0列中
-                    sheet.write(x+1,1,ds)  # 设备开关
-                    sheet.write(x+1,2,ws)  # 工作状态
-                    # sheet.write(x+1,3,tbs)  # 灯管状态
-                    sheet.write(x+1,3,rps)  # 雨控状态
-                    sheet.write(x+1,4,tps)  # 温控状态
-                    sheet.write(x+1,5,dps)  # 倾倒状态
-                    sheet.write(x+1,6,sta2[x]["data"]["ct"])  # 电击次数
-                    sheet.write(x+1,7,sta2[x]["data"]["tt"])  # 定时时长
-                    sheet.write(x+1,8,sta2[x]["data"]["at"])  # 环境温度
-                    sheet.write(x+1,9,sta2[x]["data"]["ah"])    # 环境湿度
-                    sheet.write(x+1,10,sta2[x]["data"]["cv"])    # 充电电压
-                    sheet.write(x+1,11,sta2[x]["data"]["bv"])    # 电池电压
-                    sheet.write(x+1,12,sta2[x]["upl_time"])    # 上报时间
-                    sheet.write(x+1,13,lng)    # 经度
-                    sheet.write(x+1,14,lat)    # 纬度
-                except:
-                    continue
-        # 孢子仪
-        elif device_type == "7":
-            title = ["设备ID","保温仓设定温度(℃)","保温仓当前温度(℃)","电池状态","雨控状态","摄像头状态", "电压(V)","信号强度",
-                     "环境温度(℃)","环境湿度(%)","设备版本","上报时间","经度","纬度"]
-            for i in range(len(title)): # 遍历列
-                sheet.write(0,i,title[i]) # 将title数组中的字段写入到0行i列中
-            for x in range(len(sta2)): # 遍历列表
-                try:
-
-                    if sta2[x]["data"]["batStatus"] == "0":
-                        bat_sta = "正常"
-                    else:
-                        bat_sta = "电量过低"
-
-                    if sta2[x]["data"]["rps"] == "0":
-                        rps = "正常"
-                    else:
-                        rps = "雨控"
-
-                    if sta2[x]["data"]["usb_sta"] == "0":
-                        usb_sta = "正常"
-                    else:
-                        usb_sta = "异常"
-                    try:
-                        lat = sta2[x]["data"]["lat"]
-                        lng = sta2[x]["data"]["lng"]
-                    except:
-                        lat = 0
-                        lng = 0
-                except:
-                    continue
-                sheet.write(x+1,0,devices.device_id) # 将equip_id写入到第x+1行,第0列中
-                sheet.write(x+1,1,sta2[x]["data"]["set_temp"])  # 保温仓设定温度
-                sheet.write(x+1,2,sta2[x]["data"]["pre_temp"])  # 保温仓当前温度
-                sheet.write(x+1,3,bat_sta)  # 电池状态
-                sheet.write(x+1,4,rps)  # 雨控状态
-                sheet.write(x+1,5,usb_sta)  # 摄像头状态
-                sheet.write(x+1,6,sta2[x]["data"]["vbat"])  # 电压
-                # sheet.write(x+1,8,sta2[x]["data"]["alti"])  # 海拔高度
-                sheet.write(x+1,7,sta2[x]["data"]["csq"])  # 信号强度
-                sheet.write(x+1,8,sta2[x]["data"]["at"])  # 环境温度
-                sheet.write(x+1,9,sta2[x]["data"]["ah"])    # 环境湿度
-                sheet.write(x+1,10,sta2[x]["data"]["dver"])    # 设备版本
-                sheet.write(x+1,11,sta2[x]["upl_time"])    # 上报时间
-                sheet.write(x+1,12,lng)    # 经度
-                sheet.write(x+1,13,lat)    # 纬度
-        # 色诱
-        elif device_type == "14":
-            title = ["设备ID", "上报时间", "开机状态", "空气温度", "空气湿度"]
-            for i in range(len(title)): # 遍历列
-                sheet.write(0,i,title[i]) # 将title数组中的字段写入到0行i列中
-            for x in range(len(sta2)): # 遍历列表
-                if int(sta2[x]["data"]["ds"]) == 0:
-                    ds = "关机"
-                else:
-                    ds = "开机"
-
-                try:
-                    at = str(int(sta2[x]["data"]["at"])/10)
-                    ah = str(int(sta2[x]["data"]["ah"])/10)
-                except:
-                    at = sta2[x]["data"]["at"]
-                    ah = sta2[x]["data"]["ah"]
-
-                sheet.write(x + 1, 0, devices.device_id)  # 将equip_id写入到第x+1行,第0列中
-                sheet.write(x + 1, 1, sta2[x]["upl_time"])  # 上报时间
-                sheet.write(x + 1, 2, ds)  # 开机状态
-                sheet.write(x + 1, 3, at)  # 空气温度
-                sheet.write(x + 1, 4, ah)  # 空气湿度
-        # 吸虫塔
-        elif device_type == "12":
-            title = ["设备ID","设备开关","SIM卡号","工作状态","环境温度(℃)","环境湿度(%)",
-                        "震动开关","信号强度","上报时间","经度","纬度"]
-            for i in range(len(title)): # 遍历列
-                sheet.write(0,i,title[i]) # 将title数组中的字段写入到0行i列中
-            for x in range(len(sta2)): # 遍历列表
-                try:
-                    if sta2[x]["data"]["ds"] == "0":
-                        ds = "关机"
-                    else:
-                        ds = "开机"
-
-                    if sta2[x]["data"]["ws"] == "0":
-                        ws = "待机"
-                    else:
-                        ws = "工作"
-                    if sta2[x]["data"]["shake"] == "0":
-                        shake = "关"
-                    else:
-                        shake = "开"
 
                     try:
                         lat = sta2[x]["data"]["lat"]
@@ -677,107 +434,30 @@ class cbd_export(ListView):
                     except:
                         lat = 0
                         lng = 0
-
-                    sheet.write(x+1,0,devices.device_id) # 将equip_id写入到第x+1行,第0列中
-                    sheet.write(x+1,1,ds)     # 设备开关:
-                    sheet.write(x+1,2,sta2[x]["data"]["iccid"])   # iccid
-                    sheet.write(x+1,3,ws)     # 工作状态
-                    sheet.write(x+1,4,sta2[x]["data"]["at"])  # 环境温度
-                    sheet.write(x+1,5,sta2[x]["data"]["ah"])    # 环境湿度
-                    sheet.write(x+1,6,shake)     # 震动开关:
-                    sheet.write(x+1,7,sta2[x]["data"]["csq"])     # 信号强度
-                    sheet.write(x+1,8,sta2[x]["upl_time"])    # 上报时间
-                    sheet.write(x+1,9,lng)    # 经度
-                    sheet.write(x+1,10,lat)    # 纬度
+                    sheet.write(x + 1, 0, devices.device_id)  # 将equip_id写入到第x+1行,第0列中
+                    sheet.write(x + 1, 1, ds)  # 设备开关
+                    sheet.write(x + 1, 2, ws)  # 工作状态
+                    sheet.write(x + 1, 3, rps)  # 雨控状态
+                    sheet.write(x + 1, 4, tps)  # 温控状态
+                    sheet.write(x + 1, 5, dps)  # 倾倒状态
+                    sheet.write(x + 1, 6, sta2[x]["data"]["ct"])  # 电击次数
+                    sheet.write(x + 1, 7, sta2[x]["data"]["tt"])  # 定时时长
+                    sheet.write(x + 1, 8, sta2[x]["data"]["at"])  # 环境温度
+                    sheet.write(x + 1, 9, sta2[x]["data"]["ah"])  # 环境湿度
+                    sheet.write(x + 1, 10, sta2[x]["data"]["cv"])  # 充电电压
+                    sheet.write(x + 1, 11, sta2[x]["data"]["bv"])  # 电池电压
+                    sheet.write(x + 1, 12, sta2[x]["data"]["csq"])  # 信号强度
+                    sheet.write(x + 1, 13, sta2[x]["upl_time"])  # 上报时间
+                    sheet.write(x + 1, 14, lng)  # 经度
+                    sheet.write(x + 1, 15, lat)  # 纬度
                 except:
                     continue
-        # 性诱3.0
-        elif device_type == "8":
-            print(f"---------------性诱3.0--------------")
-            t_dict = {
-                "ds": "设备开关",
-                "ws": "工作状态",
-                "at": "环境温度(℃)",
-                "ah": "环境湿度(%)",
-                "cc": "电流(mA)",
-                "cv": "充电电压(V)",
-                "bv": "电池电压(V)",
-                "bs": "电池状态",
-                "volt_ct": "诱虫次数",
-                "csq": "信号强度",
-                "addtime": "上报时间"
-            }
-            title = []
-            for k in table_headers_lt:
-                title.append(t_dict.get(k))
-            title.insert(0, "设备ID")
-            for i in range(len(title)): # 遍历列
-                sheet.write(0,i,title[i]) # 将title数组中的字段写入到0行i列中
-            for x in range(len(sta2)): # 遍历列表
-                try:
-                    if sta2[x]["data"]["ds"] == "0":
-                        ds = "关机"
-                    else:
-                        ds = "开机"
-                    if sta2[x]["data"]["ws"] == "0":
-                        ws = "待机"
-                    else:
-                        ws = "工作"
-                    try:
-                        at = sta2[x]["data"]["at"]
-                    except Exception as e:
-                        at = "0"
-                    try:
-                        ah = sta2[x]["data"]["ah"]
-                    except Exception as e:
-                        ah = "0"
-                    if sta2[x]["data"]["bs"] == "0":
-                        bs = "正常"
-                    elif sta2[x]["data"]["bs"] == "1":
-                        bs = "欠压"
-                    else:
-                        bs = "过压"
-
-                    try:
-                        lat = sta2[x]["data"]["lat"]
-                        lng = sta2[x]["data"]["lng"]
-                    except:
-                        lat = 0
-                        lng = 0
-                    table_value = {
-                        "设备ID": devices.device_id,
-                        "设备开关": ds,
-                        "工作状态": ws,
-                        "环境温度(℃)": at,
-                        "环境湿度(%)": ah,
-                        "电流(mA)": sta2[x]["data"]["cc"],
-                        "充电电压(V)": sta2[x]["data"]["cv"],
-                        "电池电压(V)": sta2[x]["data"].get("bv", "0"),
-                        "电池状态": "正常" if sta2[x]["data"].get("bs", "1") == "0" else "非正常",
-                        "诱虫次数": sta2[x]["data"]["volt_ct"],
-                        "信号强度": sta2[x]["data"]["csq"],
-                        "上报时间": sta2[x]["upl_time"]
-                    }
-                    for i, v in enumerate(title):
-                        sheet.write(x+1, i, table_value.get(v))
-                except Exception as e:
-                    print(e)
-                    continue
-            
-        else:
-            data = {"code":"400","type":"参数为空"}
-            data = json.dumps(data,ensure_ascii=False)
-            return HttpResponse(data)
         sheet.col(0).width = 256 * 18
-        sheet.col(1).width = 256 * 15
-        sheet.col(2).width = 256 * 15
-        sheet.col(3).width = 256 * 15
-        sheet.col(4).width = 256 * 15
-        sheet.col(5).width = 256 * 15
-        sheet.col(6).width = 256 * 15
-        sheet.col(7).width = 256 * 15
-        sheet.col(8).width = 256 * 15
-        sheet.col(9).width = 256 * 15
+        sheet.col(2).width = 256 * 11
+        sheet.col(3).width = 256 * 11
+        sheet.col(4).width = 256 * 13
+        sheet.col(8).width = 256 * 11
+        sheet.col(9).width = 256 * 11
         sheet.col(10).width = 256 * 20
         # 写出到IO
         output = BytesIO()
@@ -787,5 +467,4 @@ class cbd_export(ListView):
         response = HttpResponse(content_type='application/vnd.ms-excel')
         response['Content-Disposition'] = 'attachment;filename={}.xls'.format(escape_uri_path(filename))
         response.write(output.getvalue())
-        REDIS.delete(username)
         return response

+ 17 - 0
smartfarming/views/user.py

@@ -86,6 +86,23 @@ class RoleUpdateAPIView(APIView):
             return Response({"code": 0, "msg": "success"})
         except Exception as e:
             return Response({"code": 2, "msg": "更新角色失败"})
+        
+
+class APPUserLogin(APIView):
+    permission_classes = []
+    authentication_classes = []
+
+    def post(self, request, format=None):
+        # 用户登录
+        request_data = request.data 
+        username = request_data.get("username")
+        password = request_data.get("password")
+        user = authenticate(username=username, password=password)
+        if user:
+            return Response({"msg": "success", "code": 0})
+        else:
+            return Response({"msg": "success", "code": 2})
+
 
 
 class LoginAPIView(APIView):