SmartSwitchController.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  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', 0)
  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. time_point = int(time_point)
  221. if time_point > 86400:
  222. return response.json(444, {'param': 'timePoint'})
  223. scheduler_data = {
  224. 'device_id': device_id,
  225. 'time_type_radio': time_type_radio,
  226. 'time_point': time_point,
  227. 'actions': actions,
  228. 'actions_type': actions_type,
  229. 'slow_speed': slow_speed,
  230. 'repeat': repeat
  231. }
  232. elif time_type_radio == 2: # 时间段
  233. if not all([start_time, end_time]):
  234. return response.json(444, {'param': 'startTime,endTime'})
  235. start_time = int(start_time)
  236. end_time = int(end_time)
  237. if start_time >= 86400 or end_time > 86400 or start_time == end_time:
  238. return response.json(444, {'param': 'startTime,endTime'})
  239. scheduler_data = {
  240. 'device_id': device_id,
  241. 'time_type_radio': time_type_radio,
  242. 'start_time': start_time,
  243. 'end_time': end_time,
  244. 'actions': actions,
  245. 'actions_type': actions_type,
  246. 'repeat': repeat
  247. }
  248. else:
  249. return response.json(444, {'param': 'timeTypeRadio'})
  250. try:
  251. with transaction.atomic():
  252. celery_obj = CeleryBeatObj()
  253. if is_edit:
  254. if not scheduler_id:
  255. return response.json(444, {'param': 'schedulerId'})
  256. update_flag = SwitchScheduler.objects.filter(device_id=device_id, id=scheduler_id).update(
  257. **scheduler_data)
  258. if not update_flag:
  259. return response.json(173)
  260. celery_obj.del_task('switchscheduler_{}'.format(scheduler_id))
  261. celery_obj.del_task('switchscheduler_{}_1'.format(scheduler_id))
  262. celery_obj.del_task('switchscheduler_{}_2'.format(scheduler_id))
  263. else:
  264. switch_qs = SwitchScheduler.objects.create(**scheduler_data)
  265. scheduler_id = switch_qs.id
  266. # 设置排程任务
  267. serial_number = device_qs[0]['serial_number']
  268. user_id = device_qs[0]['userID']
  269. tz = CommonService.get_user_tz(user_id)
  270. topic_name = APSCHEDULER_TOPIC_NAME.format(serial_number)
  271. if time_type_radio == 1: # 时间点任务
  272. task_id = 'switchscheduler_{}'.format(scheduler_id)
  273. if actions_type == '1': # 开启或关闭
  274. msg = {
  275. "task_id": scheduler_id,
  276. "device_switch": int(actions), # 设备开关-1:反转,0:关,1:开,2:预设亮度
  277. "slow_time": slow_speed
  278. }
  279. elif actions_type == '2': # 开启且设置亮度
  280. msg = {
  281. "task_id": scheduler_id,
  282. "device_switch": 2,
  283. "pwm_control": int(actions),
  284. 'slow_time': slow_speed
  285. }
  286. else:
  287. return response.json(444, {'param': 'actionsType'})
  288. time_point_hour = int(time_point / 60 // 60)
  289. time_point_minute = int(time_point / 60 % 60)
  290. celery_obj.creat_crontab_task(tz, task_id, MQTT_TASK, time_point_minute, time_point_hour, repeat,
  291. args=[serial_number, topic_name, msg, task_id, 1, device_id,
  292. json.dumps(scheduler_data)])
  293. else: # 时间段任务
  294. start_hour = int(start_time / 60 // 60)
  295. start_minute = int(start_time / 60 % 60)
  296. end_hour = int(end_time / 60 // 60)
  297. end_minute = int(end_time / 60 % 60)
  298. if actions_type == '1':
  299. begin_task_id = 'switchscheduler_{}_1'.format(scheduler_id) # 开始任务id
  300. end_task_id = 'switchscheduler_{}_2'.format(scheduler_id) # 结束任务id
  301. msg = {"task_id": scheduler_id,
  302. "device_switch": int(actions)}
  303. celery_obj.creat_crontab_task(tz, begin_task_id, MQTT_TASK, start_minute, start_hour, repeat,
  304. args=[serial_number, topic_name, msg, begin_task_id, 1,
  305. device_id, json.dumps(scheduler_data)])
  306. msg = {"task_id": scheduler_id,
  307. "device_switch": 0 if int(actions) == 1 else 1}
  308. celery_obj.creat_crontab_task(tz, end_task_id, MQTT_TASK, end_minute, end_hour, repeat,
  309. args=[serial_number, topic_name, msg, end_task_id, 1,
  310. device_id, json.dumps(scheduler_data)])
  311. elif actions_type == '3': # 间隔任务
  312. minute = int(actions)
  313. task_id = 'switchscheduler_{}'.format(scheduler_id) # 开始任务id
  314. msg = {"task_id": scheduler_id,
  315. "device_switch": -1}
  316. if minute >= 60:
  317. hour = '{}-{}/{}'.format(start_hour, end_hour, minute // 60)
  318. minute = start_minute
  319. else:
  320. hour = '{}-{}'.format(start_hour, end_hour)
  321. minute = '*/{}'.format(minute)
  322. celery_obj.creat_crontab_task(tz, task_id, MQTT_TASK, minute, hour, repeat,
  323. args=[serial_number, topic_name, msg, task_id, 1,
  324. device_id, json.dumps(scheduler_data)])
  325. else:
  326. return response.json(444, {'param': 'actionsType'})
  327. return response.json(0)
  328. except Exception as e:
  329. print(e)
  330. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  331. @staticmethod
  332. def edit_scheduler_status(request_dict, response):
  333. """
  334. 修改排程计划状态
  335. @param request_dict: 请求参数
  336. @request_dict deviceId: 设备id
  337. @request_dict schedulerId: 排程计划id
  338. @request_dict isExecute: 修改状态
  339. @param response: 响应对象
  340. @return: response
  341. """
  342. device_id = request_dict.get('deviceId', None)
  343. scheduler_id = request_dict.get('schedulerId', None)
  344. is_execute = request_dict.get('isExecute', None)
  345. if not all([device_id, scheduler_id, is_execute]):
  346. return response.json(444, {'param': 'deviceId,schedulerId,isExecute'})
  347. try:
  348. is_execute = int(is_execute)
  349. celery_obj = CeleryBeatObj()
  350. if is_execute:
  351. celery_obj.enable_task('switchscheduler_{}'.format(scheduler_id))
  352. celery_obj.enable_task('switchscheduler_{}_1'.format(scheduler_id))
  353. celery_obj.enable_task('switchscheduler_{}_2'.format(scheduler_id))
  354. else:
  355. celery_obj.disable_task('switchscheduler_{}'.format(scheduler_id))
  356. celery_obj.disable_task('switchscheduler_{}_1'.format(scheduler_id))
  357. celery_obj.disable_task('switchscheduler_{}_2'.format(scheduler_id))
  358. SwitchScheduler.objects.filter(device_id=device_id, id=scheduler_id).update(is_execute=is_execute)
  359. return response.json(0)
  360. except Exception as e:
  361. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  362. @staticmethod
  363. def delete_scheduler(request_dict, response):
  364. """
  365. 删除排程计划
  366. @param request_dict: 请求参数
  367. @request_dict deviceId: 设备id
  368. @request_dict schedulerId: 排程计划id
  369. @param response: 响应对象
  370. @return: response
  371. """
  372. device_id = request_dict.get('deviceId', None)
  373. scheduler_id = request_dict.get('schedulerId', None)
  374. if not scheduler_id:
  375. return response.json(444, {'error param': 'deviceId or schedulerId'})
  376. try:
  377. delete_flag = SwitchScheduler.objects.filter(device_id=device_id, id=scheduler_id).delete()
  378. if not delete_flag[0]:
  379. return response.json(173)
  380. celery_obj = CeleryBeatObj()
  381. celery_obj.del_task('switchscheduler_{}'.format(scheduler_id)) # 删除排程任务
  382. celery_obj.del_task('switchscheduler_{}_1'.format(scheduler_id))
  383. celery_obj.del_task('switchscheduler_{}_2'.format(scheduler_id))
  384. return response.json(0)
  385. except Exception as e:
  386. print(e)
  387. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  388. @staticmethod
  389. def get_timer_setting(request_dict, response):
  390. """
  391. 获取计时器
  392. @param request_dict: 请求参数
  393. @request_dict deviceId: 设备id
  394. @param response: 响应对象
  395. @return: response
  396. """
  397. device_id = request_dict.get('deviceId', None)
  398. if not device_id:
  399. return response.json(444)
  400. try:
  401. key = 'Switch-Timer-' + device_id
  402. redis_obj = RedisObject()
  403. timer_info = redis_obj.get_all_hash_data(key)
  404. if not timer_info:
  405. res = {'timePoint': -1, 'countdownTime': -1, 'actions': -1, 'timerStatus': -1}
  406. else:
  407. res = timer_info
  408. return response.json(0, res)
  409. except Exception as e:
  410. print(e)
  411. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  412. @staticmethod
  413. def add_or_edit_timer(request_dict, response):
  414. """
  415. 添加/编辑计时器
  416. @param request_dict: 请求参数
  417. @request_dict deviceId: 设备id
  418. @request_dict CountdownTime: 倒计时时间(秒)
  419. @request_dict timePointDeviceWillDoing: 设备将会
  420. @request_dict timerStatus: 计时器状态
  421. @param response: 响应对象
  422. @return: response
  423. """
  424. is_edit = request_dict.get('isEdit', None)
  425. device_id = request_dict.get('deviceId', None)
  426. countdown_time = request_dict.get('countdownTime', None)
  427. actions = request_dict.get('actions', None)
  428. timer_status = request_dict.get('timerStatus', None)
  429. if not all([device_id, countdown_time, actions]):
  430. return response.json(444, {'param': 'deviceId, countdownTime, actions'})
  431. device_qs = Device_Info.objects.filter(id=device_id).values('serial_number', 'userID')
  432. if not device_qs.exists():
  433. return response.json(173)
  434. try:
  435. now_time = int(time.time())
  436. countdown_time = int(countdown_time)
  437. serial_number = device_qs[0]['serial_number']
  438. user_id = device_qs[0]['userID']
  439. tz = CommonService.get_user_tz(user_id)
  440. celery_obj = CeleryBeatObj()
  441. redis_obj = RedisObject()
  442. task_id = 'switchtimer_{}'.format(device_id)
  443. topic_name = TIMER_TOPIC_NAME.format(serial_number)
  444. key = 'Switch-Timer-' + device_id
  445. implement_time = now_time + countdown_time
  446. redis_dict = {'timePoint': implement_time,
  447. 'countdownTime': countdown_time,
  448. 'actions': actions,
  449. 'timerStatus': timer_status}
  450. with transaction.atomic():
  451. celery_obj.del_task(task_id)
  452. if is_edit:
  453. if not timer_status:
  454. return response.json(444, {'param': 'timerStatus'})
  455. timer_status = int(timer_status)
  456. if timer_status == 0: # 暂停计时器
  457. redis_dict['timePoint'] = -1
  458. redis_obj.set_hash_data(key, redis_dict)
  459. redis_obj.set_persist(key)
  460. return response.json(0)
  461. redis_obj.set_hash_data(key, redis_dict)
  462. redis_obj.set_expire(key, countdown_time)
  463. msg = {'device_switch': actions, 'task_id': task_id}
  464. celery_obj.creat_clocked_task(task_id, MQTT_TASK, implement_time, tz,
  465. args=[serial_number, topic_name, msg, task_id, 2,
  466. device_id, json.dumps(redis_dict)])
  467. return response.json(0)
  468. except Exception as e:
  469. print(e)
  470. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  471. @staticmethod
  472. def create_scheduler_log(request_dict, response):
  473. """
  474. 生成执行日志
  475. @param request_dict: 请求参数
  476. @request_dict serialNumber: 设备序列号
  477. @request_dict schedulerId: 排程id
  478. @request_dict status: 执行状态
  479. @param response: 响应对象
  480. @return: response
  481. """
  482. serial_number = request_dict.get('serial_number', None)
  483. event_type = request_dict.get('event_type', None)
  484. scheduler_id = request_dict.get('task_id', None)
  485. operate_status = request_dict.get('status', None)
  486. switch_status = request_dict.get('switch_status', None)
  487. send_time = request_dict.get('send_time', None)
  488. implement_time = request_dict.get('implement_time', None)
  489. if not all([serial_number, scheduler_id, operate_status, switch_status, implement_time]):
  490. return response.json(444, {
  491. 'error param': 'serial_number, task_id, status, switch_status, implement_time'})
  492. device_qs = Device_Info.objects.filter(serial_number=serial_number).values('id')
  493. if not device_qs.exists():
  494. return response.json(173)
  495. device_id = device_qs[0]['id']
  496. try:
  497. scene_log = {
  498. 'status': operate_status,
  499. 'created_time': implement_time,
  500. }
  501. if event_type == '1': # 排程任务
  502. scheduler_qs = SwitchScheduler.objects.filter(device_id=device_id, id=scheduler_id).values(
  503. 'time_type_radio',
  504. 'time_point',
  505. 'start_time',
  506. 'end_time',
  507. 'actions',
  508. 'actions_type',
  509. 'slow_speed',
  510. 'repeat')
  511. if not scheduler_qs.exists():
  512. return response.json(173)
  513. scene_qs = SceneLog.objects.filter(created_time=send_time, device_id=device_id, scene_id=scheduler_id)
  514. tasks = json.dumps(scheduler_qs[0])
  515. scene_id = scheduler_id
  516. elif event_type == '2': # 计时器任务
  517. scene_qs = SceneLog.objects.filter(created_time=send_time, device_id=device_id, scene_name=scheduler_id)
  518. tasks = json.dumps({'timePoint': int(send_time), 'actions': int(switch_status)})
  519. scene_id = 0
  520. elif event_type == '4':
  521. scene_log['tasks'] = json.dumps({'timePoint': int(implement_time), 'actions': int(switch_status)})
  522. scene_log['scene_id'] = 0
  523. scene_log['scene_name'] = 'switchmanual'
  524. scene_log['device_id'] = device_id
  525. SceneLog.objects.create(**scene_log)
  526. return response.json(0)
  527. else:
  528. return response.json(444, {'error param': 'event_type'})
  529. if scene_qs.exists():
  530. scene_qs.update(**scene_log)
  531. else:
  532. scene_log['tasks'] = tasks
  533. scene_log['scene_id'] = scene_id
  534. scene_log['scene_name'] = scene_id
  535. scene_log['device_id'] = device_id
  536. SceneLog.objects.create(**scene_log)
  537. return response.json(0)
  538. except Exception as e:
  539. print(e)
  540. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  541. @staticmethod
  542. def get_scheduler_log(request_dict, response):
  543. """
  544. 查询排程执行日志
  545. @param request_dict: 请求参数
  546. @request_dict deviceId: 设备id
  547. @param response: 响应对象
  548. @return: response
  549. """
  550. device_id = request_dict.get('deviceId', None)
  551. if not device_id:
  552. return response.json(444, {'error param': 'deviceId'})
  553. try:
  554. scene_qs = SceneLog.objects.filter(device_id=device_id).values('tasks', 'status', 'created_time', 'id')
  555. res = []
  556. for item in scene_qs:
  557. res.append({
  558. 'id': item['id'],
  559. 'tasks': json.loads(item['tasks']),
  560. 'status': item['status'],
  561. 'created_time': item['created_time']
  562. })
  563. return response.json(0, res)
  564. except Exception as e:
  565. print(e)
  566. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  567. @staticmethod
  568. def reset(request_dict, response):
  569. """
  570. 重置设备
  571. @param request_dict: 请求参数
  572. @request_dict serialNumber: 设备序列号
  573. @param response: 响应对象
  574. @return: response
  575. """
  576. serial_number = request_dict.get('serial_number', None)
  577. if not serial_number:
  578. return response.json(444, {'error param': 'serial_number'})
  579. device_qs = Device_Info.objects.filter(serial_number=serial_number).values('id')
  580. if not device_qs.exists():
  581. return response.json(173)
  582. device_id = device_qs[0]['device_id']
  583. try:
  584. # 删除智能开关数据
  585. SwitchDimmingSettings.objects.filter(device_id=device_id).delete()
  586. scheduler_qs = SwitchScheduler.objects.filter(device_id=device_id)
  587. if scheduler_qs.exists():
  588. celery_obj = CeleryBeatObj()
  589. for scheduler in scheduler_qs:
  590. scheduler_id = scheduler.id
  591. celery_obj.del_task('switchscheduler_{}'.format(scheduler_id)) # 删除排程任务
  592. celery_obj.del_task('switchscheduler_{}_1'.format(scheduler_id))
  593. celery_obj.del_task('switchscheduler_{}_2'.format(scheduler_id))
  594. scheduler_qs.delete()
  595. SceneLog.objects.filter(device_id=device_id).delete()
  596. FamilyRoomDevice.objects.filter(device_id=device_id).delete()
  597. Device_Info.objects.filter(id=device_id).delete()
  598. except Exception as e:
  599. print(e)
  600. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  601. @staticmethod
  602. def del_switch(device_id, serial_number):
  603. """
  604. 删除开关
  605. @param device_id: 设备id
  606. @param serial_number: 设备序列号
  607. @return: response
  608. """
  609. try:
  610. SwitchDimmingSettings.objects.filter(device_id=device_id).delete()
  611. scheduler_qs = SwitchScheduler.objects.filter(device_id=device_id)
  612. if scheduler_qs.exists():
  613. celery_obj = CeleryBeatObj()
  614. for scheduler in scheduler_qs:
  615. scheduler_id = scheduler.id
  616. celery_obj.del_task('switchscheduler_{}'.format(scheduler_id)) # 删除排程任务
  617. celery_obj.del_task('switchscheduler_{}_1'.format(scheduler_id))
  618. celery_obj.del_task('switchscheduler_{}_2'.format(scheduler_id))
  619. scheduler_qs.delete()
  620. SceneLog.objects.filter(device_id=device_id).delete()
  621. msg = {
  622. "opcode": 1 # 重置智能开关
  623. }
  624. topic_name = RESET_SWITCH_TOPIC_NAME.format(serial_number)
  625. result = CommonService.req_publish_mqtt_msg(serial_number, topic_name, msg)
  626. LOGGER.info('执行重置开关mqtt结果:{}'.format(result))
  627. except Exception as e:
  628. print(e)
  629. LOGGER.info('error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))