SmartSwitchController.py 31 KB

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