gatewayController.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. # -*- coding: utf-8 -*-
  2. """
  3. @Author : Rocky
  4. @Time : 2022/5/9 10:51
  5. @File :gatewayController.py
  6. """
  7. import time
  8. from django.views.generic.base import View
  9. from AnsjerPush.Config.gatewaySensorConfig import SENSOR_TYPE, EVENT_TYPE
  10. from AnsjerPush.config import LOGGER, XM_PUSH_CHANNEL_ID
  11. from Model.models import SensorRecord, GatewaySubDevice, GatewayPush, Device_Info, SceneLog, SmartScene, CountryModel
  12. from Object.RedisObject import RedisObject
  13. from Object.ResponseObject import ResponseObject
  14. from Service.EquipmentInfoService import EquipmentInfoService
  15. from Service.HuaweiPushService.HuaweiPushService import HuaweiPushObject
  16. from Service.PushService import PushObject
  17. class GatewayView(View):
  18. def get(self, request, *args, **kwargs):
  19. request.encoding = 'utf-8'
  20. operation = kwargs.get('operation')
  21. return self.validation(request.GET, operation)
  22. def post(self, request, *args, **kwargs):
  23. request.encoding = 'utf-8'
  24. operation = kwargs.get('operation')
  25. return self.validation(request.POST, operation)
  26. def validation(self, request_dict, operation):
  27. response = ResponseObject()
  28. if operation == 'gatewayPush': # 网关推送
  29. return self.gateway_push(request_dict, response)
  30. elif operation == 'sceneLogPush': # 场景日志推送
  31. return self.scene_log_push(request_dict, response)
  32. elif operation == 'socketPush': # 插座推送
  33. return self.socket_msg_push(request_dict, response)
  34. else:
  35. return response.json(414)
  36. @classmethod
  37. def gateway_push(cls, request_dict, response):
  38. """
  39. 网关推送
  40. @param request_dict: 请求参数
  41. @request_dict serial_number: 序列号
  42. @request_dict ieee_addr: 长地址
  43. @request_dict sensor_type: 传感器类型
  44. @request_dict event_type: 事件类型
  45. @request_dict defense: 防御状态,0:撤防,1:防御
  46. @request_dict sensor_status: 拆动状态,拆动时传参
  47. @param response: 响应对象
  48. @return: response
  49. """
  50. serial_number = request_dict.get('serial_number', None)
  51. ieee_addr = request_dict.get('ieee_addr', None)
  52. sensor_type = int(request_dict.get('sensor_type', None))
  53. event_type = int(request_dict.get('event_type', None))
  54. defense = int(request_dict.get('defense', None))
  55. LOGGER.info('---调用网关推送接口--- request_dict:{}'.format(request_dict))
  56. if not all([serial_number, ieee_addr, sensor_type, event_type]):
  57. return response.json(444)
  58. n_time = int(time.time())
  59. try:
  60. # 查询子设备表id
  61. gateway_sub_device_qs = GatewaySubDevice.objects.filter(device__serial_number=serial_number,
  62. device_type=sensor_type, ieee_addr=ieee_addr). \
  63. values('id', 'nickname', 'device__userID__region_country')
  64. if not gateway_sub_device_qs.exists():
  65. return response.json(173)
  66. country_id = gateway_sub_device_qs[0]['device__userID__region_country']
  67. lang = cls.confirm_lang(country_id)
  68. alarm = cls.get_alarm(lang, event_type)
  69. gateway_sub_device_id = gateway_sub_device_qs[0]['id']
  70. nickname = gateway_sub_device_qs[0]['nickname']
  71. sensor_record_dict = {
  72. 'gateway_sub_device_id': gateway_sub_device_id,
  73. 'alarm': alarm,
  74. 'event_type': event_type,
  75. 'created_time': n_time,
  76. }
  77. # 处理温湿度,不推送
  78. if sensor_type == SENSOR_TYPE['tem_hum_sensor'] and (
  79. event_type == EVENT_TYPE['temperature'] or event_type == EVENT_TYPE['humidity']):
  80. num = request_dict.get('num', None)
  81. num = str(int(num) / 100)
  82. sensor_record_dict['alarm'] = num
  83. SensorRecord.objects.create(**sensor_record_dict)
  84. return response.json(0)
  85. SensorRecord.objects.create(**sensor_record_dict)
  86. # 门磁被拆动/拆动恢复,修改拆动状态
  87. if event_type == 2156:
  88. gateway_sub_device_qs.update(is_tampered=1)
  89. elif event_type == 2152:
  90. gateway_sub_device_qs.update(is_tampered=0)
  91. # 撤防状态不推送
  92. if defense == 0:
  93. return response.json(0)
  94. device_info_qs = Device_Info.objects.filter(serial_number=serial_number).values('userID_id')
  95. if not device_info_qs.exists():
  96. return response.json(173)
  97. equipment_info_list = []
  98. equipment_info_model = EquipmentInfoService.randoms_choice_equipment_info()
  99. # 推送表存储数据
  100. equipment_info_kwargs = {
  101. 'device_uid': serial_number,
  102. 'device_nick_name': nickname,
  103. 'event_type': event_type,
  104. 'event_time': n_time,
  105. 'add_time': n_time,
  106. 'alarm': alarm
  107. }
  108. for device_info in device_info_qs:
  109. user_id = device_info['userID_id']
  110. equipment_info_kwargs['device_user_id'] = user_id
  111. equipment_info_list.append(equipment_info_model(**equipment_info_kwargs))
  112. # 查询推送配置数据
  113. gateway_push_qs = GatewayPush.objects.filter(user_id=user_id, logout=False). \
  114. values('user_id', 'app_bundle_id', 'app_type', 'push_type', 'token_val', 'm_code', 'lang', 'm_code',
  115. 'tz')
  116. if not gateway_push_qs.exists():
  117. continue
  118. kwargs = {
  119. 'n_time': n_time,
  120. 'event_type': event_type,
  121. 'nickname': nickname,
  122. }
  123. # 推送到每台登录账号的手机
  124. for gateway_push in gateway_push_qs:
  125. app_bundle_id = gateway_push['app_bundle_id']
  126. push_type = gateway_push['push_type']
  127. token_val = gateway_push['token_val']
  128. lang = gateway_push['lang']
  129. tz = gateway_push['tz'] if gateway_push['tz'] else 0
  130. # 获取推送所需数据
  131. msg_title = PushObject.get_msg_title(nickname)
  132. msg_text = PushObject.get_gateway_msg_text(n_time, tz, lang, alarm)
  133. kwargs['msg_title'] = msg_title
  134. kwargs['msg_text'] = msg_text
  135. kwargs['app_bundle_id'] = app_bundle_id
  136. kwargs['token_val'] = token_val
  137. try:
  138. # 推送消息
  139. cls.push_msg(push_type, **kwargs)
  140. except Exception as e:
  141. LOGGER.info('网关推送消息异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  142. continue
  143. if equipment_info_list:
  144. equipment_info_model.objects.bulk_create(equipment_info_list)
  145. return response.json(0)
  146. except Exception as e:
  147. LOGGER.info('---网关推送接口异常--- {}'.format(repr(e)))
  148. return response.json(500, 'error_ine:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  149. @staticmethod
  150. def confirm_lang(country_id):
  151. """
  152. 根据country_id确定语言
  153. @param country_id: 国家id
  154. @return lang: 语言
  155. """
  156. country_qs = CountryModel.objects.filter(id=country_id).values('country_code')
  157. if not country_qs.exists():
  158. lang = 'NA'
  159. else:
  160. lang = country_qs[0]['country_code']
  161. return lang
  162. @staticmethod
  163. def get_alarm(lang, event_type):
  164. """
  165. 根据语言和事件类型确定警报内容
  166. @param lang: 语言
  167. @param event_type: 事件类型
  168. @return alarm: 警报内容
  169. """
  170. alarm = ''
  171. if lang == 'CN':
  172. # 门磁
  173. if event_type == 2150:
  174. alarm = '门磁开'
  175. elif event_type == 2151:
  176. alarm = '门磁关'
  177. elif event_type == 2156:
  178. alarm = '被拆动'
  179. elif event_type == 2152:
  180. alarm = '拆动恢复'
  181. # 智能按钮
  182. elif event_type == 2160:
  183. alarm = '紧急按钮按下'
  184. elif event_type == 2161:
  185. alarm = '单击'
  186. elif event_type == 2162:
  187. alarm = '双击'
  188. elif event_type == 2163:
  189. alarm = '长按'
  190. # 水浸
  191. elif event_type == 2170:
  192. alarm = '水浸触发'
  193. elif event_type == 2171:
  194. alarm = '水浸恢复'
  195. # 烟雾
  196. elif event_type == 2180:
  197. alarm = '烟雾触发'
  198. elif event_type == 2181:
  199. alarm = '烟雾恢复'
  200. # 人体红外
  201. elif event_type == 2190:
  202. alarm = '有人移动'
  203. elif event_type == 2191:
  204. alarm = '无人移动'
  205. # 低电量
  206. elif event_type in (2153, 2164, 2172, 2182, 2193):
  207. alarm = '低电量'
  208. else:
  209. # 门磁
  210. if event_type == 2150:
  211. alarm = 'Door magnetic opening'
  212. elif event_type == 2151:
  213. alarm = 'Door magnetic closing'
  214. elif event_type == 2156:
  215. alarm = 'Be dismantled'
  216. elif event_type == 2152:
  217. alarm = 'Dismantling recovery'
  218. # 智能按钮
  219. elif event_type == 2160:
  220. alarm = 'Emergency button pressed'
  221. elif event_type == 2161:
  222. alarm = 'Single click'
  223. elif event_type == 2162:
  224. alarm = 'Double click'
  225. elif event_type == 2163:
  226. alarm = 'Long press'
  227. # 水浸
  228. elif event_type == 2170:
  229. alarm = 'Water immersion trigger'
  230. elif event_type == 2171:
  231. alarm = 'Water immersion recovery'
  232. # 烟雾
  233. elif event_type == 2180:
  234. alarm = 'Smoke triggering'
  235. elif event_type == 2181:
  236. alarm = 'Smoke recovery'
  237. # 人体红外
  238. elif event_type == 2190:
  239. alarm = 'Someone moving'
  240. elif event_type == 2191:
  241. alarm = 'Unmanned movement'
  242. # 低电量
  243. elif event_type in (2153, 2164, 2172, 2182, 2193):
  244. alarm = 'LOW BATTERY'
  245. return alarm
  246. @classmethod
  247. def scene_log_push(cls, request_dict, response):
  248. """
  249. 网关智能场景日志推送
  250. @param request_dict: 请求参数
  251. @request_dict sceneId: 场景id
  252. @request_dict status: 状态
  253. @param response: 响应对象
  254. @return: response
  255. """
  256. scene_id = request_dict.get('sceneId', None)
  257. status = request_dict.get('status', None)
  258. # 防止定时任务同时请求生成多条场景日志
  259. redis_obj = RedisObject()
  260. key = scene_id + 'scene_log_limit'
  261. is_lock = redis_obj.CONN.setnx(key, 1)
  262. redis_obj.CONN.expire(key, 60)
  263. if not is_lock:
  264. return response.json(0)
  265. LOGGER.info('---场景日志推送接口--- request_dict:{}'.format(request_dict))
  266. if not all([scene_id, status]):
  267. return response.json(444)
  268. smart_scene_qs = SmartScene.objects.filter(id=scene_id).values('scene_name', 'conditions', 'tasks', 'device_id',
  269. 'sub_device_id', 'user_id', 'scene_data')
  270. if not smart_scene_qs.exists():
  271. return response.json(173)
  272. scene_name = smart_scene_qs[0]['scene_name']
  273. tasks = smart_scene_qs[0]['tasks']
  274. device_id = smart_scene_qs[0]['device_id']
  275. sub_device_id = smart_scene_qs[0]['sub_device_id']
  276. n_time = int(time.time())
  277. user_id = smart_scene_qs[0]['user_id']
  278. scene_data = smart_scene_qs[0]['scene_data']
  279. if sub_device_id:
  280. gateway_sub_device_qs = GatewaySubDevice.objects.filter(id=sub_device_id).values('nickname')
  281. nickname = gateway_sub_device_qs[0]['nickname'] if gateway_sub_device_qs.exists() else ''
  282. else:
  283. device_qs = Device_Info.objects.filter(id=device_id).values('NickName')
  284. nickname = device_qs[0]['NickName'] if device_qs.exists() else ''
  285. log_dict = {
  286. 'scene_id': scene_id,
  287. 'scene_name': scene_name,
  288. 'tasks': tasks,
  289. 'status': status,
  290. 'device_id': device_id,
  291. 'sub_device_id': sub_device_id,
  292. 'created_time': n_time,
  293. }
  294. tasks = eval(tasks)
  295. try:
  296. SceneLog.objects.create(**log_dict)
  297. # 如果是一次性场景,关闭场景
  298. if scene_data:
  299. scene_data_dict = eval(scene_data)
  300. condition = scene_data_dict.get('condition')
  301. if condition:
  302. time_type = condition.get('time')
  303. if time_type == 'date':
  304. smart_scene_qs.update(is_enable=False)
  305. # 推送日志
  306. gateway_push_qs = GatewayPush.objects.filter(user_id=user_id, logout=False). \
  307. values('user_id', 'app_bundle_id', 'app_type', 'push_type', 'token_val', 'm_code', 'lang', 'm_code',
  308. 'tz')
  309. if not gateway_push_qs.exists():
  310. return response.json(174)
  311. for task in tasks:
  312. event_type = task['event_type']
  313. if event_type == '1001':
  314. kwargs = {
  315. 'n_time': n_time,
  316. 'event_type': event_type,
  317. 'nickname': nickname,
  318. }
  319. event_info = task['value']
  320. # 推送到每台登录账号的手机
  321. for gateway_push in gateway_push_qs:
  322. app_bundle_id = gateway_push['app_bundle_id']
  323. push_type = gateway_push['push_type']
  324. token_val = gateway_push['token_val']
  325. kwargs['msg_title'] = PushObject.get_msg_title(nickname)
  326. kwargs['msg_text'] = event_info
  327. kwargs['app_bundle_id'] = app_bundle_id
  328. kwargs['token_val'] = token_val
  329. try:
  330. # 推送消息
  331. cls.push_msg(push_type, **kwargs)
  332. except Exception as e:
  333. LOGGER.info(
  334. '场景日志推送消息异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  335. continue
  336. return response.json(0)
  337. except Exception as e:
  338. LOGGER.info('---场景日志推送接口异常--- {}'.format(repr(e)))
  339. return response.json(500, 'error_ine:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  340. @staticmethod
  341. def push_msg(push_type, **kwargs):
  342. """
  343. 发送推送消息
  344. @param push_type: 推送类型
  345. @param kwargs: 推送参数
  346. @return: None
  347. """
  348. if push_type == 0: # ios apns
  349. PushObject.ios_apns_push(**kwargs)
  350. elif push_type == 1: # android gcm
  351. PushObject.android_fcm_push(**kwargs)
  352. elif push_type == 2: # android 极光推送
  353. PushObject.android_jpush(**kwargs)
  354. elif push_type == 3:
  355. huawei_push_object = HuaweiPushObject()
  356. huawei_push_object.send_push_notify_message(**kwargs)
  357. elif push_type == 4: # android 小米推送
  358. channel_id = XM_PUSH_CHANNEL_ID['device_reminder']
  359. PushObject.android_xmpush(channel_id=channel_id, **kwargs)
  360. elif push_type == 5: # android vivo推送
  361. PushObject.android_vivopush(**kwargs)
  362. elif push_type == 6: # android oppo推送
  363. channel_id = 'DEVICE_REMINDER'
  364. PushObject.android_oppopush(channel_id=channel_id, **kwargs)
  365. elif push_type == 7: # android 魅族推送
  366. PushObject.android_meizupush(**kwargs)
  367. @classmethod
  368. def socket_msg_push(cls, request_dict, response):
  369. """
  370. 智能插座开关状态推送
  371. """
  372. try:
  373. serial_number = request_dict.get('serialNumber', None)
  374. device_time = request_dict.get('deviceTime', None)
  375. status = request_dict.get('status', None)
  376. if not all([serial_number, status, device_time]):
  377. return response.json(444)
  378. status = int(status)
  379. now_time = int(device_time) if device_time else int(time.time())
  380. # 获取主用户设备id
  381. log_dict = {
  382. 'status': status,
  383. 'device_id': serial_number,
  384. 'created_time': now_time,
  385. }
  386. SceneLog.objects.create(**log_dict)
  387. LOGGER.info('成功接收并保存,插座序列号{},状态:{}'.format(serial_number, status))
  388. return response.json(0)
  389. except Exception as e:
  390. print(repr(e))
  391. LOGGER.info('---插座开关日志推送接口异常--- {}'.format(repr(e)))
  392. return response.json(500, repr(e))