SubDeviceController.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. # -*- coding: utf-8 -*-
  2. """
  3. @Author : Joker
  4. @Time : 2022/5/25 15:17
  5. @File :SubDeviceController.py
  6. """
  7. import time
  8. from collections import OrderedDict
  9. from django.db import transaction
  10. from django.views import View
  11. from Model.models import Device_Info, GatewaySubDevice, FamilyRoomDevice, SensorRecord
  12. from Object.ResponseObject import ResponseObject
  13. from Object.TokenObject import TokenObject
  14. class GatewaySubDeviceView(View):
  15. def get(self, request, *args, **kwargs):
  16. request.encoding = 'utf-8'
  17. operation = kwargs.get('operation')
  18. return self.validation(request.GET, request, operation)
  19. def post(self, request, *args, **kwargs):
  20. request.encoding = 'utf-8'
  21. operation = kwargs.get('operation')
  22. return self.validation(request.POST, request, operation)
  23. def validation(self, request_dict, request, operation):
  24. token_obj = TokenObject(request.META.get('HTTP_AUTHORIZATION'))
  25. lang = request_dict.get('lang', None)
  26. response = ResponseObject(lang if lang else token_obj.lang)
  27. if token_obj.code != 0:
  28. return response.json(token_obj.code)
  29. user_id = token_obj.userID
  30. if operation == 'add': # 添加子设备
  31. return self.add(request_dict, user_id, response)
  32. elif operation == 'query': # 查询子设备
  33. return self.query(request_dict, user_id, response)
  34. elif operation == 'update': # 更新子设备信息
  35. return self.sensor_update(request_dict, response)
  36. elif operation == 'delete': # 删除子设备
  37. return self.delete(request_dict, user_id, response)
  38. elif operation == 'records': # 查询子设备记录数据
  39. return self.records(request_dict, response)
  40. else:
  41. return response.json(414)
  42. @staticmethod
  43. def add(request_dict, user_id, response):
  44. """
  45. 添加子设备
  46. @param request_dict: 请求参数
  47. @request_dict serial_number: 序列号
  48. @request_dict device_type: 设备类型
  49. @request_dict nickname: 设备名
  50. @request_dict src_addr: 短地址
  51. @request_dict family_id: 家庭id
  52. @request_dict room_id: 房间id
  53. @param user_id: 用户id
  54. @param response: 响应对象
  55. @return: response 响应对象
  56. """
  57. serial_number = request_dict.get('serialNumber', None)
  58. device_type = int(request_dict.get('deviceType', None))
  59. nickname = request_dict.get('nickName', None)
  60. ieee_addr = request_dict.get('ieeeAddr', None)
  61. src_addr = request_dict.get('srcAddr', None)
  62. family_id = request_dict.get('familyId', None)
  63. room_id = request_dict.get('roomId', 0)
  64. if not all([serial_number, device_type, nickname, src_addr, family_id]):
  65. return response.json(444)
  66. now_time = int(time.time())
  67. try:
  68. # 查询网关设备数据
  69. device_info_qs = Device_Info.objects.filter(userID_id=user_id, serial_number=serial_number).values('id')
  70. if not device_info_qs.exists():
  71. return response.json(14)
  72. device_id = device_info_qs[0]['id']
  73. # 查询是否已添加过该子设备
  74. sub_device_qs = GatewaySubDevice.objects.filter(device_id=device_id, ieee_addr=ieee_addr)
  75. if sub_device_qs.exists():
  76. return response.json(174)
  77. with transaction.atomic():
  78. sub_device = GatewaySubDevice.objects.create(device_id=device_id, device_type=device_type,
  79. nickname=nickname, ieee_addr=ieee_addr, src_addr=src_addr,
  80. status=1, created_time=now_time, updated_time=now_time)
  81. FamilyRoomDevice.objects.create(family_id=family_id, room_id=room_id, device_id=device_id,
  82. sub_device=sub_device.id, created_time=now_time, updated_time=now_time)
  83. return response.json(0)
  84. except Exception as e:
  85. return response.json(500, repr(e))
  86. @staticmethod
  87. def query(request_dict, user_id, response):
  88. """
  89. 查询子设备
  90. @param request_dict: 请求参数
  91. @request_dict serial_number: 序列号
  92. @param user_id: 用户id
  93. @param response: 响应对象
  94. @return: response
  95. """
  96. serial_number = request_dict.get('serialNumber', None)
  97. if not all([serial_number]):
  98. return response.json(444)
  99. try:
  100. device_info_qs = Device_Info.objects.filter(userID_id=user_id, serial_number=serial_number).values('id')
  101. if not device_info_qs.exists():
  102. return response.json(14)
  103. device_id = device_info_qs[0]['id']
  104. count = GatewaySubDevice.objects.filter(device_id=device_id).count()
  105. gateway_sub_device_qs = GatewaySubDevice.objects.filter(device_id=device_id).values('device_type',
  106. 'nickname', 'ieee_addr',
  107. 'src_addr', 'status')
  108. gateway_sub_device_list = [gateway_sub_device for gateway_sub_device in gateway_sub_device_qs]
  109. res = {
  110. 'count': count,
  111. 'gateway_sub_device_list': gateway_sub_device_list
  112. }
  113. return response.json(0, res)
  114. except Exception as e:
  115. return response.json(500, repr(e))
  116. @classmethod
  117. def sensor_update(cls, request_dict, response):
  118. """
  119. 传感器修改
  120. @param request_dict: 请求参数
  121. @request_dict gateway_sub_id: 子设备id
  122. @request_dict nickName: 设备名
  123. @request_dict room_id: 房间id
  124. @param response: 响应结果
  125. @return: list
  126. """
  127. gateway_sub_id = int(request_dict.get('gatewaySubId', None))
  128. nickName = request_dict.get('nickName', None)
  129. room_id = request_dict.get('roomId', None)
  130. if not all([gateway_sub_id]):
  131. return response.json(444)
  132. try:
  133. gateway_sub_qs = GatewaySubDevice.objects.filter(id=gateway_sub_id)
  134. if not gateway_sub_qs.exists():
  135. return response.json(173)
  136. if nickName:
  137. gateway_sub_qs.update(nickname=nickName)
  138. if room_id:
  139. FamilyRoomDevice.objects.filter(sub_device=gateway_sub_id).update(room_id=room_id)
  140. return response.json(0)
  141. except Exception as e:
  142. print(e.args)
  143. return response.json(500, repr(e))
  144. @staticmethod
  145. def delete(request_dict, user_id, response):
  146. """
  147. 更新子设备信息
  148. @param request_dict: 请求参数
  149. @request_dict sub_device_id: 子设备id
  150. @param user_id: 用户id
  151. @param response: 响应对象
  152. @return: response
  153. """
  154. sub_device_id = request_dict.get('subDeviceId', None)
  155. if not all([sub_device_id]):
  156. return response.json(444)
  157. try:
  158. GatewaySubDevice.objects.filter(id=sub_device_id).delete()
  159. return response.json(0)
  160. except Exception as e:
  161. return response.json(500, repr(e))
  162. @staticmethod
  163. def records(request_dict, response):
  164. """
  165. 查询子设备记录数据
  166. @param request_dict: 请求参数
  167. @request_dict gatewaySubId: 子设备id
  168. @request_dict cycle: 时间周期
  169. @request_dict page: 页数
  170. @request_dict size: 条数
  171. @param response: 响应对象
  172. @return: response
  173. """
  174. sub_device_id = request_dict.get('gatewaySubId', None)
  175. cycle = request_dict.get('cycle', None)
  176. if not all([sub_device_id]):
  177. return response.json(444, {'error param': 'gatewaySubId'})
  178. now_time = int(time.time())
  179. try:
  180. if not cycle:
  181. page = request_dict.get('page', None)
  182. size = request_dict.get('size', None)
  183. start_time = request_dict.get('startTime', None)
  184. end_time = request_dict.get('endTime', None)
  185. if not all([page, size]):
  186. return response.json(444, {'error param': 'page or size'})
  187. page, size = int(page), int(size)
  188. if start_time and end_time:
  189. sensor_record_qs = SensorRecord.objects.filter(gateway_sub_device_id=sub_device_id,
  190. created_time__range=(start_time, end_time)). \
  191. values('alarm', 'created_time').order_by('-created_time')[
  192. (page - 1) * size:page * size]
  193. else:
  194. sensor_record_qs = SensorRecord.objects.filter(gateway_sub_device_id=sub_device_id). \
  195. values('alarm', 'created_time').order_by('-created_time')[
  196. (page - 1) * size:page * size]
  197. if not sensor_record_qs.exists():
  198. return response.json(0)
  199. return response.json(0, list(sensor_record_qs))
  200. else:
  201. event_type = int(request_dict.get('eventType', None))
  202. if not event_type:
  203. return response.json(444, {'error param': 'eventType'})
  204. record_dict = OrderedDict()
  205. record_list = []
  206. if cycle == 'Hours':
  207. start_time = now_time - 24 * 60 * 60
  208. sensor_record_qs = SensorRecord.objects.filter(gateway_sub_device_id=sub_device_id,
  209. event_type=event_type,
  210. created_time__range=(start_time, now_time)). \
  211. values('alarm', 'created_time').order_by('created_time')
  212. if not sensor_record_qs.exists():
  213. return response.json(0, {'records': [], 'time': now_time})
  214. for sensor_record in sensor_record_qs:
  215. created_time = time.strftime('%m/%d %H:%M %w', time.localtime(sensor_record['created_time']))
  216. hour = int(created_time[-7:-5])
  217. minute = int(created_time[-4:-2])
  218. if hour != 23 and minute > 30: # 不为23时且分钟大于30,hour+1
  219. hour += 1
  220. alarm = float(sensor_record['alarm'])
  221. # 组织数据,record_dict:{"0": [1.0, 2.0, 3.0], "1": [1.0, 2.0, 3.0]...}
  222. if str(hour) in record_dict:
  223. record_dict[str(hour)].append(alarm)
  224. else:
  225. record_dict[str(hour)] = [alarm]
  226. elif cycle == 'Week':
  227. start_time = now_time - 24 * 60 * 60 * 7
  228. sensor_record_qs = SensorRecord.objects.filter(gateway_sub_device_id=sub_device_id,
  229. event_type=event_type,
  230. created_time__range=(start_time, now_time)). \
  231. values('alarm', 'created_time').order_by('created_time')
  232. if not sensor_record_qs.exists():
  233. return response.json(0, {'records': [], 'time': now_time})
  234. for sensor_record in sensor_record_qs:
  235. created_time = time.strftime('%m/%d %H:%M %w', time.localtime(sensor_record['created_time']))
  236. week = int(created_time[-1:])
  237. alarm = float(sensor_record['alarm'])
  238. # 组织数据,record_dict:{"0": [1.0, 2.0, 3.0], "1": [1.0, 2.0, 3.0]...}
  239. if str(week) in record_dict:
  240. record_dict[str(week)].append(alarm)
  241. else:
  242. record_dict[str(week)] = [alarm]
  243. elif cycle == 'Month':
  244. start_time = now_time - 24 * 60 * 60 * 30
  245. sensor_record_qs = SensorRecord.objects.filter(gateway_sub_device_id=sub_device_id,
  246. event_type=event_type,
  247. created_time__range=(start_time, now_time)). \
  248. values('alarm', 'created_time').order_by('created_time')
  249. if not sensor_record_qs.exists():
  250. return response.json(0, {'records': [], 'time': now_time})
  251. for sensor_record in sensor_record_qs:
  252. created_time = time.strftime('%m/%d %H:%M %w', time.localtime(sensor_record['created_time']))
  253. month = int(created_time[:2])
  254. day = int(created_time[3:5])
  255. date = str(month) + '/' + str(day)
  256. alarm = float(sensor_record['alarm'])
  257. # 组织数据,record_dict:{"0": [1.0, 2.0, 3.0], "1": [1.0, 2.0, 3.0]...}
  258. if date in record_dict:
  259. record_dict[date].append(alarm)
  260. else:
  261. record_dict[date] = [alarm]
  262. # 组织响应数据列表,value为每 小时/天 的平均值
  263. for k, v in record_dict.items():
  264. record_list.append({'key': k, 'value': round(sum(v) / len(v), 1)})
  265. res = {
  266. 'records': record_list,
  267. 'time': now_time
  268. }
  269. return response.json(0, res)
  270. except Exception as e:
  271. return response.json(500, repr(e))