gatewayController.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. # -*- coding: utf-8 -*-
  2. """
  3. @Author : Rocky
  4. @Time : 2022/5/9 10:51
  5. @File :gatewayController.py
  6. """
  7. import datetime
  8. import threading
  9. import time
  10. import pytz
  11. import requests
  12. from django.views.generic.base import View
  13. from AnsjerPush.Config.gatewaySensorConfig import SENSOR_TYPE, EVENT_TYPE, DEVICE_TYPE, SMART_SOCKET_TOPIC
  14. from AnsjerPush.config import LOGGER, XM_PUSH_CHANNEL_ID
  15. from Model.models import SensorRecord, GatewaySubDevice, GatewayPush, Device_Info, SceneLog, SmartScene, CountryModel, \
  16. EffectiveTime
  17. from Object.RedisObject import RedisObject
  18. from Object.ResponseObject import ResponseObject
  19. from Service.CommonService import CommonService
  20. from AnsjerPush.config import DETECT_PUSH_DOMAIN
  21. from Service.EquipmentInfoService import EquipmentInfoService
  22. from Service.HuaweiPushService.HuaweiPushService import HuaweiPushObject
  23. from Service.PushService import PushObject
  24. class GatewayView(View):
  25. def get(self, request, *args, **kwargs):
  26. request.encoding = 'utf-8'
  27. operation = kwargs.get('operation')
  28. return self.validation(request.GET, operation)
  29. def post(self, request, *args, **kwargs):
  30. request.encoding = 'utf-8'
  31. operation = kwargs.get('operation')
  32. return self.validation(request.POST, operation)
  33. def validation(self, request_dict, operation):
  34. response = ResponseObject()
  35. if operation == 'gatewayPush': # 网关推送
  36. return self.gateway_push(request_dict, response)
  37. elif operation == 'sceneLogPush': # 场景日志推送
  38. return self.scene_log_push(request_dict, response)
  39. elif operation == 'socketPush': # 插座推送
  40. return self.socket_msg_push(request_dict, response)
  41. else:
  42. return response.json(414)
  43. @classmethod
  44. def gateway_push(cls, request_dict, response):
  45. """
  46. 网关推送
  47. @param request_dict: 请求参数
  48. @request_dict serial_number: 序列号
  49. @request_dict ieee_addr: 长地址
  50. @request_dict sensor_type: 传感器类型
  51. @request_dict event_type: 事件类型
  52. @request_dict defense: 防御状态,0:撤防,1:防御
  53. @request_dict sensor_status: 拆动状态,拆动时传参
  54. @param response: 响应对象
  55. @return: response
  56. """
  57. serial_number = request_dict.get('serial_number', None)
  58. ieee_addr = request_dict.get('ieee_addr', None)
  59. sensor_type = int(request_dict.get('sensor_type', None))
  60. event_type = int(request_dict.get('event_type', None))
  61. defense = int(request_dict.get('defense', None))
  62. LOGGER.info('---调用网关推送接口--- request_dict:{}'.format(request_dict))
  63. if not all([serial_number, ieee_addr, sensor_type, event_type]):
  64. return response.json(444)
  65. num = None
  66. n_time = int(time.time())
  67. try:
  68. # 获取温湿度
  69. if sensor_type == SENSOR_TYPE['tem_hum_sensor'] and (
  70. event_type == EVENT_TYPE['temperature'] or event_type == EVENT_TYPE['humidity']):
  71. num = request_dict.get('num')
  72. if num is None:
  73. return response.json(444)
  74. num = int(num) / 100
  75. # 查询子设备表id
  76. gateway_sub_device_qs = GatewaySubDevice.objects.filter(device__serial_number=serial_number,
  77. device_type=sensor_type, ieee_addr=ieee_addr). \
  78. values('id', 'nickname', 'device__userID__region_country')
  79. if not gateway_sub_device_qs.exists():
  80. return response.json(173)
  81. gateway_sub_device_id = gateway_sub_device_qs[0]['id']
  82. # 多线程执行场景任务
  83. task_kwargs = {
  84. 'num': num,
  85. 'n_time': n_time,
  86. 'event_type': event_type,
  87. 'gateway_sub_device_id': gateway_sub_device_id
  88. }
  89. execute_task_thread = threading.Thread(target=cls.execute_scene_tasks, kwargs=task_kwargs)
  90. execute_task_thread.start()
  91. country_id = gateway_sub_device_qs[0]['device__userID__region_country']
  92. lang = cls.confirm_lang(country_id)
  93. alarm = cls.get_alarm(lang, event_type)
  94. nickname = gateway_sub_device_qs[0]['nickname']
  95. sensor_record_dict = {
  96. 'gateway_sub_device_id': gateway_sub_device_id,
  97. 'alarm': alarm,
  98. 'event_type': event_type,
  99. 'created_time': n_time,
  100. }
  101. # 温湿度上报不推送
  102. if num is not None:
  103. sensor_record_dict['alarm'] = str(num)
  104. SensorRecord.objects.create(**sensor_record_dict)
  105. return response.json(0)
  106. SensorRecord.objects.create(**sensor_record_dict)
  107. # 门磁被拆动/拆动恢复,修改拆动状态
  108. if event_type == 2156:
  109. gateway_sub_device_qs.update(is_tampered=1)
  110. elif event_type == 2152:
  111. gateway_sub_device_qs.update(is_tampered=0)
  112. # 撤防状态不推送
  113. if defense == 0:
  114. return response.json(0)
  115. device_info_qs = Device_Info.objects.filter(serial_number=serial_number).values('userID_id')
  116. if not device_info_qs.exists():
  117. return response.json(173)
  118. equipment_info_list = []
  119. equipment_info_model = EquipmentInfoService.randoms_choice_equipment_info()
  120. # 推送表存储数据
  121. equipment_info_kwargs = {
  122. 'device_uid': serial_number,
  123. 'device_nick_name': nickname,
  124. 'event_type': event_type,
  125. 'event_time': n_time,
  126. 'add_time': n_time,
  127. 'alarm': alarm
  128. }
  129. for device_info in device_info_qs:
  130. user_id = device_info['userID_id']
  131. equipment_info_kwargs['device_user_id'] = user_id
  132. equipment_info_list.append(equipment_info_model(**equipment_info_kwargs))
  133. # 查询推送配置数据
  134. gateway_push_qs = GatewayPush.objects.filter(user_id=user_id, logout=False). \
  135. values('user_id', 'app_bundle_id', 'app_type', 'push_type', 'token_val', 'm_code', 'lang', 'm_code',
  136. 'tz')
  137. if not gateway_push_qs.exists():
  138. continue
  139. kwargs = {
  140. 'n_time': n_time,
  141. 'event_type': event_type,
  142. 'nickname': nickname,
  143. }
  144. # 推送到每台登录账号的手机
  145. for gateway_push in gateway_push_qs:
  146. app_bundle_id = gateway_push['app_bundle_id']
  147. push_type = gateway_push['push_type']
  148. token_val = gateway_push['token_val']
  149. lang = gateway_push['lang']
  150. tz = gateway_push['tz'] if gateway_push['tz'] else 0
  151. # 获取推送所需数据
  152. msg_title = PushObject.get_msg_title(nickname)
  153. msg_text = PushObject.get_gateway_msg_text(n_time, tz, lang, alarm)
  154. kwargs['msg_title'] = msg_title
  155. kwargs['msg_text'] = msg_text
  156. kwargs['app_bundle_id'] = app_bundle_id
  157. kwargs['token_val'] = token_val
  158. try:
  159. # 推送消息
  160. cls.push_msg(push_type, **kwargs)
  161. except Exception as e:
  162. LOGGER.info('网关推送消息异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  163. continue
  164. if equipment_info_list:
  165. equipment_info_model.objects.bulk_create(equipment_info_list)
  166. return response.json(0)
  167. except Exception as e:
  168. LOGGER.info('---网关推送接口异常--- {}'.format(repr(e)))
  169. return response.json(500, 'error_ine:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  170. @staticmethod
  171. def confirm_lang(country_id):
  172. """
  173. 根据country_id确定语言
  174. @param country_id: 国家id
  175. @return lang: 语言
  176. """
  177. country_qs = CountryModel.objects.filter(id=country_id).values('country_code')
  178. if not country_qs.exists():
  179. lang = 'NA'
  180. else:
  181. lang = country_qs[0]['country_code']
  182. return lang
  183. @staticmethod
  184. def get_alarm(lang, event_type):
  185. """
  186. 根据语言和事件类型确定警报内容
  187. @param lang: 语言
  188. @param event_type: 事件类型
  189. @return alarm: 警报内容
  190. """
  191. alarm = ''
  192. if lang == 'CN':
  193. # 门磁
  194. if event_type == 2150:
  195. alarm = '门磁开'
  196. elif event_type == 2151:
  197. alarm = '门磁关'
  198. elif event_type == 2156:
  199. alarm = '被拆动'
  200. elif event_type == 2152:
  201. alarm = '拆动恢复'
  202. # 智能按钮
  203. elif event_type == 2160:
  204. alarm = '紧急按钮按下'
  205. elif event_type == 2161:
  206. alarm = '单击'
  207. elif event_type == 2162:
  208. alarm = '双击'
  209. elif event_type == 2163:
  210. alarm = '长按'
  211. # 水浸
  212. elif event_type == 2170:
  213. alarm = '水浸触发'
  214. elif event_type == 2171:
  215. alarm = '水浸恢复'
  216. # 烟雾
  217. elif event_type == 2180:
  218. alarm = '烟雾触发'
  219. elif event_type == 2181:
  220. alarm = '烟雾恢复'
  221. # 人体红外
  222. elif event_type == 2190:
  223. alarm = '有人移动'
  224. elif event_type == 2191:
  225. alarm = '无人移动'
  226. # 低电量
  227. elif event_type in (2153, 2164, 2172, 2182, 2193):
  228. alarm = '低电量'
  229. else:
  230. # 门磁
  231. if event_type == 2150:
  232. alarm = 'Door magnetic opening'
  233. elif event_type == 2151:
  234. alarm = 'Door magnetic closing'
  235. elif event_type == 2156:
  236. alarm = 'Be dismantled'
  237. elif event_type == 2152:
  238. alarm = 'Dismantling recovery'
  239. # 智能按钮
  240. elif event_type == 2160:
  241. alarm = 'Emergency button pressed'
  242. elif event_type == 2161:
  243. alarm = 'Single click'
  244. elif event_type == 2162:
  245. alarm = 'Double click'
  246. elif event_type == 2163:
  247. alarm = 'Long press'
  248. # 水浸
  249. elif event_type == 2170:
  250. alarm = 'Water immersion trigger'
  251. elif event_type == 2171:
  252. alarm = 'Water immersion recovery'
  253. # 烟雾
  254. elif event_type == 2180:
  255. alarm = 'Smoke triggering'
  256. elif event_type == 2181:
  257. alarm = 'Smoke recovery'
  258. # 人体红外
  259. elif event_type == 2190:
  260. alarm = 'Someone moving'
  261. elif event_type == 2191:
  262. alarm = 'Unmanned movement'
  263. # 低电量
  264. elif event_type in (2153, 2164, 2172, 2182, 2193):
  265. alarm = 'LOW BATTERY'
  266. return alarm
  267. @classmethod
  268. def scene_log_push(cls, request_dict, response):
  269. """
  270. 网关智能场景日志推送
  271. @param request_dict: 请求参数
  272. @request_dict sceneId: 场景id
  273. @request_dict status: 状态
  274. @param response: 响应对象
  275. @return: response
  276. """
  277. scene_id = request_dict.get('sceneId', None)
  278. status = request_dict.get('status', None)
  279. LOGGER.info('---场景日志推送接口--- request_dict:{}'.format(request_dict))
  280. if not all([scene_id, status]):
  281. return response.json(444)
  282. smart_scene_qs = SmartScene.objects.filter(id=scene_id).values('scene_name', 'conditions', 'tasks', 'device_id',
  283. 'sub_device_id', 'user_id', 'scene_data')
  284. if not smart_scene_qs.exists():
  285. return response.json(173)
  286. scene_name = smart_scene_qs[0]['scene_name']
  287. tasks = smart_scene_qs[0]['tasks']
  288. device_id = smart_scene_qs[0]['device_id']
  289. sub_device_id = smart_scene_qs[0]['sub_device_id']
  290. n_time = int(time.time())
  291. user_id = smart_scene_qs[0]['user_id']
  292. scene_data = smart_scene_qs[0]['scene_data']
  293. if sub_device_id:
  294. gateway_sub_device_qs = GatewaySubDevice.objects.filter(id=sub_device_id).values('nickname')
  295. nickname = gateway_sub_device_qs[0]['nickname'] if gateway_sub_device_qs.exists() else ''
  296. else:
  297. device_qs = Device_Info.objects.filter(id=device_id).values('NickName')
  298. nickname = device_qs[0]['NickName'] if device_qs.exists() else ''
  299. log_dict = {
  300. 'scene_id': scene_id,
  301. 'scene_name': scene_name,
  302. 'tasks': tasks,
  303. 'status': status,
  304. 'device_id': device_id,
  305. 'sub_device_id': sub_device_id,
  306. 'created_time': n_time,
  307. }
  308. tasks = eval(tasks)
  309. try:
  310. SceneLog.objects.create(**log_dict)
  311. # 如果是一次性场景,关闭场景
  312. if scene_data:
  313. scene_data_dict = eval(scene_data)
  314. condition = scene_data_dict.get('condition')
  315. if condition:
  316. time_type = condition.get('time')
  317. if time_type == 'date':
  318. smart_scene_qs.update(is_enable=False)
  319. # 推送日志
  320. gateway_push_qs = GatewayPush.objects.filter(user_id=user_id, logout=False). \
  321. values('user_id', 'app_bundle_id', 'app_type', 'push_type', 'token_val', 'm_code', 'lang', 'm_code',
  322. 'tz')
  323. if not gateway_push_qs.exists():
  324. return response.json(174)
  325. for task in tasks:
  326. event_type = task['event_type']
  327. if event_type == '1001':
  328. kwargs = {
  329. 'n_time': n_time,
  330. 'event_type': event_type,
  331. 'nickname': nickname,
  332. }
  333. event_info = task['value']
  334. # 推送到每台登录账号的手机
  335. for gateway_push in gateway_push_qs:
  336. app_bundle_id = gateway_push['app_bundle_id']
  337. push_type = gateway_push['push_type']
  338. token_val = gateway_push['token_val']
  339. kwargs['msg_title'] = PushObject.get_msg_title(nickname)
  340. kwargs['msg_text'] = event_info
  341. kwargs['app_bundle_id'] = app_bundle_id
  342. kwargs['token_val'] = token_val
  343. try:
  344. # 推送消息
  345. cls.push_msg(push_type, **kwargs)
  346. except Exception as e:
  347. LOGGER.info(
  348. '场景日志推送消息异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  349. continue
  350. return response.json(0)
  351. except Exception as e:
  352. LOGGER.info('---场景日志推送接口异常--- {}'.format(repr(e)))
  353. return response.json(500, 'error_ine:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  354. @staticmethod
  355. def push_msg(push_type, **kwargs):
  356. """
  357. 发送推送消息
  358. @param push_type: 推送类型
  359. @param kwargs: 推送参数
  360. @return: None
  361. """
  362. if push_type == 0: # ios apns
  363. PushObject.ios_apns_push(**kwargs)
  364. elif push_type == 1: # android gcm
  365. PushObject.android_fcm_push(**kwargs)
  366. elif push_type == 2: # android 极光推送
  367. PushObject.android_jpush(**kwargs)
  368. elif push_type == 3:
  369. huawei_push_object = HuaweiPushObject()
  370. huawei_push_object.send_push_notify_message(**kwargs)
  371. elif push_type == 4: # android 小米推送
  372. channel_id = XM_PUSH_CHANNEL_ID['device_reminder']
  373. PushObject.android_xmpush(channel_id=channel_id, **kwargs)
  374. elif push_type == 5: # android vivo推送
  375. PushObject.android_vivopush(**kwargs)
  376. elif push_type == 6: # android oppo推送
  377. channel_id = 'DEVICE_REMINDER'
  378. PushObject.android_oppopush(channel_id=channel_id, **kwargs)
  379. elif push_type == 7: # android 魅族推送
  380. PushObject.android_meizupush(**kwargs)
  381. @classmethod
  382. def socket_msg_push(cls, request_dict, response):
  383. """
  384. 智能插座开关状态推送
  385. """
  386. try:
  387. serial_number = request_dict.get('serialNumber', None)
  388. device_time = request_dict.get('deviceTime', None)
  389. status = request_dict.get('status', None)
  390. if not all([serial_number, status, device_time]):
  391. return response.json(444)
  392. status = int(status)
  393. now_time = int(device_time) if device_time else int(time.time())
  394. # 获取主用户设备id
  395. log_dict = {
  396. 'status': status,
  397. 'device_id': serial_number,
  398. 'created_time': now_time,
  399. }
  400. SceneLog.objects.create(**log_dict)
  401. LOGGER.info('成功接收并保存,插座序列号{},状态:{}'.format(serial_number, status))
  402. return response.json(0)
  403. except Exception as e:
  404. LOGGER.info('插座开关日志推送接口异常, error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  405. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  406. @classmethod
  407. def execute_scene_tasks(cls, gateway_sub_device_id, event_type, num, n_time):
  408. """
  409. 执行场景任务
  410. @param gateway_sub_device_id: 子设备id
  411. @param event_type: 事件类型
  412. @param num: 温湿度值
  413. @param n_time: 当前时间
  414. @return:
  415. """
  416. smart_scene_qs = SmartScene.objects.filter(sub_device_id=gateway_sub_device_id, is_enable=True). \
  417. values('id', 'scene_data', 'tz', 'is_all_day', 'effective_time_id')
  418. if smart_scene_qs.exists():
  419. for smart_scene in smart_scene_qs:
  420. if smart_scene['scene_data']:
  421. scene_data_dict = eval(smart_scene['scene_data'])
  422. condition = scene_data_dict.get('condition')
  423. if condition:
  424. # None 或 event_type
  425. scene_data_event_type = condition.get('event_type')
  426. # 触发事件类型跟条件事件类型一致,且任务列表不为空
  427. task_list = scene_data_dict.get('task_list')
  428. if event_type == scene_data_event_type and task_list:
  429. # 判断温湿度是否在条件设置的范围
  430. if num is not None:
  431. condition_value = condition.get('value')
  432. space_index = condition_value.index(' ')
  433. symbol, value = condition_value[:space_index], float(condition_value[space_index + 1:])
  434. # 温湿度不在设定范围,不执行
  435. if not ((symbol == '≥' and num >= value) or (symbol == '≤' and num <= value)):
  436. continue
  437. execute_task = cls.judge_execute_task(smart_scene, n_time)
  438. # 执行任务
  439. if execute_task:
  440. scene_id = 0
  441. task_list_len = len(task_list)
  442. for index, task in enumerate(task_list):
  443. # 最后一个任务上报日志
  444. if index == task_list_len - 1:
  445. scene_id = smart_scene['id']
  446. kwargs = {
  447. 'device_type': task['device_type'],
  448. 'event_type': task['event_type'],
  449. 'serial_number': task['serial_number'],
  450. 'delay_time': task['delay_time'],
  451. 'scene_id': scene_id
  452. }
  453. pub_mqtt_thread = threading.Thread(target=cls.pub_mqtt, kwargs=kwargs)
  454. pub_mqtt_thread.start()
  455. @classmethod
  456. def judge_execute_task(cls, smart_scene, n_time):
  457. """
  458. 判断是否执行任务
  459. @param smart_scene: 场景数据
  460. @param n_time: 当前时间
  461. @return execute_task: bool
  462. """
  463. execute_task = False
  464. # 判断时间是否在执行时间范围内
  465. if smart_scene['is_all_day'] == 1:
  466. # 全天必执行
  467. execute_task = True
  468. elif smart_scene['is_all_day'] == 2:
  469. # 非全天,判断当前时间是否在设置的时间范围
  470. tz = smart_scene['tz']
  471. time_minute, week = cls.get_time_info(n_time, tz)
  472. effective_time_id = smart_scene['effective_time_id']
  473. effective_time_qs = EffectiveTime.objects.filter(id=effective_time_id). \
  474. values('start_time', 'end_time', 'repeat')
  475. if effective_time_qs.exists():
  476. start_time = effective_time_qs[0]['start_time']
  477. end_time = effective_time_qs[0]['end_time']
  478. repeat = effective_time_qs[0]['repeat']
  479. time_frame_dict, time_frame_next_day_dict = cls.get_time_frame_dict(
  480. start_time, end_time, repeat)
  481. # 判断当前时间是否在设置的时间范围
  482. if time_frame_dict.get(week):
  483. start_time = time_frame_dict[week]['start_time']
  484. end_time = time_frame_dict[week]['end_time']
  485. if start_time <= time_minute <= end_time:
  486. execute_task = True
  487. if time_frame_next_day_dict.get(week):
  488. start_time = time_frame_next_day_dict[week]['start_time']
  489. end_time = time_frame_next_day_dict[week]['end_time']
  490. if start_time <= time_minute <= end_time:
  491. execute_task = True
  492. return execute_task
  493. @staticmethod
  494. def get_time_info(timestamp, timezone_offset):
  495. """
  496. 根据时间戳和时区获取时间(时分转为分钟数)和星期
  497. @param timestamp: 时间戳
  498. @param timezone_offset: 时区
  499. @return: time_minute, week
  500. """
  501. # 计算时区偏移量(以分钟为单位)
  502. timezone_offset_minutes = int(timezone_offset * 60)
  503. timezone = pytz.FixedOffset(timezone_offset_minutes)
  504. # 将时间戳转换为datetime对象,并应用时区
  505. dt_object = datetime.datetime.fromtimestamp(timestamp, tz=timezone)
  506. # 获取时分,并转为分钟数
  507. hour = dt_object.hour
  508. minute = dt_object.minute
  509. time_minute = hour * 60 + minute
  510. # 获取星期(0表示星期一,6表示星期日)
  511. week = str(dt_object.weekday())
  512. return time_minute, week
  513. @staticmethod
  514. def get_time_frame_dict(start_time, end_time, repeat):
  515. """
  516. 获取时间范围字典
  517. @param start_time: 开始时间
  518. @param end_time: 结束时间
  519. @param repeat: 星期周期的十进制数,如127 -> 0,1,2,3,4,5,6
  520. @return: time_frame_dict, time_frame_next_day_dict
  521. """
  522. # 十进制转为7位的二进制并倒序
  523. bin_str = bin(repeat)[2:].zfill(7)[::-1]
  524. # 生成星期周期列表
  525. week_list = []
  526. for i, bit in enumerate(bin_str):
  527. if bit == '1':
  528. week_list.append(i)
  529. # 生成时间范围字典
  530. time_frame_dict = {}
  531. time_frame_next_day_dict = {}
  532. # 非隔天
  533. if end_time > start_time:
  534. for week in week_list:
  535. time_frame_dict[str(week)] = {
  536. 'start_time': start_time,
  537. 'end_time': end_time
  538. }
  539. # 隔天
  540. else:
  541. # time_frame_dict记录当天时间范围,time_frame_next_day_dict记录溢出到第二天的时间范围
  542. for week in week_list:
  543. time_frame_dict[str(week)] = {
  544. 'start_time': start_time,
  545. 'end_time': 1439 # 23:59
  546. }
  547. week += 1
  548. if week == 7:
  549. week = 0
  550. time_frame_next_day_dict[str(week)] = {
  551. 'start_time': 0, # 00:00
  552. 'end_time': end_time
  553. }
  554. return time_frame_dict, time_frame_next_day_dict
  555. @staticmethod
  556. def pub_mqtt(device_type, event_type, serial_number, delay_time, scene_id=0):
  557. """
  558. 发布mqtt消息
  559. @param device_type: 设备类型
  560. @param event_type: 事件类型
  561. @param serial_number: 序列号
  562. @param delay_time: 延迟时间
  563. @param scene_id: 场景id
  564. @return:
  565. """
  566. if device_type == DEVICE_TYPE['socket']:
  567. topic_name = SMART_SOCKET_TOPIC.format(serial_number)
  568. status = 1 if event_type == EVENT_TYPE['socket_power_on'] else 0
  569. msg = {
  570. 'type': 1,
  571. 'data': {'deviceSwitch': status}
  572. }
  573. if delay_time:
  574. time.sleep(delay_time)
  575. CommonService.req_publish_mqtt_msg(serial_number, topic_name, msg)
  576. # 没有设备任务时,最后一个任务上报场景日志
  577. if scene_id:
  578. data = {
  579. 'sceneId': scene_id,
  580. 'status': 1
  581. }
  582. url = DETECT_PUSH_DOMAIN + 'gatewayService/sceneLogPush'
  583. requests.post(url=url, data=data, timeout=8)