Ver Fonte

对接联通IoT新平台

zhangdongming há 2 anos atrás
pai
commit
ed07266d1e

+ 8 - 6
Ansjer/config.py

@@ -455,11 +455,11 @@ APP_TYPE = {
 
 # 联通Unicom config
 # 应用地址,请向开发人员索取
-unicomAppUrl = 'https://chinaunicom-iot.unimip.cn'
+unicomAppUrl = 'https://iot-cop.unimip.cn'
 # 应用id,请向开发人员创建应用,分配appId
-unicomAppId = 'LNO7ojB7mZU5ep9IuiHvygVWbwaO9vt0'
+unicomAppId = 'gyAkIBgnqlUrTNJfvcj7vA0XRIOFyh3U'
 # 应用密匙,请向开发人员创建应用,分配appSecret
-unicomAppSecret = 'p8MT1CS4QAVl0xb4cp7VOCgMvtQp2O43'
+unicomAppSecret = 'D6u6ROqceuCaYujMjBSIXDHXRZQGtaS3'
 # 租户/产品ID,请向开发人员索取
 unicomTenantId = '1469181295663300608'
 # 密码加密密匙,请向开发人员索取
@@ -467,11 +467,13 @@ unicomEncodeKey = 'uBdUx82vPHkDKb284d7NkjFoNcKWBuka'
 # 密码加密参数,请向开发人员索取
 unicomIvKey = 'oCRU0D1wKfBlNeTz'
 # 用户名,如无请联系客户经理开通
-unicomUserName = 'zh-zhasjdz'
+unicomUserName = 'zhasj_admin'
 # 登录密码,如无请联系客户经理
-unicomPassword = 'XoROL1vCl5@_'
+unicomPassword = 'Ansjer2023..'
 # 回调签名验证加密密匙,请向开发人员索取
-unicomPushKey = 'NVVDQMBSOJTXA'
+unicomPushKey = 'N5SGE4LVOR2GG'
+# token key
+UNICOM_KEY = 'ASJ:UNICOM:API:TOKEN'
 
 # 五兴域名
 WX_TECH_URL = 'http://www.wxkjwlw.com'

+ 1 - 1
Controller/UnicomCombo/UnicomComboController.py

@@ -130,7 +130,7 @@ class UnicomComboView(View):
                     'month': combo_order['month'],
                 }
                 activate_flow = float(flow_details['flowTotalUsage'])
-                flow_total_usage = unicom_api.get_flow_usage_total(iccid)
+                flow_total_usage = float(unicom_api.get_flow_usage_total(iccid))
                 flow = 0 if flow_total_usage <= 0 else flow_total_usage - activate_flow
                 # 因APP问题,usableFlow可用流量替换为,已用流量值
                 flow_details['usableFlow'] = 0 if flow == 0 else flow

+ 1 - 0
Controller/UnicomCombo/UnicomComboTaskController.py

@@ -136,6 +136,7 @@ class UnicomComboTaskView(View):
                 flow_total = combo_qs['flow_total']
                 # 队列已使用总流量总量
                 flow_total_usage = unicom_api.get_flow_usage_total(iccid)
+                flow_total_usage = float(flow_total_usage)
                 is_expire = False
                 flow = activate_usage_flow + flow_total
                 if flow_total_usage > 0:

+ 68 - 28
Object/UnicomObject.py

@@ -9,12 +9,15 @@
 import base64
 import json
 import logging
+import time
+from decimal import Decimal
 
 import requests
 from Crypto.Cipher import AES
 
 from Ansjer.config import unicomAppUrl, unicomAppId, unicomAppSecret, unicomTenantId, \
-    unicomEncodeKey, unicomIvKey, unicomUserName, unicomPassword, unicomPushKey, SERVER_DOMAIN_SSL
+    unicomEncodeKey, unicomIvKey, unicomUserName, unicomPassword, unicomPushKey, SERVER_DOMAIN_SSL, UNICOM_KEY
+from Model.models import UnicomDeviceInfo
 from Object.RedisObject import RedisObject
 from Object.utils import SM3Util
 from Object.utils.SymmetricCryptoUtil import AESencrypt
