SubDeviceController.py 17 KB

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