SmartSwitchController.py 33 KB

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