Jelajahi Sumber

获取设备地区天气

peng 2 tahun lalu
induk
melakukan
41b89d2cb6
5 mengubah file dengan 149 tambahan dan 4 penghapusan
  1. 3 1
      Ansjer/urls.py
  2. 22 3
      Controller/ShadowController.py
  3. 59 0
      Controller/WeatherControl.py
  4. 14 0
      Model/models.py
  5. 51 0
      Object/IPWeatherObject.py

+ 3 - 1
Ansjer/urls.py

@@ -22,7 +22,8 @@ from Controller import FeedBack, EquipmentOTA, EquipmentInfo, AdminManage, AppIn
     OrderTaskController, HistoryUIDController, UIDManageUserController, SerialNumberController, CompanyController, \
     RegionController, VPGController, LanguageController, TestController, DeviceConfirmRegion, S3GetStsController, \
     DetectControllerV2, PcInfo, PctestController, DeviceDebug, PaymentCycle, \
-    DeviceLogController, CouponController, AiController, ShadowController, AppAccountManagement, InitController
+    DeviceLogController, CouponController, AiController, ShadowController, AppAccountManagement, InitController, \
+    WeatherControl
 from Controller.Cron import CronTaskController
 from Controller.MessagePush import EquipmentMessagePush
 from Controller.Surveys import CloudStorageController
@@ -365,6 +366,7 @@ urlpatterns = [
 
     # 传感器网关
     re_path('sensorGateway/(?P<operation>.*)', SensorGatewayController.SensorGateway.as_view()),
+    re_path(r'^weather/(?P<operation>.*)$', WeatherControl.WeatherView.as_view()),
 
     # 后台界面接口 -----------------------------------------------------
     # 用户登录信息等

+ 22 - 3
Controller/ShadowController.py

@@ -5,9 +5,10 @@ from django.http import JsonResponse
 
 from Ansjer.config import SERVER_TYPE, LOGGER
 from Model.models import Device_Info, UidSetModel, UID_Preview, VoicePromptModel, UID_Bucket, UidChannelSetModel, \
-    AiService, CountryModel
+    AiService, CountryModel, CityInformation
 from Object.ETkObject import ETkObject
 from Service.CommonService import CommonService
+from Object.IPWeatherObject import IPQuery
 
 
 # 更新设备影子
@@ -31,9 +32,10 @@ def update_device_shadow(request):
                                                   'data': {}})
 
         nowTime = int(time.time())
-
+        ip = CommonService.get_ip_address(request)
         # 重置按钮
         is_reset = request_dict.get('is_reset', None)
+
         # 传1则重置设备信息
         if is_reset == '1':
             LOGGER.info('设备重置: {}'.format(uid))
@@ -69,12 +71,22 @@ def update_device_shadow(request):
             AiService.objects.filter(uid=uid, use_status=1).update(detect_status=0, detect_group='')
             LOGGER.info('{}重置成功'.format(uid))
 
+            # ip变化更新tb_city_information_id
+            uid_set_qs = UidSetModel.objects.filter(uid=uid).values('ip')
+            if uid_set_qs.exists():
+                if ip != uid_set_qs[0]['ip']:
+                    ip_qs = IPQuery(ip)
+                    district = ip_qs.district
+                    city_information_qs = CityInformation.objects.filter(district=district).values('city_id')
+                    if city_information_qs.exists():
+                        city_id = city_information_qs[0]['city_id']
+                        uid_set_qs.updete(tb_city_information_id=city_id)
+
         ucode = request_dict.get('ucode', None)
         version = request_dict.get('version', None)
         p2p_region = request_dict.get('p2p_region', None)
         tz = request_dict.get('tz', None)
         video_code = request_dict.get('video_code', None)
-        ip = CommonService.get_ip_address(request)
         channel = request_dict.get('channel', None)
         cloud_vod = request_dict.get('cloud_vod', None)
         push_status = request_dict.get('push_status', None)
@@ -136,6 +148,13 @@ def update_device_shadow(request):
             qs_dict['tb_country'] = country
         LOGGER.info('{} qs_dict: {}'.format(uid, qs_dict))
 
+        ip_qs = IPQuery(ip)
+        district = ip_qs.district
+        city_information_qs = CityInformation.objects.filter(district=district).values('city_id')
+        if city_information_qs.exists():
+            city_id = city_information_qs[0]['city_id']
+            qs_dict['tb_city_information_id'] = city_id
+
         us_qs = UidSetModel.objects.filter(uid=uid)
         if us_qs.exists():
             if is_alexa and us_qs[0].is_alexa == 0:

+ 59 - 0
Controller/WeatherControl.py

