CommonService.py 22 KB

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