CommonService.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. # -*- coding: utf-8 -*-
  2. # 高复用性函数封装到CommonService类
  3. import base64
  4. import datetime
  5. import time
  6. from base64 import encodebytes
  7. from pathlib import Path
  8. from random import Random
  9. import OpenSSL.crypto as ct
  10. import ipdb
  11. import requests
  12. import simplejson as json
  13. from django.core import serializers
  14. from django.utils import timezone
  15. from pyipip import IPIPDatabase
  16. from Ansjer.config import BASE_DIR, SERVER_DOMAIN_SSL, CONFIG_INFO, CONFIG_TEST, CONFIG_CN
  17. from Controller.CheckUserData import RandomStr
  18. from Model.models import iotdeviceInfoModel, Device_Info, CountryModel, RegionModel
  19. class CommonService:
  20. # 添加模糊搜索
  21. @staticmethod
  22. def get_kwargs(data=None):
  23. if data is None:
  24. data = {}
  25. kwargs = {}
  26. for (k, v) in data.items():
  27. if v is not None and v != u'':
  28. kwargs[k + '__icontains'] = v
  29. return kwargs
  30. # 定义静态方法
  31. # 格式化query_set转dict
  32. @staticmethod
  33. def qs_to_dict(query_set):
  34. sqlJSON = serializers.serialize('json', query_set)
  35. sqlList = json.loads(sqlJSON)
  36. sqlDict = dict(zip(["datas"], [sqlList]))
  37. return sqlDict
  38. # 格式化query_set转dict
  39. @staticmethod
  40. def request_dict_to_dict(request_dict):
  41. # 传参格式转换,键包含meta获取meta[]中的值,值'true'/'false'转为True,False
  42. key_list = []
  43. value_list = []
  44. for k, v in request_dict.items():
  45. key_list.append(k[k.index('[') + 1:k.index(']')] if 'meta' in k else k)
  46. if v == 'true':
  47. v = True
  48. elif v == 'false':
  49. v = False
  50. value_list.append(v)
  51. data_dict = dict(zip(key_list, value_list))
  52. print(data_dict)
  53. return data_dict
  54. # 获取文件大小
  55. @staticmethod
  56. def get_file_size(file_path='', suffix_type='', decimal_point=0):
  57. # for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
  58. # path = Path() / 'D:/TestServer/123444.mp4'
  59. path = Path() / file_path
  60. size = path.stat().st_size
  61. mb_size = 0.0
  62. if suffix_type == 'MB':
  63. mb_size = size / 1024.0 / 1024.0
  64. if decimal_point != 0:
  65. mb_size = round(mb_size, decimal_point)
  66. return mb_size
  67. @staticmethod
  68. def get_param_flag(data=None):
  69. # print(data)
  70. if data is None:
  71. data = []
  72. flag = True
  73. for v in data:
  74. if v is None:
  75. flag = False
  76. break
  77. return flag
  78. @staticmethod
  79. def get_ip_address(request):
  80. """
  81. 获取ip地址
  82. :param request:
  83. :return:
  84. """
  85. try:
  86. real_ip = request.META['HTTP_X_FORWARDED_FOR']
  87. clientIP = real_ip.split(",")[0]
  88. except:
  89. try:
  90. clientIP = request.META['REMOTE_ADDR']
  91. except Exception as e:
  92. clientIP = ''
  93. return clientIP
  94. # @获取一天每个小时的datetime.datetime
  95. @staticmethod
  96. def getTimeDict(times):
  97. time_dict = {}
  98. t = 0
  99. for x in range(24):
  100. if x < 10:
  101. x = '0' + str(x)
  102. else:
  103. x = str(x)
  104. a = times.strftime("%Y-%m-%d") + " " + x + ":00:00"
  105. time_dict[t] = timezone.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
  106. t += 1
  107. return time_dict
  108. # 根据ip获取地址
  109. @staticmethod
  110. def getAddr(ip):
  111. print('start_time=' + str(time.time()))
  112. base_dir = BASE_DIR
  113. # ip数据库
  114. db = IPIPDatabase(base_dir + '/DB/17monipdb.dat')
  115. addr = db.lookup(ip)
  116. # ModelService.add_tmp_log(addr)
  117. ts = addr.split('\t')[0]
  118. print('end_time=' + str(time.time()))
  119. return ts
  120. # 通过ip检索ipip指定信息 lang为CN或EN
  121. @staticmethod
  122. def getIpIpInfo(ip, lang, update=False):
  123. ipbd_dir = BASE_DIR + "/DB/mydata4vipday2.ipdb"
  124. db = ipdb.City(ipbd_dir)
  125. if update:
  126. rr = db.reload(ipbd_dir)
  127. info = db.find_map(ip, lang)
  128. return info
  129. @staticmethod
  130. def getUserID(userPhone='13800138000', getUser=True, setOTAID=False, μs=True):
  131. if μs == True:
  132. if getUser == True:
  133. timeID = str(round(time.time() * 1000000))
  134. userID = timeID + userPhone
  135. return userID
  136. else:
  137. if setOTAID == False:
  138. timeID = str(round(time.time() * 1000000))
  139. ID = userPhone + timeID
  140. return ID
  141. else:
  142. timeID = str(round(time.time() * 1000000))
  143. eID = '13800' + timeID + '138000'
  144. return eID
  145. else:
  146. if getUser == True:
  147. timeID = str(round(time.time() * 1000))
  148. userID = timeID + userPhone
  149. return userID
  150. else:
  151. if setOTAID == False:
  152. timeID = str(round(time.time() * 1000))
  153. ID = userPhone + timeID
  154. return ID
  155. else:
  156. timeID = str(round(time.time() * 1000))
  157. eID = '13800' + timeID + '138000'
  158. return eID
  159. # 生成随机数
  160. @staticmethod
  161. def RandomStr(randomlength=8, number=True):
  162. str = ''
  163. if number == False:
  164. characterSet = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsT' \
  165. 'tUuVvWwXxYyZz0123456789'
  166. else:
  167. characterSet = '0123456789'
  168. length = len(characterSet) - 1
  169. random = Random()
  170. for index in range(randomlength):
  171. str += characterSet[random.randint(0, length)]
  172. return str
  173. # 生成订单好
  174. @staticmethod
  175. def createOrderID():
  176. random_id = CommonService.RandomStr(6, True)
  177. order_id = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + str(random_id)
  178. print('orderID:')
  179. print(order_id)
  180. return order_id
  181. # qs转换list datetime处理
  182. @staticmethod
  183. def qs_to_list(qs):
  184. res = []
  185. # print(qs)
  186. for ps in qs:
  187. try:
  188. if 'time' in ps:
  189. ps['time'] = ps['time'].strftime("%Y-%m-%d %H:%M:%S")
  190. if 'add_time' in ps:
  191. ps['add_time'] = ps['add_time'].strftime("%Y-%m-%d %H:%M:%S")
  192. if 'update_time' in ps:
  193. ps['update_time'] = ps['update_time'].strftime("%Y-%m-%d %H:%M:%S")
  194. if 'end_time' in ps:
  195. ps['end_time'] = ps['end_time'].strftime("%Y-%m-%d %H:%M:%S")
  196. if 'data_joined' in ps:
  197. if ps['data_joined']:
  198. ps['data_joined'] = ps['data_joined'].strftime("%Y-%m-%d %H:%M:%S")
  199. else:
  200. ps['data_joined'] = ''
  201. if 'userID__data_joined' in ps:
  202. if ps['userID__data_joined']:
  203. ps['userID__data_joined'] = ps['userID__data_joined'].strftime("%Y-%m-%d %H:%M:%S")
  204. else:
  205. ps['userID__data_joined'] = ''
  206. except Exception as e:
  207. pass
  208. res.append(ps)
  209. return res
  210. # 获取当前时间
  211. @staticmethod
  212. def get_now_time_str(n_time, tz, lang):
  213. print(n_time)
  214. print(tz)
  215. print(lang)
  216. n_time = int(n_time) + 3600 * float(tz)
  217. if lang == 'cn':
  218. return time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(int(n_time)))
  219. else:
  220. return time.strftime('%m-%d-%Y %H:%M:%S', time.gmtime(int(n_time)))
  221. # 生成随机数
  222. @staticmethod
  223. def encrypt_data(randomlength=8, number=False):
  224. str = ''
  225. if number == False:
  226. characterSet = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsT' \
  227. 'tUuVvWwXxYyZz0123456789'
  228. else:
  229. characterSet = '0123456789'
  230. length = len(characterSet) - 1
  231. random = Random()
  232. for index in range(randomlength):
  233. str += characterSet[random.randint(0, length)]
  234. return str
  235. @staticmethod
  236. def decode_data(content, start=1, end=4):
  237. if not content:
  238. return ''
  239. try:
  240. for i in range(start, end):
  241. if i == 1:
  242. content = base64.b64decode(content)
  243. content = content.decode('utf-8')
  244. content = content[1:-1]
  245. if i == 2:
  246. content = base64.b64decode(content)
  247. content = content.decode('utf-8')
  248. content = content[2:-2]
  249. if i == 3:
  250. content = base64.b64decode(content)
  251. content = content.decode('utf-8')
  252. content = content[3:-3]
  253. return content
  254. except Exception as e:
  255. print(e)
  256. return None
  257. @staticmethod
  258. def encode_data(content, start=1, end=4):
  259. if not content:
  260. return ''
  261. for i in range(start, end):
  262. if i == 1:
  263. content = RandomStr(3, False) + content + RandomStr(3, False)
  264. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  265. if i == 2:
  266. content = RandomStr(2, False) + str(content) + RandomStr(2, False)
  267. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  268. if i == 3:
  269. content = RandomStr(1, False) + str(content) + RandomStr(1, False)
  270. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  271. return content
  272. # 把格式化时间转换成时间戳
  273. @staticmethod
  274. def str_to_timestamp(str_time=None, format='%Y-%m-%d %H:%M:%S'):
  275. if str_time:
  276. time_tuple = time.strptime(str_time, format) # 把格式化好的时间转换成元祖
  277. result = time.mktime(time_tuple) # 把时间元祖转换成时间戳
  278. return int(result)
  279. return int(time.time())
  280. # 把时间戳转换成格式化
  281. @staticmethod
  282. def timestamp_to_str(timestamp=None, format='%Y-%m-%d %H:%M:%S'):
  283. if timestamp:
  284. time_tuple = time.localtime(timestamp) # 把时间戳转换成时间元祖
  285. result = time.strftime(format, time_tuple) # 把时间元祖转换成格式化好的时间
  286. return result
  287. else:
  288. return time.strptime(format)
  289. # 计算N个月后的时间戳
  290. @staticmethod
  291. def calcMonthLater(addMonth, unix_timestamp=None):
  292. if unix_timestamp:
  293. now_year = time.localtime(unix_timestamp).tm_year
  294. now_month = time.localtime(unix_timestamp).tm_mon
  295. now_day = time.localtime(unix_timestamp).tm_mday
  296. now_hour = time.localtime(unix_timestamp).tm_hour
  297. now_min = time.localtime(unix_timestamp).tm_min
  298. now_second = time.localtime(unix_timestamp).tm_sec
  299. else:
  300. now_year = datetime.datetime.now().year
  301. now_month = datetime.datetime.now().month
  302. now_day = datetime.datetime.now().day
  303. now_hour = datetime.datetime.now().hour
  304. now_min = datetime.datetime.now().minute
  305. now_second = datetime.datetime.now().second
  306. for add in range(addMonth):
  307. if now_month == 12:
  308. now_year += 1
  309. now_month = 1
  310. else:
  311. now_month += 1
  312. for is_format in range(4):
  313. try:
  314. date_format = '{now_year}-{now_month}-{now_day} {now_hour}:{now_min}:{now_second}' \
  315. .format(now_year=now_year, now_month=now_month, now_day=now_day, now_hour=now_hour,
  316. now_min=now_min, now_second=now_second)
  317. timestamps = CommonService.str_to_timestamp(date_format)
  318. except Exception as e:
  319. if str(e) == 'day is out of range for month':
  320. now_day = now_day - 1
  321. return timestamps
  322. @staticmethod
  323. def updateMac(mac: str):
  324. macArray = mac.split(':')
  325. macArray[0] = int(macArray[0], 16)
  326. macArray[1] = int(macArray[1], 16)
  327. macArray[2] = int(macArray[2], 16)
  328. first = int(macArray[5], 16)
  329. second = int(macArray[4], 16)
  330. three = int(macArray[3], 16)
  331. # print(macArray)
  332. # print(first)
  333. # print(second)
  334. # print(three)
  335. if first == 255 and second == 255 and three == 255:
  336. return None
  337. first += 1
  338. if first / 256 == 1:
  339. second += 1
  340. first = first % 256
  341. if second / 256 == 1:
  342. three += 1
  343. second = second % 256
  344. macArray[3] = three
  345. macArray[4] = second
  346. macArray[5] = first
  347. # print(macArray)
  348. tmp = ':'.join(map(lambda x: "%02x" % x, macArray))
  349. # print(tmp)
  350. return tmp.upper()
  351. @staticmethod
  352. def decode_data(content, start=1, end=4):
  353. if not content:
  354. return ''
  355. try:
  356. for i in range(start, end):
  357. if i == 1:
  358. content = base64.b64decode(content)
  359. content = content.decode('utf-8')
  360. content = content[1:-1]
  361. if i == 2:
  362. content = base64.b64decode(content)
  363. content = content.decode('utf-8')
  364. content = content[2:-2]
  365. if i == 3:
  366. content = base64.b64decode(content)
  367. content = content.decode('utf-8')
  368. content = content[3:-3]
  369. print(content)
  370. return content
  371. except Exception as e:
  372. print(e)
  373. return None
  374. @staticmethod
  375. def encode_data(content, start=1, end=4):
  376. if not content:
  377. return ''
  378. for i in range(start, end):
  379. if i == 1:
  380. content = CommonService.RandomStr(3, False) + content + CommonService.RandomStr(3, False)
  381. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  382. if i == 2:
  383. content = CommonService.RandomStr(2, False) + str(content) + CommonService.RandomStr(2, False)
  384. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  385. if i == 3:
  386. content = CommonService.RandomStr(1, False) + str(content) + CommonService.RandomStr(1, False)
  387. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  388. return content
  389. @staticmethod
  390. def encode_data_without_salt(content):
  391. return base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  392. @staticmethod
  393. def check_time_stamp_token(token, time_stamp):
  394. # 时间戳token校验
  395. if not all([token, time_stamp]):
  396. return False
  397. try:
  398. token = int(CommonService.decode_data(token))
  399. time_stamp = int(time_stamp)
  400. now_time = int(time.time())
  401. distance = now_time - time_stamp
  402. if token != time_stamp or distance > 60000 or distance < -60000: # 为了全球化时间控制在一天内
  403. return False
  404. return True
  405. except Exception as e:
  406. print(e)
  407. return False
  408. @staticmethod
  409. def check_time_stamp_token_without_distance(time_stamp_token, time_stamp):
  410. """
  411. 用于没有RTC设备的时间戳token校验
  412. @param time_stamp: 时间戳
  413. @param time_stamp_token: 时间戳token
  414. @return: boolean True/False
  415. """
  416. if not all([time_stamp_token, time_stamp]):
  417. return False
  418. try:
  419. token = CommonService.decode_data(time_stamp_token)
  420. if token != time_stamp:
  421. return False
  422. return True
  423. except Exception as e:
  424. print(e)
  425. return False
  426. @staticmethod
  427. def req_publish_mqtt_msg(thing_name, topic_name, msg):
  428. """
  429. 通用发布MQTT消息函数
  430. @param thing_name: 物品名
  431. @param topic_name: 主题名
  432. @param msg: 消息内容
  433. @return: boolean
  434. """
  435. if not all([thing_name, topic_name, msg]):
  436. return False
  437. try:
  438. # 获取数据组织将要请求的url
  439. iot = iotdeviceInfoModel.objects.filter(
  440. thing_name__icontains=thing_name).values(
  441. 'endpoint', 'token_iot_number')
  442. if not iot.exists():
  443. return False
  444. endpoint = iot[0]['endpoint']
  445. Token = iot[0]['token_iot_number']
  446. # api doc: https://docs.aws.amazon.com/zh_cn/iot/latest/developerguide/http.html
  447. # url: https://IoT_data_endpoint/topics/url_encoded_topic_name?qos=1
  448. # post请求url发布MQTT消息
  449. url = 'https://{}/topics/{}'.format(endpoint, topic_name)
  450. authorizer_name = 'Ansjer_Iot_Auth'
  451. signature = CommonService.rsa_sign(Token) # Token签名
  452. headers = {
  453. 'x-amz-customauthorizer-name': authorizer_name,
  454. 'Token': Token,
  455. 'x-amz-customauthorizer-signature': signature}
  456. r = requests.post(url=url, headers=headers, json=msg, timeout=2)
  457. if r.status_code == 200:
  458. res = r.json()
  459. if res['message'] == 'OK':
  460. return True
  461. return False
  462. else:
  463. return False
  464. except Exception as e:
  465. return False
  466. @staticmethod
  467. def rsa_sign(Token):
  468. # 私钥签名Token
  469. if not Token:
  470. return ''
  471. private_key_file = '''-----BEGIN RSA PRIVATE KEY-----
  472. MIIEpQIBAAKCAQEA5iJzEDPqtGmFMggekVro6C0lrjuC2BjunGkrFNJWpDYzxCzE
  473. X5jf4/Fq7hcIaQd5sqHugDxPVollSLPe9zNilbrd0sZfU+Ed8gRVuKW9KwfE9XFr
  474. L0pt6bKRQ0IIRfiZ9TuR0tsQysvcO1GZSXcYfPue3tGM1zOnWFThWDqZ06+sOxzt
  475. RMRl4yNfbpCG4MfxG3itNXOfrjZv2OMLSXrxmzubSvRpUYSvQPs4fm9302SAnySY
  476. 0MKzx6H6528ZQm/IDDSZy6EmNBIyTRDfxC56vnYcXvqedAQh7jJnjdvt6Q4MhASH
  477. eIYi1FBSdu2NT6wgpnrqXzx5pq9kR/lnsLID0wIDAQABAoIBAQCiF4GT1/1oNSpr
  478. ouxk1PNXFPWFUsVGD8mAwVJmx//eiY7MjfuCmdqYYmI+cFqsH2fIOeYSzGfVO9Dq
  479. 9EYHN1oovAWhf7eFDPpajFMUSyiCNmazub8VAAeKowtNpCTPo9pMsDh1m3aoYA4u
  480. ebrN0+Sbo16y8kWRDgDAZoiR7DSMs8lczk16hwfv5mw8XpNDbaL3Coi4Koe2S1Yh
  481. 2SX3vWFlpd7qF1ZYXuZIp+b8JPrV7n9eUKoFgzj0gqgwQK80CoexIjiOrNMPvkQa
  482. q+8kCvFjAzKxOK7e8gjM8lMRiGodb61kmYZkkJzFwWO4EaGbl34lfVECd1Ixp3tF
  483. be0OWAGBAoGBAPSteXDzzToD8ovM7LL11x0jWwI6HOiHu89kZtW566rIezjWBuA2
  484. TxrcYKM3h9jQRXS3CsMdoIv6XGk5lqM8ADtjn23FBWe/THYLh8bm8JOgh5RRWQDg
  485. SvkLfi9Ih2mM4NJfmuuDOh3Nze2efLM7+kOZWUQwF2Zx9mL5jvRBk351AoGBAPDI
  486. sYmT2Li+i5+0vykA2m5uPF8ZOW8BGtAfCZv0suW7BNzSgin78g9WapRd/4p0NNiL
  487. /nVMqPPCpd1akCUpV+GDWQt0hV+HZjxANE0KWhciQRyo2qvo51j8SWILJSgh0tXC
  488. aTF8qt6oGw3VN3m57vKhbrlDaz0J/NDJFci6msAnAoGBAOuG6bXPGijUj+//DYKf
  489. n7jOxdZ49kboEePrtAncdHzri6IEdI3z+WXT6bpzw/LzWUimwldb96WHFNm9s8Hi
  490. Ch8hIODbnP5naUTgiIzw1XhmONyPCewL/F+LrqX5XVA/alNX8JrwsUrrR2WLAGLQ
  491. Q3I69XDsEjptTU2tCO0bCs3ZAoGBAJ2lCHfm0JHET230zONvp5N9oREyVqQSuRdh
  492. +syc3TQDyh85w/bw+X6JOaaCFHj1tFPC9Iqf8k4GNspCLPXnp54CfR4+38O3xnvU
  493. HWoDSRC0YKT++IxtJGriYrlKSr2Hx54kdvLriIPW1D+uRW/xCDza7L9nIKMKEvgv
  494. b4/IfOEpAoGAeKM9Te7T1VzlAkS0CJOwanzwYV/zrex84WuXxlsGgPQ871lTs5AP
  495. H1QLfLfFXH+UVrCEC2yv4eml/cqFkpB3gE5i4MQ8GPVIOSs5tsIyl8YUA03vdNdB
  496. GCqvlyw5dfxNA+EtxNE2wCW/LW7ENJlACgcfgPlBZtpLheWoZB/maw4=
  497. -----END RSA PRIVATE KEY-----'''
  498. # 使用密钥文件方式
  499. # private_key_file_path = os.path.join(BASE_DIR, 'static/iotCore/private.pem')#.replace('\\', '/')
  500. # private_key_file = open(private_key_file_path, 'r')
  501. private_key = ct.load_privatekey(ct.FILETYPE_PEM, private_key_file)
  502. signature = ct.sign(private_key, Token.encode('utf8'), 'sha256')
  503. signature = encodebytes(signature).decode('utf8').replace('\n', '')
  504. # print('signature:', signature)
  505. return signature
  506. @staticmethod
  507. def get_payment_status_url(lang, payment_status):
  508. # 返回相应的支付状态url
  509. if lang == 'cn':
  510. file_name = 'success.html' if payment_status == 'success' else 'fail.html'
  511. else:
  512. file_name = 'en_success.html' if payment_status == 'success' else 'en_fail.html'
  513. pay_failed_url = "{}web/paid2/{}".format(SERVER_DOMAIN_SSL, file_name)
  514. return pay_failed_url
  515. # 根据uid查询序列号,存在则返回序列号,否则返uid
  516. @staticmethod
  517. def query_serial_with_uid(uid):
  518. device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number')
  519. if device_info_qs.exists():
  520. serial_number = device_info_qs[0]['serial_number']
  521. if serial_number:
  522. return serial_number
  523. return uid
  524. # 根据序列号查询uid,存在则返回uid,否则返回序列号
  525. @staticmethod
  526. def query_uid_with_serial(serial_number):
  527. device_info_qs = Device_Info.objects.filter(serial_number=serial_number).values('UID')
  528. if device_info_qs.exists():
  529. uid = device_info_qs[0]['UID']
  530. if uid:
  531. return uid
  532. return serial_number
  533. # 根据企业标识返回物品名
  534. @staticmethod
  535. def get_thing_name(company_mark, thing_name_suffix):
  536. if company_mark == '11A':
  537. return 'Ansjer_Device_' + thing_name_suffix
  538. elif company_mark == '11L':
  539. return 'LC' + thing_name_suffix
  540. else:
  541. return thing_name_suffix
  542. @staticmethod
  543. def confirm_region_id(request):
  544. """
  545. 根据配置信息确定region_id
  546. @param request: 请求体
  547. @return: region_id
  548. """
  549. region_id = 3
  550. if CONFIG_INFO == CONFIG_TEST or CONFIG_INFO == CONFIG_CN:
  551. region_id = 1
  552. else: # 国外配置暂时通过ip确认
  553. ip = CommonService.get_ip_address(request)
  554. ipInfo = CommonService.getIpIpInfo(ip, 'CN')
  555. if ipInfo['country_code']:
  556. country_qs = CountryModel.objects.filter(country_code=ipInfo['country_code']).values('region__id')
  557. if country_qs.exists():
  558. region_id = country_qs[0]['region__id']
  559. else: # 不存在默认返回美洲地区api
  560. region_qs = RegionModel.objects.filter(continent_code='NA').values("id")
  561. region_id = region_qs[0]['id']
  562. return region_id