SmartSwitchController.py 31 KB

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