GatewayDeviceController.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. # -*- encoding: utf-8 -*-
  2. """
  3. @File : GatewayDeviceController.py
  4. @Time : 2022/6/6 13:50
  5. @Author : stephen
  6. @Email : zhangdongming@asj6.wecom.work
  7. @Software: PyCharm
  8. """
  9. import datetime
  10. import time
  11. import requests
  12. from django.db import transaction
  13. from django.db.models import Q
  14. from django.views.generic.base import View
  15. from Ansjer.Config.gatewaySensorConfig import SMART_SCENE_TOPIC
  16. from Ansjer.config import CONFIG_INFO, AWS_IOT_SES_ACCESS_CHINA_ID, AWS_IOT_SES_ACCESS_CHINA_SECRET, \
  17. AWS_IOT_SES_ACCESS_CHINA_REGION
  18. from Ansjer.config import LOGGER
  19. from Controller.SensorGateway.EquipmentFamilyController import EquipmentFamilyView
  20. from Controller.SensorGateway.SmartSocketController import SmartSocketView
  21. from Model.models import FamilyRoomDevice, FamilyRoom, GatewaySubDevice, Device_Info, UserFamily, FamilyMember, \
  22. UidSetModel, iotdeviceInfoModel, SmartScene, SceneLog, SocketInfo, SocketPowerStatistics, SocketSchedule, \
  23. CountryModel
  24. from Object.AWS.AWSIoTDataPlaneUtil import AWSIoTDataPlaneService
  25. from Object.RedisObject import RedisObject
  26. from Object.ResponseObject import ResponseObject
  27. from Object.TokenObject import TokenObject
  28. from Service.CommonService import CommonService
  29. class GatewayDeviceView(View):
  30. def get(self, request, *args, **kwargs):
  31. request.encoding = 'utf-8'
  32. operation = kwargs.get('operation')
  33. return self.validation(request.GET, request, operation)
  34. def post(self, request, *args, **kwargs):
  35. request.encoding = 'utf-8'
  36. operation = kwargs.get('operation')
  37. return self.validation(request.POST, request, operation)
  38. def validation(self, request_dict, request, operation):
  39. token = TokenObject(request.META.get('HTTP_AUTHORIZATION'))
  40. lang = request_dict.get('lang', None)
  41. response = ResponseObject(lang) if lang else ResponseObject(token.lang)
  42. if token.code != 0:
  43. return response.json(token.code)
  44. user_id = token.userID
  45. # 网关设备
  46. if operation == 'list':
  47. return self.gateway_device_list(request_dict, response)
  48. elif operation == 'del':
  49. return self.gateway_device_del(user_id, request_dict, response)
  50. elif operation == 'update':
  51. return self.gateway_device_update(user_id, request_dict, response)
  52. elif operation == 'my/family/list':
  53. return self.my_family_list(user_id, response)
  54. elif operation == 'location-setting':
  55. return self.device_location_setting(user_id, request_dict, response)
  56. elif operation == 'bind-serial-user':
  57. return self.bind_serial_user(user_id, request_dict, response)
  58. elif operation == 'get-serial-user':
  59. return self.get_serial_user(user_id, request_dict, response)
  60. @classmethod
  61. def device_location_setting(cls, user_id, request_dict, response):
  62. """
  63. 网关位置迁移
  64. @param user_id: 用户id
  65. @param request_dict: 请求参数字典
  66. @param response: 响应对象
  67. @return: []
  68. """
  69. device_id = request_dict.get('deviceId', None)
  70. family_id = request_dict.get('familyId', None)
  71. room_id = request_dict.get('roomId', None)
  72. if not all([device_id, family_id]):
  73. return response.json(444)
  74. family_id = int(family_id)
  75. permission = EquipmentFamilyView.get_member_permission_details(user_id, family_id)
  76. if not permission or permission == '003':
  77. return response.json(404)
  78. try:
  79. with transaction.atomic():
  80. family_room_device_qs = FamilyRoomDevice.objects.filter(device_id=device_id, family_id=family_id)
  81. if family_room_device_qs.exists():
  82. family_room_device_qs = family_room_device_qs.filter(sub_device=0)
  83. if family_room_device_qs.exists() and room_id:
  84. family_room_device_qs.update(room_id=int(room_id))
  85. else:
  86. user_family_qs = UserFamily.objects.filter(id=family_id)
  87. if not user_family_qs:
  88. return response.json(173)
  89. family_room_device_qs = FamilyRoomDevice.objects.filter(device_id=device_id)
  90. if family_room_device_qs.exists():
  91. param_data = {'family_id': family_id, 'room_id': 0}
  92. if room_id:
  93. param_data['room_id'] = room_id
  94. family_room_device_qs.update(**param_data)
  95. return response.json(0)
  96. except Exception as e:
  97. print(e)
  98. return response.json(177, repr(e))
  99. @classmethod
  100. def gateway_device_update(cls, user_id, request_dict, response):
  101. """
  102. 网关设备修改名称
  103. @param user_id:
  104. @param request_dict:
  105. @param response:
  106. @return:
  107. """
  108. device_name = request_dict.get('deviceName')
  109. device_id = request_dict.get('deviceId')
  110. if not all([device_name, device_id]):
  111. return response.json(444)
  112. device_info_qs = Device_Info.objects.filter(userID_id=user_id, id=device_id)
  113. if device_info_qs.exists():
  114. device_info_qs.update(NickName=device_name)
  115. uid_set_qs = UidSetModel.objects.filter(uid=device_info_qs[0].UID)
  116. if uid_set_qs.exists():
  117. uid_set_qs.update(nickname=device_name)
  118. if device_info_qs[0].Type == 201:
  119. cls.update_socket(serial_number=device_info_qs[0].serial_number, device_name=device_name,
  120. user_id=user_id)
  121. return response.json(0)
  122. @classmethod
  123. def my_family_list(cls, user_id, response):
  124. """
  125. 我的家庭列表
  126. @param user_id:
  127. @param response:
  128. @return:
  129. """
  130. user_family_qs = UserFamily.objects.filter(user_id=user_id).values()
  131. family_list = []
  132. if user_family_qs.exists():
  133. family_member_qs = FamilyMember.objects.filter(user_id=user_id, identity=1) \
  134. .order_by('sort').values('identity', 'family_id', 'family__name', 'permission_id', 'permission__no',
  135. 'family__location', 'user__username', 'user__userIconUrl')
  136. items = EquipmentFamilyView.family_info_list(family_member_qs)
  137. return response.json(0, items)
  138. return response.json(0, family_list)
  139. @classmethod
  140. def gateway_device_del(cls, user_id, request_dict, response):
  141. """
  142. 网关设备删除或删除子设备
  143. @param user_id:
  144. @param request_dict:
  145. @param response:
  146. @return:
  147. """
  148. device_id = request_dict.get('deviceId')
  149. family_id = request_dict.get('familyId')
  150. # 1 删除网关 否则删除子设备
  151. sub_ids = request_dict.get('subIds')
  152. if not family_id:
  153. return response.json(444)
  154. permission = EquipmentFamilyView.get_member_permission_details(user_id, family_id)
  155. if not permission or permission == '003':
  156. return response.json(404)
  157. try:
  158. with transaction.atomic():
  159. if device_id:
  160. device_qs = Device_Info.objects.filter(id=device_id)
  161. if device_qs.exists():
  162. family_device_qs = FamilyRoomDevice.objects.filter(device_id=device_id)
  163. if family_device_qs.exists():
  164. family_device_qs.delete()
  165. uid_set_qs = UidSetModel.objects.filter(uid=device_qs.first().UID)
  166. if uid_set_qs.exists():
  167. uid_set_qs.delete()
  168. socket_info_qs = SocketInfo.objects.filter(device_id=device_id)
  169. if socket_info_qs.exists():
  170. # 设备在不在线, 都发布重置
  171. serial_number = device_qs.first().serial_number
  172. cls.reset_device(serial_number)
  173. socket_info_qs.delete()
  174. socket_power_qs = SocketPowerStatistics.objects.filter(device_id=device_id)
  175. if socket_power_qs.exists():
  176. socket_power_qs.delete()
  177. socket_schedule_qs = SocketSchedule.objects.filter(device_id=device_id)
  178. if socket_schedule_qs.exists():
  179. socket_schedule_qs.delete()
  180. scene_log_qs = SceneLog.objects.filter(device_id=serial_number)
  181. if scene_log_qs.exists():
  182. scene_log_qs.delete()
  183. SmartSocketView.delete_alexa_socket(serial_number)
  184. # 如果有子设备,删除子设备和关联的场景数据
  185. gateway_qs = GatewaySubDevice.objects.filter(device_id=device_id)
  186. if gateway_qs.exists():
  187. sub_id_list = gateway_qs.values_list('id', flat=True)
  188. smart_scene_qs = SmartScene.objects.filter(
  189. Q(device_id=device_id) | Q(sub_device_id__in=sub_id_list))
  190. else:
  191. smart_scene_qs = SmartScene.objects.filter(device_id=device_id)
  192. if smart_scene_qs.exists():
  193. # 通知设备删除场景id
  194. smart_scene_info = smart_scene_qs.values('id')
  195. serial_number = device_qs.first().serial_number
  196. topic_name = SMART_SCENE_TOPIC.format(serial_number)
  197. for smart_scene in smart_scene_info:
  198. msg = {
  199. 'smart_scene_delete': int(smart_scene['id'])
  200. }
  201. success = CommonService.req_publish_mqtt_msg(serial_number, topic_name, msg)
  202. try:
  203. assert success
  204. except AssertionError:
  205. return response.json(10044)
  206. time.sleep(0.3)
  207. smart_scene_qs.delete()
  208. gateway_qs.delete() # 删除子设备
  209. scene_log_qs = SceneLog.objects.filter(device_id=device_id)
  210. if scene_log_qs.exists():
  211. scene_log_qs.delete()
  212. device_qs.delete()
  213. elif sub_ids:
  214. sub_ids = sub_ids.split(',')
  215. ids = []
  216. for item in sub_ids:
  217. sub_id = int(item)
  218. ids.append(sub_id)
  219. sub_device_qs = GatewaySubDevice.objects.filter(id=sub_id).values('device_type', 'src_addr',
  220. 'device__serial_number')
  221. serial_number = sub_device_qs[0]['device__serial_number']
  222. topic_name = SMART_SCENE_TOPIC.format(serial_number)
  223. device_type = sub_device_qs[0]['device_type']
  224. if device_type == 216: # 删除智能按钮通知设备
  225. msg = {
  226. 'sos_delete': int(sub_device_qs[0]['src_addr'], 16)
  227. }
  228. success = CommonService.req_publish_mqtt_msg(serial_number, topic_name, msg)
  229. try:
  230. assert success
  231. except AssertionError:
  232. return response.json(10044)
  233. time.sleep(0.3)
  234. family_device_qs = FamilyRoomDevice.objects.filter(sub_device__in=ids)
  235. if family_device_qs.exists():
  236. family_device_qs.delete()
  237. gateway_sub_qs = GatewaySubDevice.objects.filter(id__in=ids)
  238. if gateway_sub_qs.exists():
  239. gateway_sub_qs.delete()
  240. smart_scene_qs = SmartScene.objects.filter(sub_device_id__in=ids)
  241. if smart_scene_qs.exists():
  242. smart_scene_info = smart_scene_qs.values('id')
  243. for smart_scene in smart_scene_info:
  244. # 通知设备删除场景id
  245. msg = {
  246. 'smart_scene_delete': int(smart_scene['id'])
  247. }
  248. success = CommonService.req_publish_mqtt_msg(serial_number, topic_name, msg)
  249. try:
  250. assert success
  251. except AssertionError:
  252. return response.json(10044)
  253. time.sleep(0.3)
  254. smart_scene_qs.delete()
  255. scene_log_qs = SceneLog.objects.filter(sub_device_id__in=ids)
  256. if scene_log_qs.exists():
  257. scene_log_qs.delete()
  258. return response.json(0)
  259. except Exception as e:
  260. print(e)
  261. return response.json(177, repr(e))
  262. @staticmethod
  263. def reset_device(serial_number):
  264. """
  265. 下发消息到设备
  266. """
  267. try:
  268. thing_name = 'LC_' + serial_number
  269. if 'test' == CONFIG_INFO or CONFIG_INFO == 'cn':
  270. # 创建IoT客户端
  271. iot_data_plane = AWSIoTDataPlaneService(AWS_IOT_SES_ACCESS_CHINA_ID,
  272. AWS_IOT_SES_ACCESS_CHINA_SECRET,
  273. AWS_IOT_SES_ACCESS_CHINA_REGION)
  274. # 更新影子为离线状态
  275. data = {
  276. "state": {
  277. "reported": {
  278. "online": 0
  279. }
  280. }
  281. }
  282. res = iot_data_plane.update_thing_shadow(thing_name, data)
  283. LOGGER.info('删除插座更新设备影子状态{}'.format(res))
  284. # 下发设备进行重置
  285. SOCKET_TOPIC_NAME = 'loocam/smart-socket/{}' # 插座发布消息主题(因设备当前版本只能订阅一个主题)
  286. topic_name = SOCKET_TOPIC_NAME.format(serial_number)
  287. # 发布消息内容,重置设备
  288. msg = {'type': 6, 'data': {'device_reset': 1}}
  289. result = CommonService.req_publish_mqtt_msg(serial_number, topic_name, msg)
  290. LOGGER.info('重置{}智能插座设备,发布MQTT消息结果{}'.format(serial_number, result))
  291. return True
  292. except Exception as e:
  293. LOGGER.info('插座删除下发更改影子异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  294. return False
  295. @classmethod
  296. def gateway_device_list(cls, request_dict, response):
  297. """
  298. 网关设备列表
  299. @param request_dict:
  300. @param response:
  301. @return:
  302. """
  303. device_id = request_dict.get('deviceId', None)
  304. if not device_id:
  305. return response.json(444)
  306. device_qs = FamilyRoomDevice.objects.filter(device_id=device_id, sub_device=0)
  307. if not device_qs.exists():
  308. return response.json(173)
  309. try:
  310. device_qs = device_qs.values('family_id', 'device_id', 'room_id', 'device__Type', 'device__NickName',
  311. 'device__UID',
  312. 'device__serial_number')
  313. device_qs = device_qs.first()
  314. room_id = device_qs['room_id']
  315. family_id = device_qs['family_id']
  316. gateway_room_name = ''
  317. if room_id:
  318. room_qs = FamilyRoom.objects.filter(id=room_id)
  319. gateway_room_name = room_qs.first().name if room_qs.exists() else ''
  320. iot_device_info_qs = iotdeviceInfoModel.objects.filter(
  321. serial_number=device_qs['device__serial_number'][0:6])
  322. iot_data = {}
  323. if iot_device_info_qs.exists():
  324. iot_device_Info = iot_device_info_qs.values('endpoint', 'token_iot_number')
  325. iot_data = {
  326. 'endpoint': iot_device_Info[0]['endpoint'],
  327. 'token_iot_number': iot_device_Info[0]['token_iot_number']
  328. }
  329. gateway = {
  330. 'deviceId': device_qs['device_id'],
  331. 'deviceType': device_qs['device__Type'],
  332. 'deviceNickName': device_qs['device__NickName'],
  333. 'UID': device_qs['device__UID'],
  334. 'serialNumber': device_qs['device__serial_number'],
  335. 'roomName': gateway_room_name,
  336. 'iot': iot_data,
  337. 'roomId': room_id,
  338. 'familyId': family_id,
  339. 'power': 0,
  340. 'electricity': 0,
  341. 'countDownTime': 0,
  342. 'socketStatus': False,
  343. 'online': False,
  344. 'accumulatedTime': 0,
  345. 'start': False,
  346. }
  347. if device_qs['device__Type'] == 201:
  348. socket_info_qs = SocketInfo.objects.filter(device_id=device_id).values('online', 'type_switch',
  349. 'status',
  350. 'count_down_time', 'start')
  351. if not socket_info_qs.exists():
  352. return response.json(173)
  353. socket_data = cls.smart_socket(device_id, socket_info_qs)
  354. gateway = {key: socket_data.get(key, gateway[key]) for key in gateway.keys()}
  355. family_device_qs = FamilyRoomDevice.objects.filter(device_id=device_id)
  356. family_device_qs = family_device_qs.filter(~Q(sub_device=0)).order_by('-created_time')
  357. sub_device = []
  358. sub_id_list = []
  359. if family_device_qs.exists():
  360. family_device_qs = family_device_qs.values()
  361. for item in family_device_qs:
  362. sub_id = item['sub_device']
  363. sub_id_list.append(sub_id)
  364. gateway_sub_qs = GatewaySubDevice.objects.filter(device_id=device_id, id=sub_id).values(
  365. 'id', 'device_type',
  366. 'nickname',
  367. 'src_addr', 'status',
  368. 'created_time', 'ieee_addr')
  369. if not gateway_sub_qs.exists():
  370. continue
  371. room_id = item['room_id']
  372. room_qs = FamilyRoom.objects.filter(id=room_id)
  373. gateway_room_name = room_qs.first().name if room_qs.exists() else ''
  374. gateway_sub_qs = gateway_sub_qs.first()
  375. sub_device.append({
  376. 'gatewaySubId': gateway_sub_qs['id'],
  377. 'nickName': gateway_sub_qs['nickname'],
  378. 'deviceType': gateway_sub_qs['device_type'],
  379. 'srcAddr': gateway_sub_qs['src_addr'],
  380. 'status': gateway_sub_qs['status'],
  381. 'createdTime': gateway_sub_qs['created_time'],
  382. 'roomName': gateway_room_name,
  383. 'roomId': room_qs.first().id if room_qs.exists() else 0,
  384. 'ieeeAddr': gateway_sub_qs['ieee_addr'],
  385. 'familyId': family_id,
  386. })
  387. scene_count = SmartScene.objects.filter(Q(device_id=device_id) | Q(sub_device_id__in=sub_id_list)).count()
  388. res = {'gateway': gateway, 'sub_device': sub_device, 'sub_device_count': len(sub_device),
  389. 'scene_count': scene_count}
  390. return response.json(0, res)
  391. except Exception as e:
  392. print(e.args)
  393. return response.json(500)
  394. @classmethod
  395. def smart_socket(cls, device_id, socket_info_qs):
  396. """
  397. 查詢插座信息
  398. """
  399. nowTime = int(time.time())
  400. today = datetime.date.today()
  401. # 今天开始时间
  402. today_start_time = int(time.mktime(time.strptime(str(today), '%Y-%m-%d')))
  403. data = {
  404. 'power': 0,
  405. 'electricity': 0,
  406. 'countDownTime': 0,
  407. 'accumulatedTime': 0,
  408. 'socketStatus': False,
  409. 'online': False,
  410. 'start': False,
  411. }
  412. # 插座信息
  413. socket_info_qs = socket_info_qs.filter(device_id=device_id).values('online', 'type_switch',
  414. 'status', 'count_down_time', 'start')
  415. type_switch_list = [type_switch[v] for type_switch in socket_info_qs.values('type_switch') for v in type_switch]
  416. # 判断开关类型 0:总开关,1:倒计时开关
  417. if len(type_switch_list) == 2:
  418. socket_info_qs = socket_info_qs.filter(type_switch=1)
  419. else:
  420. socket_info_qs = socket_info_qs.filter(type_switch=0)
  421. # 插座信息
  422. data['socketStatus'] = socket_info_qs[0]['status']
  423. data['start'] = socket_info_qs[0]['start']
  424. data['online'] = socket_info_qs[0]['online']
  425. data['countDownTime'] = socket_info_qs[0]['count_down_time'] if socket_info_qs[0][
  426. 'count_down_time'] else 0
  427. # 当前设备电量信息
  428. socket_power_qs = SocketPowerStatistics.objects.filter(device_id=device_id, created_time__gte=today_start_time,
  429. created_time__lt=nowTime).values('accumulated_time',
  430. 'power',
  431. 'created_time',
  432. 'electricity'). \
  433. order_by('-created_time')
  434. if not socket_power_qs.exists():
  435. return data
  436. data['power'] = round(socket_power_qs[0]['power'], 1)
  437. data['electricity'] = round(socket_power_qs[0]['electricity'], 1)
  438. data['accumulatedTime'] = socket_power_qs[0]['accumulated_time']
  439. return data
  440. @classmethod
  441. def bind_serial_user(cls, user_id, request_dict, response):
  442. """
  443. 绑定网关序列号和用户id
  444. @param user_id: 用户id
  445. @param request_dict: 请求参数字典
  446. @param response: 响应对象
  447. @return:
  448. """
  449. serial_number = request_dict.get('serialNumber')
  450. if not serial_number:
  451. return response.json(444)
  452. try:
  453. redis_obj = RedisObject()
  454. result = redis_obj.set_data(user_id, serial_number, 300)
  455. if not result:
  456. return response.json(178)
  457. return response.json(0)
  458. except Exception as e:
  459. print(e)
  460. return response.json(177, repr(e))
  461. @classmethod
  462. def get_serial_user(cls, user_id, request_dict, response):
  463. """
  464. 获取用户id绑定网关序列号
  465. @param user_id: 用户id
  466. @param request_dict: 请求参数字典
  467. @param response: 响应对象
  468. @return:
  469. """
  470. try:
  471. redis_obj = RedisObject()
  472. serial_number = redis_obj.get_data(user_id)
  473. if not serial_number:
  474. return response.json(173)
  475. return response.json(0, {'serialNumber': serial_number})
  476. except Exception as e:
  477. print(e)
  478. return response.json(177, repr(e))
  479. @classmethod
  480. def update_socket(cls, serial_number, device_name, user_id):
  481. url = 'https://www.zositech.xyz/deviceStatus/addOrUpdateSwitch'
  482. try:
  483. data = {
  484. 'nick_name': device_name,
  485. 'serial_number': serial_number,
  486. 'user_id': user_id,
  487. }
  488. requests.post(url=url, data=data, timeout=5)
  489. except Exception as e:
  490. print(repr(e))
  491. #
  492. # ___====-_ _-====___
  493. # _--^^^#####// \\#####^^^--_
  494. # _-^##########// ( ) \\##########^-_
  495. # -############// |\^^/| \\############-
  496. # _/############// (@::@) \\############\_
  497. # /#############(( \\// ))#############\
  498. # -###############\\ (oo) //###############-
  499. # -#################\\ / VV \ //#################-
  500. # -###################\\/ \//###################-
  501. # _#/|##########/\######( /\ )######/\##########|\#_
  502. # |/ |#/\#/\#/\/ \#/\##\ | | /##/\#/ \/\#/\#/\#| \|
  503. # ` |/ V V ` V \#\| | | |/#/ V ' V V \| '
  504. # ` ` ` ` / | | | | \ ' ' ' '
  505. # ( | | | | )
  506. # __\ | | | | /__
  507. # (vvv(VVV)(VVV)vvv)
  508. # 神兽保佑
  509. # 代码无BUG!
  510. #