SmartSwitchController.py 33 KB

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