IotCoreController.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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
  117. region_id = CommonService.confirm_region_id(request)
  118. iotClient = IOTClient(region_id)
  119. # 拼接物品名
  120. thingName = CommonService.get_thing_name(company_mark, thing_name_suffix)
  121. thingGroup = device_version + '_' + language
  122. res = iotClient.register_to_iot_core(thingName, thingGroup, response)
  123. token_iot_number = hashlib.md5((str(uuid.uuid1()) + str(int(time.time()))).encode('utf-8')).hexdigest()
  124. iotdeviceInfoModel.objects.create(uid=uid,
  125. serial_number=serial,
  126. endpoint=res[0]['endpoint'],
  127. certificate_id=res[0]['certificateId'],
  128. certificate_pem=res[0]['certificatePem'],
  129. public_key=res[0]['publicKey'],
  130. private_key=res[0]['privateKey'],
  131. thing_name=res[1]['ThingName'],
  132. thing_groups=res[1]['thingGroupName'],
  133. token_iot_number=token_iot_number
  134. )
  135. res = {
  136. 'certificateId': res[0]['certificateId'],
  137. 'certificatePem': res[0]['certificatePem'],
  138. 'publicKey': res[0]['publicKey'],
  139. 'privateKey': res[0]['privateKey'],
  140. 'endpoint': res[0]['endpoint']
  141. }
  142. return response.json(0, {'res': res})
  143. except Exception as e:
  144. print(e)
  145. return response.json(500, repr(e))
  146. @staticmethod
  147. def thing_regroup(request_dict, response):
  148. # 物品重新分组
  149. uid = request_dict.get('uid', '')
  150. token = request_dict.get('token', None)
  151. language = request_dict.get('language', None)
  152. region_id = request_dict.get('region_id', None)
  153. time_stamp = request_dict.get('time_stamp', None)
  154. device_version = request_dict.get('device_version', None)
  155. if not all([token, language, region_id, time_stamp, device_version]):
  156. return response.json(444)
  157. # 时间戳token校验
  158. if not CommonService.check_time_stamp_token(token, time_stamp):
  159. return response.json(13)
  160. company_mark = '11A'
  161. thing_name_suffix = uid
  162. if not uid:
  163. # 使用序列号
  164. serial_number = request_dict.get('serial_number', None)
  165. if not serial_number:
  166. return response.json(444)
  167. company_mark = serial_number[-3:]
  168. thing_name_suffix = serial_number
  169. uid = CommonService.query_uid_with_serial(serial_number)
  170. uid_set_qs = UidSetModel.objects.filter(uid=uid)
  171. thingName = CommonService.get_thing_name(company_mark, thing_name_suffix)
  172. new_thingGroupName = (device_version + '_' + language).replace('.', '_') # 物品组命名不能包含'.'
  173. try:
  174. iotClient = IOTClient(int(region_id))
  175. # 获取旧物品组
  176. list_groups_res = iotClient.client.list_thing_groups_for_thing(thingName=thingName, maxResults=1)
  177. old_thingGroupName = list_groups_res['thingGroups'][0]['groupName']
  178. # 没有新物品组则创建
  179. list_thing_groups_res = iotClient.client.list_thing_groups(namePrefixFilter=new_thingGroupName
  180. , maxResults=1, recursive=False)
  181. if not list_thing_groups_res['thingGroups']:
  182. attributes = {
  183. "update_time": "0"
  184. }
  185. thingGroupProperties = {
  186. "thingGroupDescription": "OTA",
  187. "attributePayload": {
  188. "attributes": attributes,
  189. "merge": False # 更新时覆盖掉而不是合并
  190. }
  191. }
  192. iotClient.client.create_thing_group(thingGroupName=new_thingGroupName
  193. , thingGroupProperties=thingGroupProperties)
  194. iotClient.client.update_thing_groups_for_thing(thingName=thingName
  195. , thingGroupsToAdd=[new_thingGroupName]
  196. , thingGroupsToRemove=[old_thingGroupName])
  197. # 更新设备版本信息
  198. uid_set_qs.update(version=device_version)
  199. return response.json(0)
  200. except Exception as e:
  201. print(e)
  202. return response.json(500, repr(e))
  203. def clear_Iot_Cerm(self, request_dict, response):
  204. serial_number = request_dict.get('serial_number', None)
  205. if serial_number:
  206. iot = iotdeviceInfoModel.objects.filter(thing_name="Ansjer_Device_" + serial_number)
  207. if iot.exists():
  208. iot.delete()
  209. return response.json(0)
  210. else:
  211. return response.json(444)
  212. # Alexa请求IoT Core下发MQTT消息通知设备开始或停止推流,或唤醒设备
  213. @staticmethod
  214. def request_publish_message(request_dict, response):
  215. UID = request_dict.get('UID', None)
  216. rtsp = request_dict.get('rtsp', None)
  217. enable = request_dict.get('enable', '1')
  218. if not all([UID, rtsp]):
  219. return response.json(444)
  220. try:
  221. thing_name = CommonService.query_serial_with_uid(UID) # 存在序列号则为使用序列号作为物品名
  222. topic_name = 'ansjer/generic/{}'.format(thing_name)
  223. msg = OrderedDict(
  224. [
  225. ('alexaRtspCommand', rtsp),
  226. ('enable', int(enable)),
  227. ]
  228. )
  229. if not CommonService.req_publish_mqtt_msg(thing_name, topic_name, msg):
  230. return response.json(10044)
  231. return response.json(0)
  232. except Exception as e:
  233. return response.json(500, repr(e))
  234. def get_s3_pull_key(self, request_dict, response, request):
  235. # 通用发布主题通知
  236. UID = request_dict.get('UID', None)
  237. if not all([UID]):
  238. return response.json(444)
  239. try:
  240. # 获取检查uid的序列号,如果没有序列号,不使用MQTT下发消息
  241. device_info_qs = Device_Info.objects.filter(UID=UID).values('UID', 'serial_number')
  242. if not device_info_qs.exists():
  243. return response.json(10043)
  244. uid = device_info_qs[0]['UID']
  245. serial_number = device_info_qs[0]['serial_number']
  246. # 如果device_info表的serial_number不为空,物品名为'Ansjer_Device_序列号'
  247. thing_name_suffix = serial_number if serial_number != '' else uid
  248. # 获取数据组织将要请求的url
  249. iot = iotdeviceInfoModel.objects.filter(thing_name__contains=thing_name_suffix).values('thing_name',
  250. 'endpoint',
  251. 'token_iot_number')
  252. if not iot.exists():
  253. return response.json(10043)
  254. endpoint = iot[0]['endpoint']
  255. MSG = self.get_s3_key_return_msg(endpoint)
  256. return response.json(0, MSG)
  257. except Exception as e:
  258. # print(e)
  259. return response.json(500, repr(e))
  260. def get_s3_key_return_msg(self, endpoint):
  261. MSG = {}
  262. if 'cn-northwest-1' in endpoint:
  263. key = AWS_IOT_GETS3_PULL_CHINA_ID
  264. secret = AWS_IOT_GETS3_PULL_CHINA_SECRET
  265. arn = AWS_ARN[0]
  266. region_name = AWS_IOT_SES_ACCESS_CHINA_REGION
  267. else:
  268. key = AWS_IOT_GETS3_PULL_FOREIGN_ID
  269. secret = AWS_IOT_GETS3_PULL_FOREIGN_SECRET
  270. arn = AWS_ARN[1]
  271. if 'ap-southeast-1' in endpoint:
  272. region_name = AWS_IOT_SES_ACCESS_FOREIGN_REGION_ASIA
  273. if 'eu-west-1' in endpoint:
  274. region_name = AWS_IOT_SES_ACCESS_FOREIGN_REGION_EUROPE
  275. if 'us-east-1' in endpoint:
  276. region_name = AWS_IOT_SES_ACCESS_FOREIGN_REGION_AMERICA
  277. MSG['AccessKeyId'] = key
  278. MSG['AccessKeySecret'] = secret
  279. MSG['bucket_name'] = 'asj-log'
  280. MSG['arn'] = arn
  281. MSG['region_name'] = region_name
  282. return MSG
  283. def getIotInfo(self, request_dict, response):
  284. # 获取IoT数据
  285. serial_number = request_dict.get('serial_number', None)
  286. uid = request_dict.get('uid', None)
  287. if not uid and not serial_number:
  288. return response.json(444)
  289. try:
  290. if serial_number:
  291. serial_number = serial_number[0:6]
  292. iot_info_qs = iotdeviceInfoModel.objects.filter(serial_number=serial_number). \
  293. values('endpoint', 'token_iot_number')
  294. else:
  295. iot_info_qs = iotdeviceInfoModel.objects.filter(uid=uid). \
  296. values('endpoint', 'token_iot_number')
  297. if not iot_info_qs.exists():
  298. return response.json(173)
  299. endpoint = iot_info_qs[0]['endpoint']
  300. token_iot_number = iot_info_qs[0]['token_iot_number']
  301. res = {'endpoint': endpoint, 'token_iot_number': token_iot_number}
  302. return response.json(0, res)
  303. except Exception as e:
  304. return response.json(500, repr(e))
  305. def pcGetIotInfo(self, request_dict, response):
  306. # PC工具获取IoT数据
  307. serial_number = request_dict.get('serial_number', None)
  308. uid = request_dict.get('uid', None)
  309. if not uid and not serial_number:
  310. return response.json(444)
  311. try:
  312. if serial_number:
  313. serial_number = serial_number[0:6]
  314. iot_info_qs = iotdeviceInfoModel.objects.filter(serial_number=serial_number). \
  315. values('endpoint', 'token_iot_number')
  316. else:
  317. iot_info_qs = iotdeviceInfoModel.objects.filter(uid=uid). \
  318. values('endpoint', 'token_iot_number')
  319. if not iot_info_qs.exists():
  320. return response.json(173)
  321. endpoint = iot_info_qs[0]['endpoint']
  322. token_iot_number = iot_info_qs[0]['token_iot_number']
  323. res = {'endpoint': endpoint, 'token_iot_number': token_iot_number}
  324. return response.json(0, res)
  325. except Exception as e:
  326. return response.json(500, repr(e))