SmartSwitchController.py 27 KB

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