@@ -0,0 +1,59 @@
+# -*- coding: utf-8 -*-
+"""
+@Author : peng
+@Time : 2023-8-18 10:45:46
+@File :WeatherControl.py
+"""
+from Ansjer.config import LOGGER
+import time
+
+from django.views import View
+from Object.IPWeatherObject import WeatherInfo
+from Model.models import UidSetModel, CityInformation
+from Object.ResponseObject import ResponseObject
+
+
+class WeatherView(View):
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation')
+        return self.validation(request.GET, operation, request)
+
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation')
+        return self.validation(request.POST, operation, request)
+
+    def validation(self, request_dict, operation, request):
+        lang = request_dict.get('lang', 'en')
+        response = ResponseObject(lang)
+        if operation == 'get':  # 获取天气
+            return self.get_weather(request_dict, response)
+        else:
+            return response.json(414)
+
+    @staticmethod
+    def get_weather(request_dict, response):
+        """
+        获取天气
+        @param request_dict: 请求参数
+        @request_dict uid: 设备uid
+        @param response: 响应对象
+        @return: response
+        """
+        uid = request_dict.get('uid')
+        if not uid:
+            return response.json(444, 'uid')
+        uid_set_qs = UidSetModel.objects.filter(uid=uid).values('tb_city_information_id')
+        if not uid_set_qs.exists():
+            return response.json(173)
+        try:
+            city_obj = WeatherInfo(uid_set_qs[0]['tb_city_information_id'])
+            temp, humidity = city_obj.get_city_weather()
+            if not all([temp, humidity]):
+                return response.json(10, '获取天气失败')
+            return response.json(0, {'temp': temp, 'humidity': humidity})
+        except Exception as e:
+            print(e)
+            return response.json(500)
+

+ 14 - 0
Model/models.py

@@ -1381,6 +1381,7 @@ class UidSetModel(models.Model):
     is_notification = models.IntegerField(blank=True, default=1, verbose_name='新加-消息提醒开关')  # 0:关闭,1:开启
     new_detect_interval = models.IntegerField(blank=True, verbose_name='新加-消息提醒间隔', default=60)  # 秒
     tb_country = models.IntegerField(blank=True, default=0, verbose_name='国家')
+    tb_city_information_id = models.IntegerField(blank=True, default=0, verbose_name='城市信息')
     device_type = models.SmallIntegerField(default=0, verbose_name='设备类型')
     ai_type = models.SmallIntegerField(default=0, verbose_name='检测类型')
 
@@ -3571,3 +3572,16 @@ class IotCardUsageHistory(models.Model):
         db_table = 'iot_card_usage_history'
         verbose_name = '物联网卡用量历史'
         verbose_name_plural = verbose_name
+
+
+class CityInformation(models.Model):
+    id = models.AutoField(primary_key=True, verbose_name='自增id')
+    city_id = models.IntegerField(default=0, verbose_name='城市id')
+    district = models.CharField(default='', max_length=32, verbose_name='区级名称')
+    city = models.CharField(default='', max_length=32, verbose_name='市级名称')
+    region = models.CharField(default='', max_length=30, verbose_name='省级名称')
+
+    class Meta:
+        db_table = 'city_information'
+        verbose_name = '城市信息'
+        verbose_name_plural = verbose_name

+ 51 - 0
Object/IPWeatherObject.py

@@ -0,0 +1,51 @@
+# @Author    : Rocky
+# @File      : IPWeatherObject.py
+# @Time      : 2023/8/16 8:56
+import requests
+
+
+class IPQuery:
+    """
+    阿里云IP地址查询
+    https://market.aliyun.com/products/57002003/cmapi021970.html?spm=5176.2020520132.recommend-card.dbottom-suggestion.33e17218GYjWDt#sku=yuncode15970000020
+    """
+
+    def __init__(self, ip):
+        self.appcode = 'd7d63b34b1d54214be446608a57ff0a2'
+        self.host = 'https://c2ba.api.huachen.cn'
+        self.path = '/ip'
+
+        self.district = None
+
+        param = 'ip=' + ip
+        url = self.host + self.path + '?' + param
+
+        # 获取ip的区级和城市信息
+        headers = {'Authorization': 'APPCODE ' + self.appcode}
+        res = requests.get(url=url, headers=headers)
+        if res.status_code == 200:
+            # 反序列化响应数据
+            res_data = eval(res.content.decode('utf-8'))
+            if res_data['ret'] == 200:
+                district = res_data['data']['district']
+                city = res_data['data']['city'] + '市'
+                self.district = district if district else city
+
+
+class WeatherInfo:
+    def __init__(self, city_id):
+        self.appcode = 'd7d63b34b1d54214be446608a57ff0a2'
+        self.headers = {'Authorization': 'APPCODE ' + self.appcode,
+                        'Content-Type': 'application/x-www-form-urlencoded'}
+        self.city_id = city_id
+
+    def get_city_weather(self):
+        url = "https://aliv18.data.moji.com/whapi/json/alicityweather/condition"  # 获取实时天气
+        data = {'cityId': self.city_id}
+        response = requests.post(url, headers=self.headers, data=data, verify=False)
+        if response.status_code == 200:
+            result = response.json()
+            if result['code'] == 0:
+                # 返回温湿度
+                return result['data']['condition']['temp'], result['data']['condition']['humidity']
+        return None, None