SmartSwitchController.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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 os
  10. import threading
  11. import time
  12. from django.views import View
  13. from Model.models import SwitchInfo, SwitchDimmingSettings, SwitchChronopher, Device_Info, SceneLog, FamilyRoomDevice
  14. from Service.CommonService import CommonService
  15. from Object.ApschedulerObject import ApschedulerObject
  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/smart-switch/{}' # 重置设备
  20. class SmartSwitchView(View):
  21. def get(self, request, *args, **kwargs):
  22. request.encoding = 'utf-8'
  23. operation = kwargs.get('operation')
  24. return self.validation(request.GET, request, operation)
  25. def post(self, request, *args, **kwargs):
  26. request.encoding = 'utf-8'
  27. operation = kwargs.get('operation')
  28. return self.validation(request.POST, request, operation)
  29. def validation(self, request_dict, request, operation):
  30. token_code, user_id, response = CommonService.verify_token_get_user_id(request_dict, request)
  31. if operation == 'switch-report-log': # 设备上报执行日志
  32. return self.create_log(request_dict, response)
  33. elif operation == 'reset': # 设备重置
  34. return self.reset(request_dict, response)
  35. else:
  36. if token_code != 0:
  37. return response.json(token_code)
  38. if operation == 'get-switch-info': # 设备获取智能开关数据
  39. return self.get_switch_info(request_dict, response)
  40. elif operation == 'get-dimming-setting': # 获取智能开关调光设置
  41. return self.get_dimming_setting(request_dict, response)
  42. elif operation == 'get-chronopher-setting': # 获取定时计划
  43. return self.get_chronopher_setting(request_dict, response)
  44. elif operation == 'add-or-edit-chronopher': # 添加/编辑定时计划
  45. return self.add_or_edit_chronopher(request_dict, response)
  46. elif operation == 'delete-chronopher': # 删除定时计划
  47. return self.delete_chronopher(request_dict, response)
  48. elif operation == 'edit-dimming-correction': # 设置调光校正
  49. return self.edit_dimming_correction(request_dict, response)
  50. elif operation == 'edit-dimming-setting': # 修改智能开关调光设置
  51. return self.edit_dimming_setting(request_dict, response)
  52. elif operation == 'log': # 查询日志
  53. return self.get_log(request_dict, response)
  54. else:
  55. return response.json(414)
  56. @staticmethod
  57. def get_switch_info(request_dict, response):
  58. """
  59. 获取智能开关设备信息
  60. @param request_dict: 请求参数
  61. @request_dict deviceId: 设备id
  62. @param response: 响应对象
  63. @return: response
  64. """
  65. device_id = request_dict.get('deviceId', None)
  66. if not device_id:
  67. return response.json(444)
  68. try:
  69. switch_info_qs = SwitchInfo.objects.filter(device_id=device_id).values()
  70. if not switch_info_qs.exists():
  71. return response.json(173)
  72. res = {
  73. 'model': switch_info_qs[0]['model'],
  74. 'hardwareVersion': switch_info_qs[0]['hardware_version'],
  75. 'firmwareVersion': switch_info_qs[0]['firmware_version'],
  76. 'mac': switch_info_qs[0]['mac'],
  77. }
  78. return response.json(0, res)
  79. except Exception as e:
  80. print(e)
  81. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  82. @staticmethod
  83. def get_dimming_setting(request_dict, response):
  84. """
  85. 获取智能开关调光设置信息
  86. @param request_dict: 请求参数
  87. @request_dict deviceId: 设备id
  88. @param response: 响应对象
  89. @return: response
  90. """
  91. device_id = request_dict.get('deviceId', None)
  92. if not device_id:
  93. return response.json(444)
  94. try:
  95. switch_setting_info_qs = SwitchDimmingSettings.objects.filter(device_id=device_id).values()
  96. if not switch_setting_info_qs.exists():
  97. return response.json(173)
  98. res = {
  99. 'clickTurnOnSpeed': switch_setting_info_qs[0]['click_turn_on_speed'],
  100. 'clickTurnOffSpeed': switch_setting_info_qs[0]['click_turn_off_speed'],
  101. 'doubleClick': switch_setting_info_qs[0]['double_click'],
  102. 'press': switch_setting_info_qs[0]['press'],
  103. 'doublePressClickTurnOnSpeed': switch_setting_info_qs[0]['double_press_click_turn_on_speed'],
  104. 'doublePressClickTurnOffSpeed': switch_setting_info_qs[0]['double_press_click_turn_off_speed'],
  105. 'dimmingCorrection': switch_setting_info_qs[0]['dimming_correction'],
  106. }
  107. return response.json(0, res)
  108. except Exception as e:
  109. print(e)
  110. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  111. @staticmethod
  112. def edit_dimming_correction(request_dict, response):
  113. """
  114. 修改智能开关调光校正
  115. @param request_dict: 请求参数
  116. @request_dict deviceId: 设备id
  117. @request_dict dimmingCorrection: 调光校正
  118. @param response: 响应对象
  119. @return: response
  120. """
  121. device_id = request_dict.get('deviceId', None)
  122. dimming_correction = request_dict.get('dimmingCorrection', None)
  123. if not device_id:
  124. return response.json(444)
  125. try:
  126. SwitchDimmingSettings.objects.filter(device_id=device_id).update(dimming_correction=dimming_correction)
  127. return response.json(0)
  128. except Exception as e:
  129. print(e)
  130. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  131. @staticmethod
  132. def edit_dimming_setting(request_dict, response):
  133. """
  134. 修改智能开关调光设置
  135. @param request_dict: 请求参数
  136. @request_dict deviceId: 设备id
  137. @request_dict clickTurnOnSpeed: 单击开启速度
  138. @request_dict clickTurnOffSpeed: 单击关闭速度
  139. @request_dict doubleClick: 双击
  140. @request_dict press: 长按
  141. @request_dict doublePressClickTurnOnSpeed: 双击/长按开启速度
  142. @request_dict doublePressClickTurnOffSpeed: 双击/长按单击关闭速度
  143. @param response: 响应对象
  144. @return: response
  145. """
  146. device_id = request_dict.get('deviceId', None)
  147. click_turn_on_speed = request_dict.get('clickTurnOnSpeed', None)
  148. click_turn_off_speed = request_dict.get('clickTurnOffSpeed', None)
  149. double_click = request_dict.get('doubleClick', None)
  150. press = request_dict.get('press', None)
  151. double_press_click_turn_on_speed = request_dict.get('doublePressClickTurnOnSpeed', None)
  152. double_press_click_turn_off_speed = request_dict.get('doublePressClickTurnOffSpeed', None)
  153. if not device_id:
  154. return response.json(444)
  155. try:
  156. dimming_setting_data = {
  157. 'device_id': device_id,
  158. 'click_turn_on_speed': click_turn_on_speed,
  159. 'click_turn_off_speed': click_turn_off_speed,
  160. 'double_click': double_click,
  161. 'press': press,
  162. 'double_press_click_turn_on_speed': double_press_click_turn_on_speed,
  163. 'double_press_click_turn_off_speed': double_press_click_turn_off_speed
  164. }
  165. SwitchDimmingSettings.objects.filter(device_id=device_id).update(**dimming_setting_data)
  166. return response.json(0)
  167. except Exception as e:
  168. print(e)
  169. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  170. @staticmethod
  171. def get_chronopher_setting(request_dict, response):
  172. """
  173. 获取定时计划设置
  174. @param request_dict: 请求参数
  175. @request_dict deviceId: 设备id
  176. @param response: 响应对象
  177. @return: response
  178. """
  179. device_id = request_dict.get('deviceId', None)
  180. if not device_id:
  181. return response.json(444)
  182. try:
  183. switch_chronopher_qs = SwitchChronopher.objects.filter(device_id=device_id).values()
  184. if not switch_chronopher_qs.exists():
  185. return response.json(173)
  186. switch_chronopher_list = []
  187. for item in switch_chronopher_qs:
  188. switch_chronopher_list.append({
  189. 'chronopherId': item['id'],
  190. 'timeTypeRadio': item['time_type_radio'],
  191. 'timePoint': item['time_point'],
  192. 'timeQuantumStartTime': item['time_quantum_start_time'],
  193. 'timeQuantumEndTime': item['time_quantum_end_time'],
  194. 'timePointDeviceWillDoing': item['time_point_device_will_doing'],
  195. 'timeQuantumDeviceWillDoing': item['time_quantum_device_will_doing'],
  196. 'slowOpenOrCloseSpeed': item['slow_open_or_close_speed'],
  197. 'repeat': item['repeat'],
  198. })
  199. return response.json(0, {'list': switch_chronopher_list})
  200. except Exception as e:
  201. print(e)
  202. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  203. @staticmethod
  204. def add_or_edit_chronopher(request_dict, response):
  205. """
  206. 添加/编辑定时计划
  207. @param request_dict: 请求参数
  208. @request_dict deviceId: 设备id
  209. @request_dict chronopherId: 定时计划id
  210. @request_dict timeTypeRadio: 切换时间点/时间段
  211. @request_dict timePoint: 时间点
  212. @request_dict timeQuantumStartTime: 时间段开始时间
  213. @request_dict timeQuantumEndTime: 时间段结束时间
  214. @request_dict timePointDeviceWillDoing: 设备将会
  215. @request_dict timeQuantumDeviceWillDoing: 设备将会
  216. @request_dict slowOpenOrCloseSpeed: 缓慢开/关速度
  217. @request_dict repeat: 重复周期
  218. @param response: 响应对象
  219. @return: response
  220. """
  221. is_edit = request_dict.get('isEdit', None)
  222. device_id = request_dict.get('deviceId', None)
  223. chronopher_id = request_dict.get('chronopherId', None)
  224. time_type_radio = int(request_dict.get('timeTypeRadio', 0))
  225. time_point = request_dict.get('timePoint', None)
  226. time_quantum_start_time = request_dict.get('timeQuantumStartTime', None)
  227. time_quantum_end_time = request_dict.get('timeQuantumEndTime', None)
  228. time_point_device_will_doing = request_dict.get('timePointDeviceWillDoing', None)
  229. time_quantum_device_will_doing = request_dict.get('timeQuantumDeviceWillDoing', None)
  230. slow_open_or_close_speed = request_dict.get('slowOpenOrCloseSpeed', None)
  231. repeat = request_dict.get('repeat', None)
  232. if not all([device_id, repeat]):
  233. return response.json(444, {'param': 'deviceId,repeat'})
  234. device_qs = Device_Info.objects.filter(id=device_id).values('serial_number')
  235. if not device_qs.exists():
  236. return response.json(173)
  237. if time_type_radio == 1: # 时间点
  238. if not all([time_point, slow_open_or_close_speed]):
  239. return response.json(444, {'param': 'timePoint,slowOpenOrCloseSpeed'})
  240. chronopher_data = {
  241. 'device_id': device_id,
  242. 'time_type_radio': time_type_radio,
  243. 'time_point': time_point,
  244. 'time_point_device_will_doing': time_point_device_will_doing,
  245. 'slow_open_or_close_speed': slow_open_or_close_speed,
  246. 'repeat': repeat
  247. }
  248. elif time_type_radio == 2: # 时间段
  249. if not all([time_quantum_start_time, time_quantum_end_time]):
  250. return response.json(444, {'param': 'timeQuantumStartTime,timeQuantumEndTime'})
  251. time_quantum_start_time = int(time_quantum_start_time)
  252. time_quantum_end_time = int(time_quantum_end_time)
  253. chronopher_data = {
  254. 'device_id': device_id,
  255. 'time_type_radio': time_type_radio,
  256. 'time_quantum_start_time': time_quantum_start_time,
  257. 'time_quantum_end_time': time_quantum_end_time,
  258. 'time_quantum_device_will_doing': time_quantum_device_will_doing,
  259. 'repeat': repeat
  260. }
  261. else:
  262. return response.json(444, {'param': 'timeTypeRadio'})
  263. try:
  264. with transaction.atomic():
  265. apscheduler_obj = ApschedulerObject()
  266. if is_edit:
  267. if not chronopher_id:
  268. return response.json(444, {'param': 'timeTypeRadio'})
  269. update_flag = SwitchChronopher.objects.filter(device_id=device_id, id=chronopher_id).update(
  270. **chronopher_data)
  271. if not update_flag:
  272. return response.json(173)
  273. apscheduler_obj.del_job('switchchronopher_{}'.format(chronopher_id))
  274. apscheduler_obj.del_job('switchchronopher_{}_1'.format(chronopher_id))
  275. apscheduler_obj.del_job('switchchronopher_{}_2'.format(chronopher_id))
  276. else:
  277. switch_qs = SwitchChronopher.objects.create(**chronopher_data)
  278. chronopher_id = switch_qs.id
  279. # 设置定时任务
  280. serial_number = device_qs[0]['serial_number']
  281. topic_name = APSCHEDULER_TOPIC_NAME.format(serial_number)
  282. if time_type_radio == 1:
  283. task_id = 'switchchronopher_{}'.format(chronopher_id)
  284. if time_point_device_will_doing in ['0', '1']: # 开启或关闭
  285. msg = {
  286. "taskId": chronopher_id,
  287. "deviceSwitch": int(time_point_device_will_doing), # 设备开关-1:反转,0:关,1:开,2:预设亮度
  288. "slowTime": slow_open_or_close_speed
  289. }
  290. else: # 开启且设置亮度
  291. msg = {
  292. "taskId": chronopher_id,
  293. "deviceSwitch": 2,
  294. "pwmControl": int(time_point_device_will_doing),
  295. 'slowTime': slow_open_or_close_speed
  296. }
  297. time_str = datetime.datetime.fromtimestamp(int(time_point))
  298. apscheduler_obj.create_cron_job(SmartSwitchView.send_mqtt, task_id, repeat, time_str.hour,
  299. time_str.minute, [serial_number, topic_name, msg, task_id])
  300. else:
  301. start_hour = int(time_quantum_start_time / 60 // 60)
  302. start_minute = int(time_quantum_start_time / 60 % 60)
  303. end_hour = int(time_quantum_end_time / 60 // 60)
  304. end_minute = int(time_quantum_end_time / 60 % 60)
  305. if time_quantum_device_will_doing in ['0', '1']:
  306. begin_task_id = 'switchchronopher_{}_1'.format(chronopher_id) # 开始任务id
  307. end_task_id = 'switchchronopher_{}_2'.format(chronopher_id) # 结束任务id
  308. msg = {"taskId": chronopher_id,
  309. "deviceSwitch": int(time_quantum_device_will_doing)}
  310. apscheduler_obj.create_cron_job(SmartSwitchView.send_mqtt, begin_task_id, repeat, start_hour,
  311. start_minute, [serial_number, topic_name, msg, begin_task_id])
  312. msg = {"taskId": chronopher_id,
  313. "deviceSwitch": 0 if int(time_quantum_device_will_doing) == 1 else 1}
  314. apscheduler_obj.create_cron_job(SmartSwitchView.send_mqtt, end_task_id, repeat, end_hour,
  315. end_minute, [serial_number, topic_name, msg, end_task_id])
  316. else: # 间隔任务
  317. minute = int(time_quantum_device_will_doing)
  318. task_id = 'switchchronopher_{}'.format(chronopher_id) # 开始任务id
  319. msg = {"taskId": chronopher_id,
  320. "deviceSwitch": -1}
  321. if minute >= 60:
  322. hour = '{}-{}/{}'.format(start_hour, end_hour, minute // 60)
  323. minute = start_minute
  324. else:
  325. hour = '{}-{}'.format(start_hour, end_hour)
  326. minute = '{}/{}'.format(start_minute, minute)
  327. apscheduler_obj.create_cron_job(SmartSwitchView.send_mqtt, task_id, repeat, hour, minute,
  328. [serial_number, topic_name, msg, task_id])
  329. return response.json(0)
  330. except Exception as e:
  331. print(e)
  332. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  333. @staticmethod
  334. def delete_chronopher(request_dict, response):
  335. """
  336. 删除定时计划
  337. @param request_dict: 请求参数
  338. @request_dict deviceId: 设备id
  339. @request_dict chronopherId: 定时计划id
  340. @param response: 响应对象
  341. @return: response
  342. """
  343. device_id = request_dict.get('deviceId', None)
  344. chronopher_id = request_dict.get('chronopherId', None)
  345. if not chronopher_id:
  346. return response.json(444, {'error param': 'deviceId or chronopherId'})
  347. try:
  348. delete_flag = SwitchChronopher.objects.filter(device_id=device_id, id=chronopher_id).delete()
  349. if not delete_flag[0]:
  350. return response.json(173)
  351. apscheduler_obj = ApschedulerObject()
  352. apscheduler_obj.del_job('switchchronopher_{}'.format(chronopher_id)) # 删除定时任务
  353. apscheduler_obj.del_job('switchchronopher_{}_1'.format(chronopher_id))
  354. apscheduler_obj.del_job('switchchronopher_{}_2'.format(chronopher_id))
  355. return response.json(0)
  356. except Exception as e:
  357. print(e)
  358. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  359. @staticmethod
  360. def send_mqtt(serial_number, topic_name, msg, task_id):
  361. """
  362. 定时发送mqtt, (不要随意更改,否则定时任务不执行)
  363. @param serial_number: 设备序列号
  364. @param topic_name: 主题
  365. @param msg: 消息
  366. @param task_id: 任务id
  367. @return: response
  368. """
  369. result = CommonService.req_publish_mqtt_msg(serial_number, topic_name, msg)
  370. LOGGER.info('定时发送mqtt结果:{},参数:{},{},{},{},{},线程:{},进程:{}'.format(result, serial_number, topic_name, msg,
  371. int(time.time()), task_id,
  372. threading.get_ident(), os.getpid()))
  373. @staticmethod
  374. def create_log(request_dict, response):
  375. """
  376. 生成执行日志
  377. @param request_dict: 请求参数
  378. @request_dict serialNumber: 设备序列号
  379. @request_dict chronopherId: 排程id
  380. @request_dict status: 执行状态
  381. @param response: 响应对象
  382. @return: response
  383. """
  384. serial_number = request_dict.get('serialNumber', None)
  385. chronopher_id = request_dict.get('taskId', None)
  386. status = request_dict.get('status', None)
  387. implement_time = request_dict.get('implementTime', None)
  388. if not all([serial_number, chronopher_id, status, implement_time]):
  389. return response.json(444, {'error param': 'deviceId or chronopherId'})
  390. device_qs = Device_Info.objects.filter(serial_number=serial_number).values('id')
  391. if not device_qs.exists():
  392. return response.json(173)
  393. device_id = device_qs[0]['id']
  394. chronopher_qs = SwitchChronopher.objects.filter(device_id=device_id, id=chronopher_id).values(
  395. 'time_type_radio', 'time_point', 'time_quantum_start_time', 'time_quantum_end_time',
  396. 'time_point_device_will_doing', 'time_quantum_device_will_doing', 'slow_open_or_close_speed', 'repeat')
  397. if not chronopher_qs.exists():
  398. return response.json(173)
  399. try:
  400. scene_log = {
  401. 'scene_id': chronopher_id,
  402. 'device_id': device_id,
  403. 'tasks': json.dumps(chronopher_qs[0]),
  404. 'status': status,
  405. 'created_time': implement_time,
  406. }
  407. scene_qs = SceneLog.objects.filter(created_time=implement_time, device_id=device_id,
  408. scene_id=chronopher_id)
  409. if not scene_qs.exists():
  410. SceneLog.objects.create(**scene_log)
  411. return response.json(0)
  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 get_log(request_dict, response):
  417. """
  418. 查询执行日志
  419. @param request_dict: 请求参数
  420. @request_dict deviceId: 设备id
  421. @param response: 响应对象
  422. @return: response
  423. """
  424. device_id = request_dict.get('deviceId', None)
  425. if not device_id:
  426. return response.json(444, {'error param': 'deviceId'})
  427. try:
  428. scene_qs = SceneLog.objects.filter(device_id=device_id).values('tasks', 'status', 'created_time', 'id')
  429. res = []
  430. for item in scene_qs:
  431. res.append({
  432. 'id': item['id'],
  433. 'tasks': json.loads(item['tasks']),
  434. 'status': item['status'],
  435. 'created_time': item['created_time']
  436. })
  437. return response.json(0, res)
  438. except Exception as e:
  439. print(e)
  440. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  441. @staticmethod
  442. def reset(request_dict, response):
  443. """
  444. 查询执行日志
  445. @param request_dict: 请求参数
  446. @request_dict serialNumber: 设备序列号
  447. @param response: 响应对象
  448. @return: response
  449. """
  450. serial_number = request_dict.get('serialNumber', None)
  451. if not serial_number:
  452. return response.json(444, {'error param': 'serialNumber'})
  453. device_qs = Device_Info.objects.filter(serial_number=serial_number).values('id')
  454. if not device_qs.exists():
  455. return response.json(173)
  456. device_id = device_qs[0]['device_id']
  457. try:
  458. # 删除智能开关数据
  459. SwitchDimmingSettings.objects.filter(device_id=device_id).delete()
  460. chronopher_qs = SwitchChronopher.objects.filter(device_id=device_id)
  461. if chronopher_qs.exists():
  462. chronopher_id = chronopher_qs[0].id
  463. apscheduler_obj = ApschedulerObject()
  464. apscheduler_obj.del_job('switchchronopher_{}'.format(chronopher_id)) # 删除定时任务
  465. apscheduler_obj.del_job('switchchronopher_{}_1'.format(chronopher_id))
  466. apscheduler_obj.del_job('switchchronopher_{}_2'.format(chronopher_id))
  467. chronopher_qs.delete()
  468. SceneLog.objects.filter(device_id=device_id).delete()
  469. FamilyRoomDevice.objects.filter(device_id=device_id).delete()
  470. Device_Info.objects.filter(id=device_id).delete()
  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 del_switch(device_id, serial_number):
  476. """
  477. 删除开关
  478. @param device_id: 设备id
  479. @param serial_number: 设备序列号
  480. @return: response
  481. """
  482. try:
  483. SwitchDimmingSettings.objects.filter(device_id=device_id).delete()
  484. chronopher_qs = SwitchChronopher.objects.filter(device_id=device_id)
  485. if chronopher_qs.exists():
  486. chronopher_id = chronopher_qs[0].id
  487. apscheduler_obj = ApschedulerObject()
  488. apscheduler_obj.del_job('switchchronopher_{}'.format(chronopher_id)) # 删除定时任务
  489. apscheduler_obj.del_job('switchchronopher_{}_1'.format(chronopher_id))
  490. apscheduler_obj.del_job('switchchronopher_{}_2'.format(chronopher_id))
  491. chronopher_qs.delete()
  492. SceneLog.objects.filter(device_id=device_id).delete()
  493. msg = {
  494. "device_reset": 1 # 重置智能开关
  495. }
  496. topic_name = RESET_SWITCH_TOPIC_NAME.format(serial_number)
  497. result = CommonService.req_publish_mqtt_msg(serial_number, topic_name, msg)
  498. LOGGER.info('执行重置开关mqtt结果:{}'.format(result))
  499. except Exception as e:
  500. print(e)
  501. LOGGER.info('error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))