IotCoreController.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. import hashlib
  4. import logging
  5. import time
  6. import uuid
  7. from collections import OrderedDict
  8. import requests
  9. from django.views import View
  10. from Ansjer.config import AWS_IOT_GETS3_PULL_CHINA_ID, AWS_IOT_GETS3_PULL_CHINA_SECRET, \
  11. AWS_IOT_GETS3_PULL_FOREIGN_ID, AWS_IOT_GETS3_PULL_FOREIGN_SECRET, AWS_ARN, AWS_IOT_SES_ACCESS_CHINA_REGION, \
  12. AWS_IOT_SES_ACCESS_FOREIGN_REGION_ASIA, AWS_IOT_SES_ACCESS_FOREIGN_REGION_EUROPE, \
  13. AWS_IOT_SES_ACCESS_FOREIGN_REGION_AMERICA, CONFIG_INFO, CONFIG_TEST, CONFIG_CN
  14. from Controller.DeviceConfirmRegion import Device_Region
  15. from Model.models import Device_Info, iotdeviceInfoModel, SerialNumberModel, UidSetModel
  16. from Object.IOTCore.IotObject import IOTClient
  17. from Object.ResponseObject import ResponseObject
  18. from Object.TokenObject import TokenObject
  19. from Service.CommonService import CommonService
  20. class IotCoreView(View):
  21. def get(self, request, *args, **kwargs):
  22. request.encoding = 'utf-8'
  23. request_dict = request.GET
  24. operation = kwargs.get('operation', None)
  25. return self.validate(operation, request_dict, request)
  26. def post(self, request, *args, **kwargs):
  27. request.encoding = 'utf-8'
  28. request_dict = request.POST
  29. operation = kwargs.get('operation', None)
  30. return self.validate(operation, request_dict, request)
  31. def validate(self, operation, request_dict, request):
  32. response = ResponseObject()
  33. lang = request_dict.get('lang', 'en')
  34. response.lang = lang
  35. if operation == 'createKeysAndCertificate':
  36. return self.create_keys_and_certificate(request_dict, response, request)
  37. elif operation == 'requestPublishMessage':
  38. return self.request_publish_message(request_dict, response)
  39. elif operation == 'getS3PullKey':
  40. return self.get_s3_pull_key(request_dict, response, request)
  41. elif operation == 'thingRegroup':
  42. return self.thing_regroup(request_dict, response)
  43. elif operation == 'pcGetIotInfo':
  44. return self.pcGetIotInfo(request_dict, response)
  45. else:
  46. token = TokenObject(request_dict.get('token', None))
  47. if token.code != 0:
  48. return response.json(token.code)
  49. response.lang = token.lang
  50. if operation == 'clearIotCerm':
  51. return self.clear_Iot_Cerm(request_dict, response)
  52. elif operation == 'getIotInfo':
  53. return self.getIotInfo(request_dict, response)
  54. else:
  55. return response.json(404)
  56. # 设备注册到aws iot core
  57. @staticmethod
  58. def create_keys_and_certificate(request_dict, response, request):
  59. logger = logging.getLogger('info')
  60. logger.info('设备注册到aws iot core请求参数:{}'.format(request_dict))
  61. token = request_dict.get('token', None)
  62. language = request_dict.get('language', None)
  63. time_stamp = request_dict.get('time_stamp', None)
  64. device_version = request_dict.get('device_version', None).replace('.', '_') # 物品组命名不能包含'.'
  65. if not all([token, language, time_stamp, device_version]):
  66. return response.json(444, {'param': 'token, language, time_stamp, device_version'})
  67. try:
  68. # 时间戳token校验
  69. no_rtc = request_dict.get('no_rtc', None)
  70. if no_rtc:
  71. if not CommonService.check_time_stamp_token_without_distance(token, time_stamp):
  72. return response.json(13)
  73. else:
  74. if not CommonService.check_time_stamp_token(token, time_stamp):
  75. return response.json(13)
  76. uid = request_dict.get('uid', '')
  77. uid_code = request_dict.get('uid_code', None)
  78. company_mark = '11A'
  79. if not uid: # 传序列号
  80. serial_number = request_dict.get('serial_number', None)
  81. serial_number_code = request_dict.get('serial_number_code', None)
  82. if not all([serial_number, serial_number_code]):
  83. return response.json(444, {'param': 'serial_number, serial_number_code'})
  84. # 序列号编码解码校验
  85. serial_number_code = CommonService.decode_data(serial_number_code)
  86. if serial_number != serial_number_code:
  87. return response.json(404)
  88. serial = serial_number[0:6]
  89. company_mark = serial_number[-3:]
  90. try:
  91. SerialNumberModel.objects.get(serial_number=serial)
  92. except:
  93. return response.json(444)
  94. thing_name_suffix = serial_number # 物品名后缀
  95. iot_device_info_qs = iotdeviceInfoModel.objects.filter(serial_number=serial)
  96. else: # 传uid
  97. # uid编码解码校验
  98. uid_code = CommonService.decode_data(uid_code)
  99. if uid != uid_code:
  100. return response.json(404)
  101. serial = '' # iot_deviceInfo表写入serial_number为''
  102. thing_name_suffix = uid # 物品名后缀
  103. iot_device_info_qs = iotdeviceInfoModel.objects.filter(uid=uid)
  104. # 判断设备是否已注册过
  105. if iot_device_info_qs.exists():
  106. iot = iot_device_info_qs[0]
  107. res = {
  108. 'certificateId': iot.certificate_id,
  109. 'certificatePem': iot.certificate_pem,
  110. 'publicKey': iot.public_key,
  111. 'privateKey': iot.private_key,
  112. 'endpoint': iot.endpoint
  113. }
  114. return response.json(0, {'res': res})
  115. else:
  116. region_id = request_dict.get('region_id', None)
  117. if not region_id:
  118. # 根据配置信息确定region_id
  119. region_id = CommonService.confirm_region_id(request)
  120. iotClient = IOTClient(int(region_id))
  121. # 拼接物品名
  122. thingName = CommonService.get_thing_name(company_mark, thing_name_suffix)
  123. thingGroup = device_version + '_' + language
  124. res = iotClient.register_to_iot_core(thingName, thingGroup, response)
  125. token_iot_number = hashlib.md5((str(uuid.uuid1()) + str(int(time.time()))).encode('utf-8')).hexdigest()
  126. iotdeviceInfoModel.objects.create(uid=uid,
  127. serial_number=serial,
  128. endpoint=res[0]['endpoint'],
  129. certificate_id=res[0]['certificateId'],
  130. certificate_pem=res[0]['certificatePem'],
  131. public_key=res[0]['publicKey'],
  132. private_key=res[0]['privateKey'],
  133. thing_name=res[1]['ThingName'],
  134. thing_groups=res[1]['thingGroupName'],
  135. token_iot_number=token_iot_number
  136. )
  137. res = {
  138. 'certificateId': res[0]['certificateId'],
  139. 'certificatePem': res[0]['certificatePem'],
  140. 'publicKey': res[0]['publicKey'],
  141. 'privateKey': res[0]['privateKey'],
  142. 'endpoint': res[0]['endpoint']
  143. }
  144. return response.json(0, {'res': res})
  145. except Exception as e:
  146. print(e)
  147. return response.json(500, repr(e))
  148. @staticmethod
  149. def thing_regroup(request_dict, response):
  150. # 物品重新分组
  151. uid = request_dict.get('uid', '')
  152. token = request_dict.get('token', None)
  153. language = request_dict.get('language', None)
  154. region_id = request_dict.get('region_id', None)
  155. time_stamp = request_dict.get('time_stamp', None)
  156. device_version = request_dict.get('device_version', None)
  157. if not all([token, language, region_id, time_stamp, device_version]):
  158. return response.json(444)
  159. # 时间戳token校验
  160. if not CommonService.check_time_stamp_token(token, time_stamp):
  161. return response.json(13)
  162. company_mark = '11A'
  163. thing_name_suffix = uid
  164. if not uid:
  165. # 使用序列号
  166. serial_number = request_dict.get('serial_number', None)
  167. if not serial_number:
  168. return response.json(444)
  169. company_mark = serial_number[-3:]
  170. thing_name_suffix = serial_number
  171. uid = CommonService.query_uid_with_serial(serial_number)
  172. uid_set_qs = UidSetModel.objects.filter(uid=uid)
  173. thingName = CommonService.get_thing_name(company_mark, thing_name_suffix)
  174. new_thingGroupName = (device_version + '_' + language).replace('.', '_') # 物品组命名不能包含'.'
  175. try:
  176. iotClient = IOTClient(int(region_id))
  177. # 获取旧物品组
  178. list_groups_res = iotClient.client.list_thing_groups_for_thing(thingName=thingName, maxResults=1)
  179. old_thingGroupName = list_groups_res['thingGroups'][0]['groupName']
  180. # 没有新物品组则创建
  181. list_thing_groups_res = iotClient.client.list_thing_groups(namePrefixFilter=new_thingGroupName
  182. , maxResults=1, recursive=False)
  183. if not list_thing_groups_res['thingGroups']:
  184. attributes = {
  185. "update_time": "0"
  186. }
  187. thingGroupProperties = {
  188. "thingGroupDescription": "OTA",
  189. "attributePayload": {
  190. "attributes": attributes,
  191. "merge": False # 更新时覆盖掉而不是合并
  192. }
  193. }
  194. iotClient.client.create_thing_group(thingGroupName=new_thingGroupName
  195. , thingGroupProperties=thingGroupProperties)
  196. iotClient.client.update_thing_groups_for_thing(thingName=thingName
  197. , thingGroupsToAdd=[new_thingGroupName]
  198. , thingGroupsToRemove=[old_thingGroupName])
  199. # 更新设备版本信息
  200. uid_set_qs.update(version=device_version)
  201. return response.json(0)
  202. except Exception as e:
  203. print(e)
  204. return response.json(500, repr(e))
  205. def clear_Iot_Cerm(self, request_dict, response):
  206. serial_number = request_dict.get('serial_number', None)
  207. if serial_number:
  208. iot = iotdeviceInfoModel.objects.filter(thing_name="Ansjer_Device_" + serial_number)
  209. if iot.exists():
  210. iot.delete()
  211. return response.json(0)
  212. else:
  213. return response.json(444)
  214. # Alexa请求IoT Core下发MQTT消息通知设备开始或停止推流,或唤醒设备
  215. @staticmethod
  216. def request_publish_message(request_dict, response):
  217. UID = request_dict.get('UID', None)
  218. rtsp = request_dict.get('rtsp', None)
  219. enable = request_dict.get('enable', '1')
  220. if not all([UID, rtsp]):
  221. return response.json(444)
  222. try:
  223. thing_name = CommonService.query_serial_with_uid(UID) # 存在序列号则为使用序列号作为物品名
  224. topic_name = 'ansjer/generic/{}'.format(thing_name)
  225. msg = OrderedDict(
  226. [
  227. ('alexaRtspCommand', rtsp),
  228. ('enable', int(enable)),
  229. ]
  230. )
  231. if not CommonService.req_publish_mqtt_msg(thing_name, topic_name, msg):
  232. return response.json(10044)
  233. return response.json(0)
  234. except Exception as e:
  235. return response.json(500, repr(e))
  236. def get_s3_pull_key(self, request_dict, response, request):
  237. # 通用发布主题通知
  238. UID = request_dict.get('UID', None)
  239. if not all([UID]):
  240. return response.json(444)
  241. try:
  242. # 获取检查uid的序列号,如果没有序列号,不使用MQTT下发消息
  243. device_info_qs = Device_Info.objects.filter(UID=UID).values('UID', 'serial_number')
  244. if not device_info_qs.exists():
  245. return response.json(10043)
  246. uid = device_info_qs[0]['UID']
  247. serial_number = device_info_qs[0]['serial_number']
  248. # 如果device_info表的serial_number不为空,物品名为'Ansjer_Device_序列号'
  249. thing_name_suffix = serial_number if serial_number != '' else uid
  250. # 获取数据组织将要请求的url
  251. iot = iotdeviceInfoModel.objects.filter(thing_name__contains=thing_name_suffix).values('thing_name',
  252. 'endpoint',
  253. 'token_iot_number')
  254. if not iot.exists():
  255. return response.json(10043)
  256. endpoint = iot[0]['endpoint']
  257. MSG = self.get_s3_key_return_msg(endpoint)
  258. return response.json(0, MSG)
  259. except Exception as e:
  260. # print(e)
  261. return response.json(500, repr(e))
  262. def get_s3_key_return_msg(self, endpoint):
  263. MSG = {}
  264. if 'cn-northwest-1' in endpoint:
  265. key = AWS_IOT_GETS3_PULL_CHINA_ID
  266. secret = AWS_IOT_GETS3_PULL_CHINA_SECRET
  267. arn = AWS_ARN[0]
  268. region_name = AWS_IOT_SES_ACCESS_CHINA_REGION
  269. else:
  270. key = AWS_IOT_GETS3_PULL_FOREIGN_ID
  271. secret = AWS_IOT_GETS3_PULL_FOREIGN_SECRET
  272. arn = AWS_ARN[1]
  273. if 'ap-southeast-1' in endpoint:
  274. region_name = AWS_IOT_SES_ACCESS_FOREIGN_REGION_ASIA
  275. if 'eu-west-1' in endpoint:
  276. region_name = AWS_IOT_SES_ACCESS_FOREIGN_REGION_EUROPE
  277. if 'us-east-1' in endpoint:
  278. region_name = AWS_IOT_SES_ACCESS_FOREIGN_REGION_AMERICA
  279. MSG['AccessKeyId'] = key
  280. MSG['AccessKeySecret'] = secret
  281. MSG['bucket_name'] = 'asj-log'
  282. MSG['arn'] = arn
  283. MSG['region_name'] = region_name
  284. return MSG
  285. def getIotInfo(self, request_dict, response):
  286. # 获取IoT数据
  287. serial_number = request_dict.get('serial_number', None)
  288. uid = request_dict.get('uid', None)
  289. if not uid and not serial_number:
  290. return response.json(444)
  291. try:
  292. if serial_number:
  293. serial_number = serial_number[0:6]
  294. iot_info_qs = iotdeviceInfoModel.objects.filter(serial_number=serial_number). \
  295. values('endpoint', 'token_iot_number')
  296. else:
  297. iot_info_qs = iotdeviceInfoModel.objects.filter(uid=uid). \
  298. values('endpoint', 'token_iot_number')
  299. if not iot_info_qs.exists():
  300. return response.json(173)
  301. endpoint = iot_info_qs[0]['endpoint']
  302. token_iot_number = iot_info_qs[0]['token_iot_number']
  303. res = {'endpoint': endpoint, 'token_iot_number': token_iot_number}
  304. return response.json(0, res)
  305. except Exception as e:
  306. return response.json(500, repr(e))
  307. def pcGetIotInfo(self, request_dict, response):
  308. # PC工具获取IoT数据
  309. serial_number = request_dict.get('serial_number', None)
  310. uid = request_dict.get('uid', None)
  311. if not uid and not serial_number:
  312. return response.json(444)
  313. try:
  314. if serial_number:
  315. serial_number = serial_number[0:6]
  316. iot_info_qs = iotdeviceInfoModel.objects.filter(serial_number=serial_number). \
  317. values('endpoint', 'token_iot_number')
  318. else:
  319. iot_info_qs = iotdeviceInfoModel.objects.filter(uid=uid). \
  320. values('endpoint', 'token_iot_number')
  321. if not iot_info_qs.exists():
  322. return response.json(173)
  323. endpoint = iot_info_qs[0]['endpoint']
  324. token_iot_number = iot_info_qs[0]['token_iot_number']
  325. res = {'endpoint': endpoint, 'token_iot_number': token_iot_number}
  326. return response.json(0, res)
  327. except Exception as e:
  328. return response.json(500, repr(e))