gatewayController.py 15 KB

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