gatewayController.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  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. # 防止定时任务同时请求生成多条场景日志
  280. redis_obj = RedisObject()
  281. key = scene_id + 'scene_log_limit'
  282. is_lock = redis_obj.CONN.setnx(key, 1)
  283. redis_obj.CONN.expire(key, 60)
  284. if not is_lock:
  285. return response.json(0)
  286. LOGGER.info('---场景日志推送接口--- request_dict:{}'.format(request_dict))
  287. if not all([scene_id, status]):
  288. return response.json(444)
  289. smart_scene_qs = SmartScene.objects.filter(id=scene_id).values('scene_name', 'conditions', 'tasks', 'device_id',
  290. 'sub_device_id', 'user_id', 'scene_data')
  291. if not smart_scene_qs.exists():
  292. return response.json(173)
  293. scene_name = smart_scene_qs[0]['scene_name']
  294. tasks = smart_scene_qs[0]['tasks']
  295. device_id = smart_scene_qs[0]['device_id']
  296. sub_device_id = smart_scene_qs[0]['sub_device_id']
  297. n_time = int(time.time())
  298. user_id = smart_scene_qs[0]['user_id']
  299. scene_data = smart_scene_qs[0]['scene_data']
  300. if sub_device_id:
  301. gateway_sub_device_qs = GatewaySubDevice.objects.filter(id=sub_device_id).values('nickname')
  302. nickname = gateway_sub_device_qs[0]['nickname'] if gateway_sub_device_qs.exists() else ''
  303. else:
  304. device_qs = Device_Info.objects.filter(id=device_id).values('NickName')
  305. nickname = device_qs[0]['NickName'] if device_qs.exists() else ''
  306. log_dict = {
  307. 'scene_id': scene_id,
  308. 'scene_name': scene_name,
  309. 'tasks': tasks,
  310. 'status': status,
  311. 'device_id': device_id,
  312. 'sub_device_id': sub_device_id,
  313. 'created_time': n_time,
  314. }
  315. tasks = eval(tasks)
  316. try:
  317. SceneLog.objects.create(**log_dict)
  318. # 如果是一次性场景,关闭场景
  319. if scene_data:
  320. scene_data_dict = eval(scene_data)
  321. condition = scene_data_dict.get('condition')
  322. if condition:
  323. time_type = condition.get('time')
  324. if time_type == 'date':
  325. smart_scene_qs.update(is_enable=False)
  326. # 推送日志
  327. gateway_push_qs = GatewayPush.objects.filter(user_id=user_id, logout=False). \
  328. values('user_id', 'app_bundle_id', 'app_type', 'push_type', 'token_val', 'm_code', 'lang', 'm_code',
  329. 'tz')
  330. if not gateway_push_qs.exists():
  331. return response.json(174)
  332. for task in tasks:
  333. event_type = task['event_type']
  334. if event_type == '1001':
  335. kwargs = {
  336. 'n_time': n_time,
  337. 'event_type': event_type,
  338. 'nickname': nickname,
  339. }
  340. event_info = task['value']
  341. # 推送到每台登录账号的手机
  342. for gateway_push in gateway_push_qs:
  343. app_bundle_id = gateway_push['app_bundle_id']
  344. push_type = gateway_push['push_type']
  345. token_val = gateway_push['token_val']
  346. kwargs['msg_title'] = PushObject.get_msg_title(nickname)
  347. kwargs['msg_text'] = event_info
  348. kwargs['app_bundle_id'] = app_bundle_id
  349. kwargs['token_val'] = token_val
  350. try:
  351. # 推送消息
  352. cls.push_msg(push_type, **kwargs)
  353. except Exception as e:
  354. LOGGER.info(
  355. '场景日志推送消息异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  356. continue
  357. return response.json(0)
  358. except Exception as e:
  359. LOGGER.info('---场景日志推送接口异常--- {}'.format(repr(e)))
  360. return response.json(500, 'error_ine:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  361. @staticmethod
  362. def push_msg(push_type, **kwargs):
  363. """
  364. 发送推送消息
  365. @param push_type: 推送类型
  366. @param kwargs: 推送参数
  367. @return: None
  368. """
  369. if push_type == 0: # ios apns
  370. PushObject.ios_apns_push(**kwargs)
  371. elif push_type == 1: # android gcm
  372. PushObject.android_fcm_push(**kwargs)
  373. elif push_type == 2: # android 极光推送
  374. PushObject.android_jpush(**kwargs)
  375. elif push_type == 3:
  376. huawei_push_object = HuaweiPushObject()
  377. huawei_push_object.send_push_notify_message(**kwargs)
  378. elif push_type == 4: # android 小米推送
  379. channel_id = XM_PUSH_CHANNEL_ID['device_reminder']
  380. PushObject.android_xmpush(channel_id=channel_id, **kwargs)
  381. elif push_type == 5: # android vivo推送
  382. PushObject.android_vivopush(**kwargs)
  383. elif push_type == 6: # android oppo推送
  384. channel_id = 'DEVICE_REMINDER'
  385. PushObject.android_oppopush(channel_id=channel_id, **kwargs)
  386. elif push_type == 7: # android 魅族推送
  387. PushObject.android_meizupush(**kwargs)
  388. @classmethod
  389. def socket_msg_push(cls, request_dict, response):
  390. """
  391. 智能插座开关状态推送
  392. """
  393. try:
  394. serial_number = request_dict.get('serialNumber', None)
  395. device_time = request_dict.get('deviceTime', None)
  396. status = request_dict.get('status', None)
  397. if not all([serial_number, status, device_time]):
  398. return response.json(444)
  399. status = int(status)
  400. now_time = int(device_time) if device_time else int(time.time())
  401. # 获取主用户设备id
  402. log_dict = {
  403. 'status': status,
  404. 'device_id': serial_number,
  405. 'created_time': now_time,
  406. }
  407. SceneLog.objects.create(**log_dict)
  408. LOGGER.info('成功接收并保存,插座序列号{},状态:{}'.format(serial_number, status))
  409. return response.json(0)
  410. except Exception as e:
  411. LOGGER.info('插座开关日志推送接口异常, error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  412. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  413. @classmethod
  414. def execute_scene_tasks(cls, gateway_sub_device_id, event_type, num, n_time):
  415. """
  416. 执行场景任务
  417. @param gateway_sub_device_id: 子设备id
  418. @param event_type: 事件类型
  419. @param num: 温湿度值
  420. @param n_time: 当前时间
  421. @return:
  422. """
  423. smart_scene_qs = SmartScene.objects.filter(sub_device_id=gateway_sub_device_id, is_enable=True). \
  424. values('id', 'scene_data', 'tz', 'is_all_day', 'effective_time_id')
  425. if smart_scene_qs.exists():
  426. for smart_scene in smart_scene_qs:
  427. if smart_scene['scene_data']:
  428. scene_data_dict = eval(smart_scene['scene_data'])
  429. condition = scene_data_dict.get('condition')
  430. if condition:
  431. # None 或 event_type
  432. scene_data_event_type = condition.get('event_type')
  433. # 触发事件类型跟条件事件类型一致,且任务列表不为空
  434. task_list = scene_data_dict.get('task_list')
  435. if event_type == scene_data_event_type and task_list:
  436. # 判断温湿度是否在条件设置的范围
  437. if num is not None:
  438. condition_value = condition.get('value')
  439. space_index = condition_value.index(' ')
  440. symbol, value = condition_value[:space_index], float(condition_value[space_index + 1:])
  441. # 温湿度不在设定范围,不执行
  442. if not ((symbol == '≥' and num >= value) or (symbol == '≤' and num <= value)):
  443. continue
  444. execute_task = cls.judge_execute_task(smart_scene, n_time)
  445. # 执行任务
  446. if execute_task:
  447. scene_id = 0
  448. task_list_len = len(task_list)
  449. for index, task in enumerate(task_list):
  450. # 最后一个任务上报日志
  451. if index == task_list_len - 1:
  452. scene_id = smart_scene['id']
  453. kwargs = {
  454. 'device_type': task['device_type'],
  455. 'event_type': task['event_type'],
  456. 'serial_number': task['serial_number'],
  457. 'delay_time': task['delay_time'],
  458. 'scene_id': scene_id
  459. }
  460. pub_mqtt_thread = threading.Thread(target=cls.pub_mqtt, kwargs=kwargs)
  461. pub_mqtt_thread.start()
  462. @classmethod
  463. def judge_execute_task(cls, smart_scene, n_time):
  464. """
  465. 判断是否执行任务
  466. @param smart_scene: 场景数据
  467. @param n_time: 当前时间
  468. @return execute_task: bool
  469. """
  470. execute_task = False
  471. # 判断时间是否在执行时间范围内
  472. if smart_scene['is_all_day'] == 1:
  473. # 全天必执行
  474. execute_task = True
  475. elif smart_scene['is_all_day'] == 2:
  476. # 非全天,判断当前时间是否在设置的时间范围
  477. tz = smart_scene['tz']
  478. time_minute, week = cls.get_time_info(n_time, tz)
  479. effective_time_id = smart_scene['effective_time_id']
  480. effective_time_qs = EffectiveTime.objects.filter(id=effective_time_id). \
  481. values('start_time', 'end_time', 'repeat')
  482. if effective_time_qs.exists():
  483. start_time = effective_time_qs[0]['start_time']
  484. end_time = effective_time_qs[0]['end_time']
  485. repeat = effective_time_qs[0]['repeat']
  486. time_frame_dict, time_frame_next_day_dict = cls.get_time_frame_dict(
  487. start_time, end_time, repeat)
  488. # 判断当前时间是否在设置的时间范围
  489. if time_frame_dict.get(week):
  490. start_time = time_frame_dict[week]['start_time']
  491. end_time = time_frame_dict[week]['end_time']
  492. if start_time <= time_minute <= end_time:
  493. execute_task = True
  494. if time_frame_next_day_dict.get(week):
  495. start_time = time_frame_next_day_dict[week]['start_time']
  496. end_time = time_frame_next_day_dict[week]['end_time']
  497. if start_time <= time_minute <= end_time:
  498. execute_task = True
  499. return execute_task
  500. @staticmethod
  501. def get_time_info(timestamp, timezone_offset):
  502. """
  503. 根据时间戳和时区获取时间(时分转为分钟数)和星期
  504. @param timestamp: 时间戳
  505. @param timezone_offset: 时区
  506. @return: time_minute, week
  507. """
  508. # 计算时区偏移量(以分钟为单位)
  509. timezone_offset_minutes = int(timezone_offset * 60)
  510. timezone = pytz.FixedOffset(timezone_offset_minutes)
  511. # 将时间戳转换为datetime对象,并应用时区
  512. dt_object = datetime.datetime.fromtimestamp(timestamp, tz=timezone)
  513. # 获取时分,并转为分钟数
  514. hour = dt_object.hour
  515. minute = dt_object.minute
  516. time_minute = hour * 60 + minute
  517. # 获取星期(0表示星期一,6表示星期日)
  518. week = str(dt_object.weekday())
  519. return time_minute, week
  520. @staticmethod
  521. def get_time_frame_dict(start_time, end_time, repeat):
  522. """
  523. 获取时间范围字典
  524. @param start_time: 开始时间
  525. @param end_time: 结束时间
  526. @param repeat: 星期周期的十进制数,如127 -> 0,1,2,3,4,5,6
  527. @return: time_frame_dict, time_frame_next_day_dict
  528. """
  529. # 十进制转为7位的二进制并倒序
  530. bin_str = bin(repeat)[2:].zfill(7)[::-1]
  531. # 生成星期周期列表
  532. week_list = []
  533. for i, bit in enumerate(bin_str):
  534. if bit == '1':
  535. week_list.append(i)
  536. # 生成时间范围字典
  537. time_frame_dict = {}
  538. time_frame_next_day_dict = {}
  539. # 非隔天
  540. if end_time > start_time:
  541. for week in week_list:
  542. time_frame_dict[str(week)] = {
  543. 'start_time': start_time,
  544. 'end_time': end_time
  545. }
  546. # 隔天
  547. else:
  548. # time_frame_dict记录当天时间范围,time_frame_next_day_dict记录溢出到第二天的时间范围
  549. for week in week_list:
  550. time_frame_dict[str(week)] = {
  551. 'start_time': start_time,
  552. 'end_time': 1439 # 23:59
  553. }
  554. week += 1
  555. if week == 7:
  556. week = 0
  557. time_frame_next_day_dict[str(week)] = {
  558. 'start_time': 0, # 00:00
  559. 'end_time': end_time
  560. }
  561. return time_frame_dict, time_frame_next_day_dict
  562. @staticmethod
  563. def pub_mqtt(device_type, event_type, serial_number, delay_time, scene_id=0):
  564. """
  565. 发布mqtt消息
  566. @param device_type: 设备类型
  567. @param event_type: 事件类型
  568. @param serial_number: 序列号
  569. @param delay_time: 延迟时间
  570. @param scene_id: 场景id
  571. @return:
  572. """
  573. if device_type == DEVICE_TYPE['socket']:
  574. topic_name = SMART_SOCKET_TOPIC.format(serial_number)
  575. status = 1 if event_type == EVENT_TYPE['socket_power_on'] else 0
  576. msg = {
  577. 'type': 1,
  578. 'data': {'deviceSwitch': status}
  579. }
  580. if delay_time:
  581. time.sleep(delay_time)
  582. CommonService.req_publish_mqtt_msg(serial_number, topic_name, msg)
  583. # 没有设备任务时,最后一个任务上报场景日志
  584. if scene_id:
  585. data = {
  586. 'sceneId': scene_id,
  587. 'status': 1
  588. }
  589. url = DETECT_PUSH_DOMAIN + 'gatewayService/sceneLogPush'
  590. requests.post(url=url, data=data, timeout=8)