gatewayController.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. # -*- coding: utf-8 -*-
  2. """
  3. @Author : Rocky
  4. @Time : 2022/5/9 10:51
  5. @File :gatewayController.py
  6. """
  7. import logging
  8. import time
  9. from django.views.generic.base import View
  10. from AnsjerPush.Config.gatewaySensorConfig import SENSOR_TYPE, EVENT_TYPE
  11. from Model.models import SensorRecord, GatewaySubDevice, GatewayPush, Device_Info, SceneLog, SmartScene
  12. from Object.ResponseObject import ResponseObject
  13. from Object.utils import LocalDateTimeUtil
  14. from Service.CommonService import CommonService
  15. from Service.EquipmentInfoService import EquipmentInfoService
  16. from Service.HuaweiPushService.HuaweiPushService import HuaweiPushObject
  17. from Service.PushService import PushObject
  18. class GatewayView(View):
  19. def get(self, request, *args, **kwargs):
  20. request.encoding = 'utf-8'
  21. operation = kwargs.get('operation')
  22. return self.validation(request.GET, operation)
  23. def post(self, request, *args, **kwargs):
  24. request.encoding = 'utf-8'
  25. operation = kwargs.get('operation')
  26. return self.validation(request.POST, operation)
  27. def validation(self, request_dict, operation):
  28. response = ResponseObject()
  29. if operation == 'gatewayPush': # 网关推送
  30. return self.gateway_push(request_dict, response)
  31. elif operation == 'sceneLogPush': # 场景日志推送
  32. return self.scene_log_push(request_dict, response)
  33. else:
  34. return response.json(414)
  35. @staticmethod
  36. def gateway_push(request_dict, response):
  37. """
  38. 网关推送
  39. @param request_dict: 请求参数
  40. @request_dict serial_number: 序列号
  41. @request_dict ieee_addr: 长地址
  42. @request_dict src_addr: 短地址
  43. @request_dict sensor_type: 传感器类型
  44. @request_dict event_type: 事件类型
  45. @request_dict alarm: 消息内容
  46. @request_dict defense: 防御状态,0:撤防,1:防御
  47. @request_dict sensor_status: 拆动状态,拆动时传参
  48. @param response: 响应对象
  49. @return: response
  50. """
  51. logger = logging.getLogger('info')
  52. serial_number = request_dict.get('serial_number', None)
  53. ieee_addr = request_dict.get('ieee_addr', None)
  54. src_addr = request_dict.get('src_addr', None)
  55. sensor_type = int(request_dict.get('sensor_type', None))
  56. event_type = int(request_dict.get('event_type', None))
  57. alarm = request_dict.get('alarm', None)
  58. defense = int(request_dict.get('defense', None))
  59. sensor_status = request_dict.get('sensor_status', None)
  60. logger.info('---调用网关推送接口--- request_dict:{}'.format(request_dict))
  61. if not all([serial_number, ieee_addr, src_addr, sensor_type, event_type, alarm]):
  62. return response.json(444)
  63. n_time = int(time.time())
  64. try:
  65. # 查询子设备表id
  66. gateway_sub_device_qs = GatewaySubDevice.objects.filter(device__serial_number=serial_number,
  67. device_type=sensor_type, ieee_addr=ieee_addr,
  68. src_addr=src_addr).values('id', 'nickname')
  69. if not gateway_sub_device_qs.exists():
  70. return response.json(173)
  71. else:
  72. gateway_sub_device_id = gateway_sub_device_qs[0]['id']
  73. nickname = gateway_sub_device_qs[0]['nickname']
  74. sensor_record_dict = {
  75. 'gateway_sub_device_id': gateway_sub_device_id,
  76. 'alarm': alarm,
  77. 'event_type': event_type,
  78. 'created_time': n_time,
  79. }
  80. # 处理温湿度,不推送
  81. if sensor_type == SENSOR_TYPE['tem_hum_sensor'] and (
  82. event_type == EVENT_TYPE['temperature'] or event_type == EVENT_TYPE['humidity']):
  83. num = request_dict.get('num', None)
  84. num = str(int(num) / 100)
  85. sensor_record_dict['alarm'] = num
  86. SensorRecord.objects.create(**sensor_record_dict)
  87. return response.json(0)
  88. SensorRecord.objects.create(**sensor_record_dict)
  89. # (门磁,烟雾,人体)传感器被拆动/拆动恢复,修改拆动状态
  90. if sensor_status:
  91. if sensor_type != SENSOR_TYPE['smart_button']: # 智能按钮不更新
  92. gateway_sub_device_qs.update(is_tampered=1)
  93. elif sensor_type == SENSOR_TYPE['door_magnet'] or sensor_type == SENSOR_TYPE['smoke_sensor'] or \
  94. sensor_type == SENSOR_TYPE['body_sensor']:
  95. gateway_sub_device_qs.update(is_tampered=0)
  96. # 撤防状态不推送
  97. if defense == 0:
  98. return response.json(0)
  99. device_info_qs = Device_Info.objects.filter(serial_number=serial_number).values('userID_id')
  100. if not device_info_qs.exists():
  101. return response.json(173)
  102. equipment_info_list = []
  103. for device_info in device_info_qs:
  104. user_id = device_info['userID_id']
  105. # 组织存储数据
  106. local_date_time = CommonService.get_now_time_str(n_time=n_time, tz=0, lang='cn')[:10]
  107. equipment_info_list.append(EquipmentInfoService.get_equipment_info_obj(
  108. local_date_time,
  109. add_time=n_time,
  110. event_time=n_time,
  111. receive_time=n_time,
  112. device_uid=serial_number,
  113. device_nick_name=nickname,
  114. alarm=alarm,
  115. event_type=event_type,
  116. device_user_id=user_id,
  117. ))
  118. if equipment_info_list:
  119. # 根据日期获得星期几
  120. week = LocalDateTimeUtil.date_to_week(local_date_time)
  121. EquipmentInfoService.equipment_info_bulk_create(week, equipment_info_list)
  122. # 查询推送配置数据
  123. gateway_push_qs = GatewayPush.objects.filter(user_id=user_id, logout=False). \
  124. values('user_id', 'app_bundle_id', 'app_type', 'push_type', 'token_val', 'm_code', 'lang', 'm_code',
  125. 'tz')
  126. if not gateway_push_qs.exists():
  127. continue
  128. kwargs = {
  129. 'n_time': n_time,
  130. 'event_type': event_type,
  131. 'nickname': nickname,
  132. }
  133. # 推送到每台登录账号的手机
  134. for gateway_push in gateway_push_qs:
  135. app_bundle_id = gateway_push['app_bundle_id']
  136. push_type = gateway_push['push_type']
  137. token_val = gateway_push['token_val']
  138. lang = gateway_push['lang']
  139. tz = gateway_push['tz'] if gateway_push['tz'] else 0
  140. # 获取推送所需数据
  141. msg_title = PushObject.get_msg_title(nickname)
  142. msg_text = PushObject.get_gateway_msg_text(n_time, tz, lang, alarm)
  143. kwargs['msg_title'] = msg_title
  144. kwargs['msg_text'] = msg_text
  145. kwargs['app_bundle_id'] = app_bundle_id
  146. kwargs['token_val'] = token_val
  147. try:
  148. # 推送消息
  149. if push_type == 0: # ios apns
  150. PushObject.ios_apns_push(**kwargs)
  151. elif push_type == 1: # android gcm
  152. PushObject.android_fcm_push(**kwargs)
  153. elif push_type == 2: # android 极光推送
  154. PushObject.android_jpush(**kwargs)
  155. elif push_type == 3:
  156. huawei_push_object = HuaweiPushObject()
  157. huawei_push_object.send_push_notify_message(**kwargs)
  158. elif push_type == 4: # android 小米推送
  159. PushObject.android_xmpush(**kwargs)
  160. elif push_type == 5: # android vivo推送
  161. PushObject.android_vivopush(**kwargs)
  162. elif push_type == 6: # android oppo推送
  163. PushObject.android_oppopush(**kwargs)
  164. elif push_type == 7: # android 魅族推送
  165. PushObject.android_meizupush(**kwargs)
  166. except Exception as e:
  167. logger.info('网关推送消息异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  168. continue
  169. return response.json(0)
  170. except Exception as e:
  171. logger.info('---网关推送接口异常--- {}'.format(repr(e)))
  172. return response.json(500, repr(e))
  173. @staticmethod
  174. def scene_log_push(request_dict, response):
  175. """
  176. 网关智能场景日志推送
  177. @param request_dict: 请求参数
  178. @request_dict sceneId: 场景id
  179. @request_dict status: 状态
  180. @param response: 响应对象
  181. @return: response
  182. """
  183. logger = logging.getLogger('info')
  184. scene_id = request_dict.get('sceneId', None)
  185. status = request_dict.get('status', None)
  186. logger.info('---场景日志推送接口--- request_dict:{}'.format(request_dict))
  187. if not all([scene_id, status]):
  188. return response.json(444)
  189. smart_scene_qs = SmartScene.objects.filter(id=scene_id).values('scene_name', 'conditions', 'tasks', 'device_id',
  190. 'sub_device_id', 'user_id')
  191. if not smart_scene_qs.exists():
  192. return response.json(173)
  193. scene_name = smart_scene_qs[0]['scene_name']
  194. tasks = smart_scene_qs[0]['tasks']
  195. device_id = smart_scene_qs[0]['device_id']
  196. sub_device_id = smart_scene_qs[0]['sub_device_id']
  197. n_time = int(time.time())
  198. user_id = smart_scene_qs[0]['user_id']
  199. if sub_device_id:
  200. gateway_sub_device_qs = GatewaySubDevice.objects.filter(id=sub_device_id).values('nickname')
  201. nickname = gateway_sub_device_qs[0]['nickname'] if gateway_sub_device_qs.exists() else ''
  202. else:
  203. device_qs = Device_Info.objects.filter(id=device_id).values('NickName')
  204. nickname = device_qs[0]['NickName'] if device_qs.exists() else ''
  205. log_dict = {
  206. 'scene_id': scene_id,
  207. 'scene_name': scene_name,
  208. 'tasks': tasks,
  209. 'status': status,
  210. 'device_id': device_id,
  211. 'sub_device_id': sub_device_id,
  212. 'created_time': n_time,
  213. }
  214. tasks = eval(tasks)
  215. try:
  216. SceneLog.objects.create(**log_dict)
  217. # 推送日志
  218. gateway_push_qs = GatewayPush.objects.filter(user_id=user_id, logout=False). \
  219. values('user_id', 'app_bundle_id', 'app_type', 'push_type', 'token_val', 'm_code', 'lang', 'm_code',
  220. 'tz')
  221. if not gateway_push_qs.exists():
  222. return response.json(174)
  223. for task in tasks:
  224. event_type = task['event_type']
  225. if event_type == '1001':
  226. kwargs = {
  227. 'n_time': n_time,
  228. 'event_type': event_type,
  229. 'nickname': nickname,
  230. }
  231. event_info = task['value']
  232. # 推送到每台登录账号的手机
  233. for gateway_push in gateway_push_qs:
  234. app_bundle_id = gateway_push['app_bundle_id']
  235. push_type = gateway_push['push_type']
  236. token_val = gateway_push['token_val']
  237. kwargs['msg_title'] = PushObject.get_msg_title(nickname)
  238. kwargs['msg_text'] = event_info
  239. kwargs['app_bundle_id'] = app_bundle_id
  240. kwargs['token_val'] = token_val
  241. try:
  242. # 推送消息
  243. if push_type == 0: # ios apns
  244. PushObject.ios_apns_push(**kwargs)
  245. elif push_type == 1: # android gcm
  246. PushObject.android_fcm_push(**kwargs)
  247. elif push_type == 2: # android 极光推送
  248. PushObject.android_jpush(**kwargs)
  249. elif push_type == 3:
  250. huawei_push_object = HuaweiPushObject()
  251. huawei_push_object.send_push_notify_message(**kwargs)
  252. elif push_type == 4: # android 小米推送
  253. PushObject.android_xmpush(**kwargs)
  254. elif push_type == 5: # android vivo推送
  255. PushObject.android_vivopush(**kwargs)
  256. elif push_type == 6: # android oppo推送
  257. PushObject.android_oppopush(**kwargs)
  258. elif push_type == 7: # android 魅族推送
  259. PushObject.android_meizupush(**kwargs)
  260. except Exception as e:
  261. logger.info('场景日志推送消息异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  262. continue
  263. return response.json(0)
  264. except Exception as e:
  265. logger.info('---场景日志推送接口异常--- {}'.format(repr(e)))
  266. return response.json(500, repr(e))