@@ -87,7 +90,7 @@ class UnicomObjeect:
 
     def get_encode_password(self):
         """
-        获取对称加密
+        获取对称加密AES
         @return: encrypt_pwd
         """
         aes = AESencrypt(self.encodeKey.encode('utf-8'), AES.MODE_CBC, self.ivKey.encode('utf-8'),
@@ -101,6 +104,10 @@ class UnicomObjeect:
         生成令牌
         @return: token
         """
+        redis = RedisObject()
+        token = redis.get_data(UNICOM_KEY)
+        if token:
+            return token
         url = self.appUrl + '/auc/oauth/token'
         pwd = self.get_encode_password()
         body = {'username': self.username, 'password': pwd, 'grant_type': 'password', 'scope': 'server'}
@@ -108,7 +115,10 @@ class UnicomObjeect:
         headers['Authorization'] = self.get_login_authorization()
         response_data = requests.post(url, data=body, headers=headers)
         response_data = json.loads(response_data.text)
-        return response_data['access_token']
+        token = response_data['access_token']
+        expires_in = response_data['expires_in']
+        redis.set_data(UNICOM_KEY, token, int(expires_in))
+        return token
 
     def refresh_token(self, refresh_token):
         """
@@ -141,7 +151,8 @@ class UnicomObjeect:
         @param re_params:
         @return:
         """
-        url = self.appUrl + '/platform/api/device/verify-device'
+        re_params['appId'] = self.appId
+        url = self.appUrl + '/cop-platform/api/device/verify-device'
         return requests.get(url, params=re_params, headers=self.business_unify_headers())
 
     def query_device_status(self, **re_params):
@@ -150,8 +161,11 @@ class UnicomObjeect:
         @param re_params:
         @return:
         """
-        url = self.appUrl + '/platform/api/device/device-status'
-        return requests.get(url, params=re_params, headers=self.business_unify_headers())
+        url = self.appUrl + '/cop-platform/api/device/detail'
+        re_params['appId'] = self.appId
+        headers = self.business_unify_headers()
+        headers['content-type'] = 'application/json'
+        return requests.get(url, params=re_params, headers=headers)
 
     def update_device_state(self, **re_data):
         """
@@ -159,9 +173,10 @@ class UnicomObjeect:
         @param re_data:
         @return:
         """
-        url = self.appUrl + '/platform/api/device/async-device-state'
+        url = self.appUrl + '/cop-platform/api/device/async-device-state'
         headers = self.business_unify_headers()
         headers['content-type'] = 'application/json'
+        re_data['appId'] = self.appId
         re_data['callbackUrl'] = SERVER_DOMAIN_SSL + 'unicom/api/device-status-change'
         return requests.post(url, data=json.dumps(re_data), headers=headers)
 
@@ -171,8 +186,10 @@ class UnicomObjeect:
         @param re_params:
         @return:
         """
-        url = self.appUrl + '/platform/api/usage/device-usage-history'
-        return requests.get(url, params=re_params, headers=self.business_unify_headers())
+        headers = self.business_unify_headers()
+        re_params['appId'] = self.appId
+        url = self.appUrl + '/cop-platform/api/usage/device-usage-history'
+        return requests.get(url, params=re_params, headers=headers)
 
     def query_current_renew_list_usage_details(self, **re_params):
         """
@@ -180,7 +197,8 @@ class UnicomObjeect:
         @param re_params:
         @return:
         """
-        url = self.appUrl + '/platform/api/usage/current-renewlist-usage-details'
+        url = self.appUrl + '/cop-platform/api/device/current-package-usage-details'
+        re_params['appId'] = self.appId
         return requests.get(url, params=re_params, headers=self.business_unify_headers())
 
     def get_device_batch_detail(self, **re_data):
@@ -241,14 +259,43 @@ class UnicomObjeect:
         @return: 返回结果dict
         """
         redis = RedisObject()
-        flow_usage_details = redis.get_data(key)
-        if flow_usage_details:
-            flow_usage_details = json.loads(flow_usage_details)
+        sim_flow_used_total = redis.get_data(key)
+        if sim_flow_used_total:
+            return Decimal(sim_flow_used_total).quantize(Decimal('0.00'))
         else:
-            flow_usage_details = UnicomObjeect().query_current_renew_list_usage_details(**usage_data)
+            # API查询设备信息其中包含周期流量使用
+            flow_usage_details = UnicomObjeect().query_device_status(**usage_data)
             flow_usage_details = UnicomObjeect().get_text_dict(flow_usage_details)
-            redis.set_data(key=key, val=json.dumps(flow_usage_details), expire=expire)
-        return flow_usage_details
+            if flow_usage_details and flow_usage_details.get('success'):
+                cycle_total = flow_usage_details['data'].get('simCycleUsedFlow', 0)
+            else:
+                cycle_total = 0
+            # 查询SIM卡信息
+            sim_qs = UnicomDeviceInfo.objects.filter(iccid=usage_data['iccid'])
+            if not sim_qs:
+                return cycle_total
+            cycle_total = Decimal(cycle_total).quantize(Decimal('0.00'))
+            sim_vo = sim_qs.first()
+            n_time = int(time.time())
+
+            # 判断数据库周期流量用量 是否大于API查询出来的周期用量 如果是则判定进入了下一个周期
+            if sim_vo.sim_cycle_used_flow != 0 and sim_vo.sim_cycle_used_flow > cycle_total:
+                sim_used_flow = sim_vo.sim_used_flow + sim_vo.sim_cycle_used_flow
+                sim_qs.update(
+                    sim_used_flow=sim_used_flow,
+                    sim_cycle_used_flow=cycle_total,
+                    updated_time=n_time
+                )
+                # 队列用量历史总量 + 上一个周期流量 + 当前周期流量 = 总消耗流量
+                sim_flow_used_total = sim_used_flow + cycle_total
+            elif cycle_total > sim_vo.sim_cycle_used_flow:  # API周期用量大于当前数据库用量则更新记录
+                sim_qs.update(sim_cycle_used_flow=cycle_total, updated_time=n_time)
+                # 队列用量历史总量 + 当前周期流量 = 总消耗流量
+                sim_flow_used_total = sim_vo.sim_used_flow + cycle_total
+            else:
+                sim_flow_used_total = sim_vo.sim_used_flow + sim_vo.sim_cycle_used_flow
+            redis.set_data(key=key, val=str(sim_flow_used_total), expire=expire)
+        return sim_flow_used_total
 
     @staticmethod
     def get_flow_usage_total(iccid):
@@ -258,14 +305,9 @@ class UnicomObjeect:
         @return: flow_total_usage 当前套餐总已使用流量
         """
         flow_key = 'ASJ:UNICOM:FLOW:{}'
-        usage_data = {'iccid': iccid, 'realTime': True}
+        usage_data = {'iccid': iccid}
         expire_time = 60 * 10 + 60
-        flow_usage_details = UnicomObjeect().get_flow_total_usage(flow_key.format(iccid), expire_time, **usage_data)
-        # 当月实际总使用流量
-        flow_total_usage = 0
-        if flow_usage_details and flow_usage_details['success']:
-            flow_total_usage = flow_usage_details['data']['flowTotalUsage']
-        return flow_total_usage
+        return UnicomObjeect().get_flow_total_usage(flow_key.format(iccid), expire_time, **usage_data)
 
     @staticmethod
     def change_device_to_activate(iccid):
@@ -278,7 +320,7 @@ class UnicomObjeect:
             re_data = {'iccid': iccid}
             result = UnicomObjeect().query_device_status(**re_data)
             res_dict = UnicomObjeect().get_text_dict(result)
-            # 状态不等于1(激活)时进行激活 1:激活;2:停用
+            # 状态不等于1(激活)时进行激活 1:激活;3:停用
             if res_dict['data']['status'] != 1:
                 re_data = {"iccid": iccid, "status": 1}
                 UnicomObjeect().update_device_state(**re_data)
@@ -293,7 +335,7 @@ class UnicomObjeect:
         @return:
         """
         if iccid:
-            re_data = {"iccid": iccid, "status": 2}
+            re_data = {"iccid": iccid, "status": 3}
             response = UnicomObjeect().update_device_state(**re_data)
             logger.info('停用iccid响应结果:{}'.format(response.text))
             # 查询是否停用成功
@@ -302,7 +344,7 @@ class UnicomObjeect:
             res_dict = UnicomObjeect().get_text_dict(result)
             logger.info('查询iccid状态:{}'.format(res_dict))
             if res_dict['data']['status'] != 3:
-                re_data['status'] = 2
+                re_data['status'] = 3
                 response = UnicomObjeect().update_device_state(**re_data)
                 logger.info('再次停卡:{}'.format(response.text))
             return True
@@ -328,5 +370,3 @@ class UnicomObjeect:
                 return 0
             traffic_dict = json.loads(traffic_val)
         return traffic_dict['data']['flowTotalUsage']
-
-