CommonService.py 23 KB

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