SmartSwitchController.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. # -*- coding: utf-8 -*-
  2. """
  3. # @Author : cheng
  4. # @Time : 2023/7/10 11:20
  5. # @File: SmartSwitchController.py
  6. """
  7. import datetime
  8. import json
  9. import time
  10. from django.views import View
  11. from Model.models import SwitchDimmingSettings, SwitchScheduler, Device_Info, SceneLog, FamilyRoomDevice
  12. from Object.RedisObject import RedisObject
  13. from Service.CommonService import CommonService
  14. from Object.CeleryBeatObject import CeleryBeatObj
  15. from django.db import transaction
  16. from Ansjer.config import LOGGER
  17. APSCHEDULER_TOPIC_NAME = 'loocam/switch/time_scheduling/{}' # 排程主题
  18. RESET_SWITCH_TOPIC_NAME = 'loocam/switch/request_update/{}' # 重置设备
  19. TIMER_TOPIC_NAME = 'loocam/switch/count_down/{}' # 计时器主题
  20. MQTT_TASK = 'Controller.CeleryTasks.tasks.send_mqtt'
  21. class SmartSwitchView(View):
  22. def get(self, request, *args, **kwargs):
  23. request.encoding = 'utf-8'
  24. operation = kwargs.get('operation')
  25. return self.validation(request.GET, request, operation)
  26. def post(self, request, *args, **kwargs):
  27. request.encoding = 'utf-8'
  28. operation = kwargs.get('operation')
  29. return self.validation(request.POST, request, operation)
  30. def validation(self, request_dict, request, operation):
  31. token_code, user_id, response = CommonService.verify_token_get_user_id(request_dict, request)
  32. if operation == 'switch-scheduler-log': # 设备上报排程日志
  33. return self.create_scheduler_log(request_dict, response)
  34. elif operation == 'reset': # 设备重置
  35. return self.reset(request_dict, response)
  36. else:
  37. if token_code != 0:
  38. return response.json(token_code)
  39. if operation == 'get-dimming-setting': # 获取智能开关调光设置
  40. return self.get_dimming_setting(request_dict, response)
  41. elif operation == 'get-scheduler-setting': # 获取排程计划
  42. return self.get_scheduler_setting(request_dict, response)
  43. elif operation == 'add-or-edit-scheduler': # 添加/编辑排程计划
  44. return self.add_or_edit_scheduler(request_dict, response)
  45. elif operation == 'edit-scheduler-status': # 修改排程计划状态
  46. return self.edit_scheduler_status(request_dict, response)
  47. elif operation == 'delete-scheduler': # 删除排程计划
  48. return self.delete_scheduler(request_dict, response)
  49. elif operation == 'get-timer-setting': # 获取计时器
  50. return self.get_timer_setting(request_dict, response)
  51. elif operation == 'add-or-edit-timer': # 添加/编辑计时器
  52. return self.add_or_edit_timer(request_dict, response)
  53. elif operation == 'edit-dimming-correction': # 设置调光校正
  54. return self.edit_dimming_correction(request_dict, response)
  55. elif operation == 'edit-dimming-setting': # 修改智能开关调光设置
  56. return self.edit_dimming_setting(request_dict, response)
  57. elif operation == 'get-scheduler-log': # 查询排程日志
  58. return self.get_scheduler_log(request_dict, response)
  59. else:
  60. return response.json(414)
  61. @staticmethod
  62. def get_dimming_setting(request_dict, response):
  63. """
  64. 获取智能开关调光设置信息
  65. @param request_dict: 请求参数
  66. @request_dict deviceId: 设备id
  67. @param response: 响应对象
  68. @return: response
  69. """
  70. device_id = request_dict.get('deviceId', None)
  71. if not device_id:
  72. return response.json(444)
  73. try:
  74. switch_setting_info_qs = SwitchDimmingSettings.objects.filter(device_id=device_id).values()
  75. if not switch_setting_info_qs.exists():
  76. return response.json(173)
  77. res = {
  78. 'clickTurnOnSpeed': switch_setting_info_qs[0]['click_turn_on_speed'],
  79. 'clickTurnOffSpeed': switch_setting_info_qs[0]['click_turn_off_speed'],
  80. 'doubleClick': switch_setting_info_qs[0]['double_click'],
  81. 'press': switch_setting_info_qs[0]['press'],
  82. 'doublePressClickTurnOnSpeed': switch_setting_info_qs[0]['double_press_click_turn_on_speed'],
  83. 'doublePressClickTurnOffSpeed': switch_setting_info_qs[0]['double_press_click_turn_off_speed'],
  84. 'dimmingCorrection': switch_setting_info_qs[0]['dimming_correction'],
  85. }
  86. return response.json(0, res)
  87. except Exception as e:
  88. print(e)
  89. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  90. @staticmethod
  91. def edit_dimming_correction(request_dict, response):
  92. """
  93. 修改智能开关调光校正
  94. @param request_dict: 请求参数
  95. @request_dict deviceId: 设备id
  96. @request_dict dimmingCorrection: 调光校正
  97. @param response: 响应对象
  98. @return: response
  99. """
  100. device_id = request_dict.get('deviceId', None)
  101. dimming_correction = request_dict.get('dimmingCorrection', None)
  102. if not device_id:
  103. return response.json(444)
  104. try:
  105. SwitchDimmingSettings.objects.filter(device_id=device_id).update(dimming_correction=dimming_correction)
  106. return response.json(0)
  107. except Exception as e:
  108. print(e)
  109. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  110. @staticmethod
  111. def edit_dimming_setting(request_dict, response):
  112. """
  113. 修改智能开关调光设置
  114. @param request_dict: 请求参数
  115. @request_dict deviceId: 设备id
  116. @request_dict clickTurnOnSpeed: 单击开启速度
  117. @request_dict clickTurnOffSpeed: 单击关闭速度
  118. @request_dict doubleClick: 双击
  119. @request_dict press: 长按
  120. @request_dict doublePressClickTurnOnSpeed: 双击/长按开启速度
  121. @request_dict doublePressClickTurnOffSpeed: 双击/长按单击关闭速度
  122. @param response: 响应对象
  123. @return: response
  124. """
  125. device_id = request_dict.get('deviceId', None)
  126. click_turn_on_speed = request_dict.get('clickTurnOnSpeed', None)
  127. click_turn_off_speed = request_dict.get('clickTurnOffSpeed', None)
  128. double_click = request_dict.get('doubleClick', None)
  129. press = request_dict.get('press', None)
  130. double_press_click_turn_on_speed = request_dict.get('doublePressClickTurnOnSpeed', None)
  131. double_press_click_turn_off_speed = request_dict.get('doublePressClickTurnOffSpeed', None)
  132. if not device_id:
  133. return response.json(444)
  134. try:
  135. dimming_setting_data = {
  136. 'device_id': device_id,
  137. 'click_turn_on_speed': click_turn_on_speed,
  138. 'click_turn_off_speed': click_turn_off_speed,
  139. 'double_click': double_click,
  140. 'press': press,
  141. 'double_press_click_turn_on_speed': double_press_click_turn_on_speed,
  142. 'double_press_click_turn_off_speed': double_press_click_turn_off_speed
  143. }
  144. SwitchDimmingSettings.objects.filter(device_id=device_id).update(**dimming_setting_data)
  145. return response.json(0)
  146. except Exception as e:
  147. print(e)
  148. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  149. @staticmethod
  150. def get_scheduler_setting(request_dict, response):
  151. """
  152. 获取排程计划设置
  153. @param request_dict: 请求参数
  154. @request_dict deviceId: 设备id
  155. @param response: 响应对象
  156. @return: response
  157. """
  158. device_id = request_dict.get('deviceId', None)
  159. if not device_id:
  160. return response.json(444)
  161. try:
  162. switch_scheduler_qs = SwitchScheduler.objects.filter(device_id=device_id).values()
  163. if not switch_scheduler_qs.exists():
  164. return response.json(173)
  165. switch_scheduler_list = []
  166. for item in switch_scheduler_qs:
  167. switch_scheduler_list.append({
  168. 'schedulerId': item['id'],
  169. 'timeTypeRadio': item['time_type_radio'],
  170. 'timePoint': item['time_point'],
  171. 'startTime': item['start_time'],
  172. 'endTime': item['end_time'],
  173. 'actionsType': item['actions_type'],
  174. 'actions': item['actions'],
  175. 'slowSpeed': item['slow_speed'],
  176. 'repeat': item['repeat'],
  177. 'isExecute': item['is_execute'],
  178. })
  179. return response.json(0, {'list': switch_scheduler_list})
  180. except Exception as e:
  181. print(e)
  182. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  183. @staticmethod
  184. def add_or_edit_scheduler(request_dict, response):
  185. """
  186. 添加/编辑排程计划
  187. @param request_dict: 请求参数
  188. @request_dict deviceId: 设备id
  189. @request_dict schedulerId: 排程计划id
  190. @request_dict timeTypeRadio: 切换时间点/时间段
  191. @request_dict timePoint: 时间点
  192. @request_dict startTime: 时间段开始时间
  193. @request_dict endTime: 时间段结束时间
  194. @request_dict actions: 排程操作
  195. @request_dict actionsType: 操作类型
  196. @request_dict slowOpenOrCloseSpeed: 缓慢开/关速度
  197. @request_dict repeat: 重复周期
  198. @param response: 响应对象
  199. @return: response
  200. """
  201. is_edit = request_dict.get('isEdit', None)
  202. device_id = request_dict.get('deviceId', None)
  203. scheduler_id = request_dict.get('schedulerId', None)
  204. time_type_radio = int(request_dict.get('timeTypeRadio', 0))
  205. time_point = request_dict.get('timePoint', None)
  206. start_time = request_dict.get('startTime', None)
  207. end_time = request_dict.get('endTime', None)
  208. actions = request_dict.get('actions', None)
  209. actions_type = request_dict.get('actionsType', None)
  210. slow_speed = request_dict.get('slowSpeed', None)
  211. repeat = request_dict.get('repeat', None)
  212. if not all([device_id, repeat]):
  213. return response.json(444, {'param': 'deviceId,repeat'})
  214. device_qs = Device_Info.objects.filter(id=device_id).values('serial_number', 'userID')
  215. if not device_qs.exists():
  216. return response.json(173)
  217. if time_type_radio == 1: # 时间点
  218. if not all([time_point]):
  219. return response.json(444, {'param': 'timePoint'})
  220. if actions_type == '1':
  221. scheduler_data = {
  222. 'device_id': device_id,
  223. 'time_type_radio': time_type_radio,
  224. 'time_point': time_point,
  225. 'actions': actions,
  226. 'actions_type': actions_type,
  227. 'slow_speed': slow_speed,
  228. 'repeat': repeat
  229. }
  230. elif actions_type == '2':
  231. scheduler_data = {
  232. 'device_id': device_id,
  233. 'time_type_radio': time_type_radio,
  234. 'time_point': time_point,
  235. 'actions': actions,
  236. 'actions_type': actions_type,
  237. 'repeat': repeat
  238. }
  239. else:
  240. return response.json(444, {'param': 'actionsType'})
  241. elif time_type_radio == 2: # 时间段
  242. if not all([start_time, end_time]):
  243. return response.json(444, {'param': 'startTime,endTime'})
  244. start_time = int(start_time)
  245. end_time = int(end_time)
  246. scheduler_data = {
  247. 'device_id': device_id,
  248. 'time_type_radio': time_type_radio,
  249. 'start_time': start_time,
  250. 'end_time': end_time,
  251. 'actions': actions,
  252. 'actions_type': actions_type,
  253. 'repeat': repeat
  254. }
  255. else:
  256. return response.json(444, {'param': 'timeTypeRadio'})
  257. try:
  258. with transaction.atomic():
  259. celery_obj = CeleryBeatObj()
  260. if is_edit:
  261. if not scheduler_id:
  262. return response.json(444, {'param': 'schedulerId'})
  263. update_flag = SwitchScheduler.objects.filter(device_id=device_id, id=scheduler_id).update(
  264. **scheduler_data)
  265. if not update_flag:
  266. return response.json(173)
  267. celery_obj.del_task('switchscheduler_{}'.format(scheduler_id))
  268. celery_obj.del_task('switchscheduler_{}_1'.format(scheduler_id))
  269. celery_obj.del_task('switchscheduler_{}_2'.format(scheduler_id))
  270. else:
  271. switch_qs = SwitchScheduler.objects.create(**scheduler_data)
  272. scheduler_id = switch_qs.id
  273. # 设置排程任务
  274. serial_number = device_qs[0]['serial_number']
  275. user_id = device_qs[0]['userID']
  276. tz = CommonService.get_user_tz(user_id)
  277. topic_name = APSCHEDULER_TOPIC_NAME.format(serial_number)
  278. if time_type_radio == 1: # 时间点任务
  279. task_id = 'switchscheduler_{}'.format(scheduler_id)
  280. if actions_type == '1': # 开启或关闭
  281. msg = {
  282. "task_id": scheduler_id,
  283. "device_switch": int(actions), # 设备开关-1:反转,0:关,1:开,2:预设亮度
  284. "slow_time": slow_speed
  285. }
  286. elif actions_type == '2': # 开启且设置亮度
  287. msg = {
  288. "task_id": scheduler_id,
  289. "device_switch": 2,
  290. "pwm_control": int(actions),
  291. 'slow_time': slow_speed
  292. }
  293. else:
  294. return response.json(444, {'param': 'actionsType'})
  295. time_str = datetime.datetime.fromtimestamp(int(time_point))
  296. celery_obj.creat_crontab_task(tz, task_id, MQTT_TASK, time_str.minute,
  297. time_str.hour, repeat,
  298. args=[serial_number, topic_name, msg, task_id, 1, device_id,
  299. json.dumps(scheduler_data)])
  300. else: # 时间段任务
  301. start_hour = int(start_time / 60 // 60)
  302. start_minute = int(start_time / 60 % 60)
  303. end_hour = int(end_time / 60 // 60)
  304. end_minute = int(end_time / 60 % 60)
  305. if actions_type == '1':
  306. begin_task_id = 'switchscheduler_{}_1'.format(scheduler_id) # 开始任务id
  307. end_task_id = 'switchscheduler_{}_2'.format(scheduler_id) # 结束任务id
  308. msg = {"task_id": scheduler_id,
  309. "device_switch": int(actions)}
  310. celery_obj.creat_crontab_task(tz, begin_task_id, MQTT_TASK, start_minute, start_hour, repeat,
  311. args=[serial_number, topic_name, msg, begin_task_id, 1,
  312. device_id, json.dumps(scheduler_data)])
  313. msg = {"task_id": scheduler_id,
  314. "device_switch": 0 if int(actions) == 1 else 1}
  315. celery_obj.creat_crontab_task(tz, end_task_id, MQTT_TASK, end_minute, end_hour, repeat,
  316. args=[serial_number, topic_name, msg, end_task_id, 1,
  317. device_id, json.dumps(scheduler_data)])
  318. elif actions_type == '3': # 间隔任务
  319. minute = int(actions)
  320. task_id = 'switchscheduler_{}'.format(scheduler_id) # 开始任务id
  321. msg = {"task_id": scheduler_id,
  322. "device_switch": -1}
  323. if minute >= 60:
  324. hour = '{}-{}/{}'.format(start_hour, end_hour, minute // 60)
  325. minute = start_minute
  326. else:
  327. hour = '{}-{}'.format(start_hour, end_hour)
  328. minute = '*/{}'.format(minute)
  329. celery_obj.creat_crontab_task(tz, task_id, MQTT_TASK, minute, hour, repeat,
  330. args=[serial_number, topic_name, msg, task_id, 1,
  331. device_id, json.dumps(scheduler_data)])
  332. else:
  333. return response.json(444, {'param': 'actionsType'})
  334. return response.json(0)
  335. except Exception as e:
  336. print(e)
  337. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  338. @staticmethod
  339. def edit_scheduler_status(request_dict, response):
  340. """
  341. 修改排程计划状态
  342. @param request_dict: 请求参数
  343. @request_dict deviceId: 设备id
  344. @request_dict schedulerId: 排程计划id
  345. @request_dict isExecute: 修改状态
  346. @param response: 响应对象
  347. @return: response
  348. """
  349. device_id = request_dict.get('deviceId', None)
  350. scheduler_id = request_dict.get('schedulerId', None)
  351. is_execute = request_dict.get('isExecute', None)
  352. if not all([device_id, scheduler_id, is_execute]):
  353. return response.json(444, {'param': 'deviceId,schedulerId,isExecute'})
  354. try:
  355. is_execute = int(is_execute)
  356. celery_obj = CeleryBeatObj()
  357. if is_execute:
  358. celery_obj.enable_task('switchscheduler_{}'.format(scheduler_id))
  359. celery_obj.enable_task('switchscheduler_{}_1'.format(scheduler_id))
  360. celery_obj.enable_task('switchscheduler_{}_2'.format(scheduler_id))
  361. else:
  362. celery_obj.disable_task('switchscheduler_{}'.format(scheduler_id))
  363. celery_obj.disable_task('switchscheduler_{}_1'.format(scheduler_id))
  364. celery_obj.disable_task('switchscheduler_{}_2'.format(scheduler_id))
  365. SwitchScheduler.objects.filter(device_id=device_id, id=scheduler_id).update(is_execute=is_execute)
  366. return response.json(0)
  367. except Exception as e:
  368. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  369. @staticmethod
  370. def delete_scheduler(request_dict, response):
  371. """
  372. 删除排程计划
  373. @param request_dict: 请求参数
  374. @request_dict deviceId: 设备id
  375. @request_dict schedulerId: 排程计划id
  376. @param response: 响应对象
  377. @return: response
  378. """
  379. device_id = request_dict.get('deviceId', None)
  380. scheduler_id = request_dict.get('schedulerId', None)
  381. if not scheduler_id:
  382. return response.json(444, {'error param': 'deviceId or schedulerId'})
  383. try:
  384. delete_flag = SwitchScheduler.objects.filter(device_id=device_id, id=scheduler_id).delete()
  385. if not delete_flag[0]:
  386. return response.json(173)
  387. celery_obj = CeleryBeatObj()
  388. celery_obj.del_task('switchscheduler_{}'.format(scheduler_id)) # 删除排程任务
  389. celery_obj.del_task('switchscheduler_{}_1'.format(scheduler_id))
  390. celery_obj.del_task('switchscheduler_{}_2'.format(scheduler_id))
  391. return response.json(0)
  392. except Exception as e:
  393. print(e)
  394. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  395. @staticmethod
  396. def get_timer_setting(request_dict, response):
  397. """
  398. 获取计时器
  399. @param request_dict: 请求参数
  400. @request_dict deviceId: 设备id
  401. @param response: 响应对象
  402. @return: response
  403. """
  404. device_id = request_dict.get('deviceId', None)
  405. if not device_id:
  406. return response.json(444)
  407. try:
  408. key = 'Switch-Timer-' + device_id
  409. redis_obj = RedisObject()
  410. timer_info = redis_obj.get_all_hash_data(key)
  411. if not timer_info:
  412. res = {'timePoint': -1, 'countdownTime': -1, 'actions': -1, 'timerStatus': -1}
  413. else:
  414. res = timer_info
  415. return response.json(0, res)
  416. except Exception as e:
  417. print(e)
  418. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  419. @staticmethod
  420. def add_or_edit_timer(request_dict, response):
  421. """
  422. 添加/编辑计时器
  423. @param request_dict: 请求参数
  424. @request_dict deviceId: 设备id
  425. @request_dict CountdownTime: 倒计时时间(秒)
  426. @request_dict timePointDeviceWillDoing: 设备将会
  427. @request_dict timerStatus: 计时器状态
  428. @param response: 响应对象
  429. @return: response
  430. """
  431. is_edit = request_dict.get('isEdit', None)
  432. device_id = request_dict.get('deviceId', None)
  433. countdown_time = request_dict.get('countdownTime', None)
  434. actions = request_dict.get('actions', None)
  435. timer_status = request_dict.get('timerStatus', None)
  436. if not all([device_id, countdown_time, actions]):
  437. return response.json(444, {'param': 'deviceId, countdownTime, actions'})
  438. device_qs = Device_Info.objects.filter(id=device_id).values('serial_number', 'userID')
  439. if not device_qs.exists():
  440. return response.json(173)
  441. try:
  442. now_time = int(time.time())
  443. countdown_time = int(countdown_time)
  444. serial_number = device_qs[0]['serial_number']
  445. user_id = device_qs[0]['userID']
  446. tz = CommonService.get_user_tz(user_id)
  447. celery_obj = CeleryBeatObj()
  448. redis_obj = RedisObject()
  449. task_id = 'switchtimer_{}'.format(device_id)
  450. topic_name = TIMER_TOPIC_NAME.format(serial_number)
  451. key = 'Switch-Timer-' + device_id
  452. implement_time = now_time + countdown_time
  453. redis_dict = {'timePoint': implement_time,
  454. 'countdownTime': countdown_time,
  455. 'actions': actions,
  456. 'timerStatus': timer_status}
  457. with transaction.atomic():
  458. celery_obj.del_task(task_id)
  459. if is_edit:
  460. if not timer_status:
  461. return response.json(444, {'param': 'timerStatus'})
  462. timer_status = int(timer_status)
  463. if timer_status == 0: # 暂停计时器
  464. redis_dict['timePoint'] = -1
  465. redis_obj.set_hash_data(key, redis_dict)
  466. redis_obj.set_persist(key)
  467. return response.json(0)
  468. redis_obj.set_hash_data(key, redis_dict)
  469. redis_obj.set_expire(key, countdown_time)
  470. msg = {'device_switch': actions, 'task_id': task_id}
  471. celery_obj.creat_clocked_task(task_id, MQTT_TASK, implement_time, tz,
  472. args=[serial_number, topic_name, msg, task_id, 2,
  473. device_id, json.dumps(redis_dict)])
  474. return response.json(0)
  475. except Exception as e:
  476. print(e)
  477. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  478. @staticmethod
  479. def create_scheduler_log(request_dict, response):
  480. """
  481. 生成执行日志
  482. @param request_dict: 请求参数
  483. @request_dict serialNumber: 设备序列号
  484. @request_dict schedulerId: 排程id
  485. @request_dict status: 执行状态
  486. @param response: 响应对象
  487. @return: response
  488. """
  489. serial_number = request_dict.get('serial_number', None)
  490. event_type = request_dict.get('event_type', None)
  491. scheduler_id = request_dict.get('task_id', None)
  492. operate_status = request_dict.get('status', None)
  493. switch_status = request_dict.get('switch_status', None)
  494. send_time = request_dict.get('send_time', None)
  495. implement_time = request_dict.get('implement_time', None)
  496. if not all([serial_number, scheduler_id, operate_status, switch_status, implement_time]):
  497. return response.json(444, {
  498. 'error param': 'serial_number, task_id, status, switch_status, implement_time'})
  499. device_qs = Device_Info.objects.filter(serial_number=serial_number).values('id')
  500. if not device_qs.exists():
  501. return response.json(173)
  502. device_id = device_qs[0]['id']
  503. try:
  504. scene_log = {
  505. 'status': operate_status,
  506. 'created_time': implement_time,
  507. }
  508. if event_type == '1': # 排程任务
  509. scheduler_qs = SwitchScheduler.objects.filter(device_id=device_id, id=scheduler_id).values(
  510. 'time_type_radio',
  511. 'time_point',
  512. 'start_time',
  513. 'end_time',
  514. 'actions',
  515. 'actions_type',
  516. 'slow_speed',
  517. 'repeat')
  518. if not scheduler_qs.exists():
  519. return response.json(173)
  520. scene_qs = SceneLog.objects.filter(created_time=send_time, device_id=device_id, scene_id=scheduler_id)
  521. tasks = json.dumps(scheduler_qs[0])
  522. scene_id = scheduler_id
  523. elif event_type == '2': # 计时器任务
  524. scene_qs = SceneLog.objects.filter(created_time=send_time, device_id=device_id, scene_name=scheduler_id)
  525. tasks = json.dumps({'timePoint': int(send_time), 'actions': int(switch_status)})
  526. scene_id = 0
  527. elif event_type == '4':
  528. scene_log['tasks'] = json.dumps({'timePoint': int(implement_time), 'actions': int(switch_status)})
  529. scene_log['scene_id'] = 0
  530. scene_log['scene_name'] = 'switchmanual'
  531. scene_log['device_id'] = device_id
  532. SceneLog.objects.create(**scene_log)
  533. return response.json(0)
  534. else:
  535. return response.json(444, {'error param': 'event_type'})
  536. if scene_qs.exists():
  537. scene_qs.update(**scene_log)
  538. else:
  539. scene_log['tasks'] = tasks
  540. scene_log['scene_id'] = scene_id
  541. scene_log['scene_name'] = scene_id
  542. scene_log['device_id'] = device_id
  543. SceneLog.objects.create(**scene_log)
  544. return response.json(0)
  545. except Exception as e:
  546. print(e)
  547. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  548. @staticmethod
  549. def get_scheduler_log(request_dict, response):
  550. """
  551. 查询排程执行日志
  552. @param request_dict: 请求参数
  553. @request_dict deviceId: 设备id
  554. @param response: 响应对象
  555. @return: response
  556. """
  557. device_id = request_dict.get('deviceId', None)
  558. if not device_id:
  559. return response.json(444, {'error param': 'deviceId'})
  560. try:
  561. scene_qs = SceneLog.objects.filter(device_id=device_id).values('tasks', 'status', 'created_time', 'id')
  562. res = []
  563. for item in scene_qs:
  564. res.append({
  565. 'id': item['id'],
  566. 'tasks': json.loads(item['tasks']),
  567. 'status': item['status'],
  568. 'created_time': item['created_time']
  569. })
  570. return response.json(0, res)
  571. except Exception as e:
  572. print(e)
  573. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  574. @staticmethod
  575. def reset(request_dict, response):
  576. """
  577. 重置设备
  578. @param request_dict: 请求参数
  579. @request_dict serialNumber: 设备序列号
  580. @param response: 响应对象
  581. @return: response
  582. """
  583. serial_number = request_dict.get('serial_number', None)
  584. if not serial_number:
  585. return response.json(444, {'error param': 'serial_number'})
  586. device_qs = Device_Info.objects.filter(serial_number=serial_number).values('id')
  587. if not device_qs.exists():
  588. return response.json(173)
  589. device_id = device_qs[0]['device_id']
  590. try:
  591. # 删除智能开关数据
  592. SwitchDimmingSettings.objects.filter(device_id=device_id).delete()
  593. scheduler_qs = SwitchScheduler.objects.filter(device_id=device_id)
  594. if scheduler_qs.exists():
  595. celery_obj = CeleryBeatObj()
  596. for scheduler in scheduler_qs:
  597. scheduler_id = scheduler.id
  598. celery_obj.del_task('switchscheduler_{}'.format(scheduler_id)) # 删除排程任务
  599. celery_obj.del_task('switchscheduler_{}_1'.format(scheduler_id))
  600. celery_obj.del_task('switchscheduler_{}_2'.format(scheduler_id))
  601. scheduler_qs.delete()
  602. SceneLog.objects.filter(device_id=device_id).delete()
  603. FamilyRoomDevice.objects.filter(device_id=device_id).delete()
  604. Device_Info.objects.filter(id=device_id).delete()
  605. except Exception as e:
  606. print(e)
  607. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  608. @staticmethod
  609. def del_switch(device_id, serial_number):
  610. """
  611. 删除开关
  612. @param device_id: 设备id
  613. @param serial_number: 设备序列号
  614. @return: response
  615. """
  616. try:
  617. SwitchDimmingSettings.objects.filter(device_id=device_id).delete()
  618. scheduler_qs = SwitchScheduler.objects.filter(device_id=device_id)
  619. if scheduler_qs.exists():
  620. celery_obj = CeleryBeatObj()
  621. for scheduler in scheduler_qs:
  622. scheduler_id = scheduler.id
  623. celery_obj.del_task('switchscheduler_{}'.format(scheduler_id)) # 删除排程任务
  624. celery_obj.del_task('switchscheduler_{}_1'.format(scheduler_id))
  625. celery_obj.del_task('switchscheduler_{}_2'.format(scheduler_id))
  626. scheduler_qs.delete()
  627. SceneLog.objects.filter(device_id=device_id).delete()
  628. msg = {
  629. "opcode": 1 # 重置智能开关
  630. }
  631. topic_name = RESET_SWITCH_TOPIC_NAME.format(serial_number)
  632. result = CommonService.req_publish_mqtt_msg(serial_number, topic_name, msg)
  633. LOGGER.info('执行重置开关mqtt结果:{}'.format(result))
  634. except Exception as e:
  635. print(e)
  636. LOGGER.info('error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))