123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332 |
- # -*- coding: utf-8 -*-
- """
- @Author : Rocky
- @Time : 2022/5/9 10:51
- @File :gatewayController.py
- """
- import logging
- import time
- from django.views.generic.base import View
- from AnsjerPush.Config.gatewaySensorConfig import SENSOR_TYPE, EVENT_TYPE
- from Model.models import SensorRecord, GatewaySubDevice, GatewayPush, Device_Info, SceneLog, SmartScene
- from Object.RedisObject import RedisObject
- from Object.ResponseObject import ResponseObject
- from Object.utils import LocalDateTimeUtil
- from Service.CommonService import CommonService
- from Service.EquipmentInfoService import EquipmentInfoService
- from Service.HuaweiPushService.HuaweiPushService import HuaweiPushObject
- from Service.PushService import PushObject
- LOGGER = logging.getLogger('info')
- class GatewayView(View):
- def get(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- operation = kwargs.get('operation')
- return self.validation(request.GET, operation)
- def post(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- operation = kwargs.get('operation')
- return self.validation(request.POST, operation)
- def validation(self, request_dict, operation):
- response = ResponseObject()
- if operation == 'gatewayPush': # 网关推送
- return self.gateway_push(request_dict, response)
- elif operation == 'sceneLogPush': # 场景日志推送
- return self.scene_log_push(request_dict, response)
- elif operation == 'socketPush': # 插座推送
- return self.socket_msg_push(request_dict, response)
- else:
- return response.json(414)
- @staticmethod
- def gateway_push(request_dict, response):
- """
- 网关推送
- @param request_dict: 请求参数
- @request_dict serial_number: 序列号
- @request_dict ieee_addr: 长地址
- @request_dict src_addr: 短地址
- @request_dict sensor_type: 传感器类型
- @request_dict event_type: 事件类型
- @request_dict alarm: 消息内容
- @request_dict defense: 防御状态,0:撤防,1:防御
- @request_dict sensor_status: 拆动状态,拆动时传参
- @param response: 响应对象
- @return: response
- """
- logger = logging.getLogger('info')
- serial_number = request_dict.get('serial_number', None)
- ieee_addr = request_dict.get('ieee_addr', None)
- src_addr = request_dict.get('src_addr', None)
- sensor_type = int(request_dict.get('sensor_type', None))
- event_type = int(request_dict.get('event_type', None))
- alarm = request_dict.get('alarm', None)
- defense = int(request_dict.get('defense', None))
- sensor_status = request_dict.get('sensor_status', None)
- logger.info('---调用网关推送接口--- request_dict:{}'.format(request_dict))
- if not all([serial_number, ieee_addr, src_addr, sensor_type, event_type, alarm]):
- return response.json(444)
- n_time = int(time.time())
- try:
- # 查询子设备表id
- gateway_sub_device_qs = GatewaySubDevice.objects.filter(device__serial_number=serial_number,
- device_type=sensor_type, ieee_addr=ieee_addr,
- src_addr=src_addr).values('id', 'nickname')
- if not gateway_sub_device_qs.exists():
- return response.json(173)
- else:
- gateway_sub_device_id = gateway_sub_device_qs[0]['id']
- nickname = gateway_sub_device_qs[0]['nickname']
- sensor_record_dict = {
- 'gateway_sub_device_id': gateway_sub_device_id,
- 'alarm': alarm,
- 'event_type': event_type,
- 'created_time': n_time,
- }
- # 处理温湿度,不推送
- if sensor_type == SENSOR_TYPE['tem_hum_sensor'] and (
- event_type == EVENT_TYPE['temperature'] or event_type == EVENT_TYPE['humidity']):
- num = request_dict.get('num', None)
- num = str(int(num) / 100)
- sensor_record_dict['alarm'] = num
- SensorRecord.objects.create(**sensor_record_dict)
- return response.json(0)
- SensorRecord.objects.create(**sensor_record_dict)
- # (门磁,烟雾,人体)传感器被拆动/拆动恢复,修改拆动状态
- if sensor_status:
- if sensor_type != SENSOR_TYPE['smart_button']: # 智能按钮不更新
- gateway_sub_device_qs.update(is_tampered=1)
- elif sensor_type == SENSOR_TYPE['door_magnet'] or sensor_type == SENSOR_TYPE['smoke_sensor'] or \
- sensor_type == SENSOR_TYPE['body_sensor']:
- gateway_sub_device_qs.update(is_tampered=0)
- # 撤防状态不推送
- if defense == 0:
- return response.json(0)
- device_info_qs = Device_Info.objects.filter(serial_number=serial_number).values('userID_id')
- if not device_info_qs.exists():
- return response.json(173)
- equipment_info_list = []
- for device_info in device_info_qs:
- user_id = device_info['userID_id']
- # 组织存储数据
- local_date_time = CommonService.get_now_time_str(n_time=n_time, tz=0, lang='cn')[:10]
- equipment_info_list.append(EquipmentInfoService.get_equipment_info_obj(
- local_date_time,
- add_time=n_time,
- event_time=n_time,
- receive_time=n_time,
- device_uid=serial_number,
- device_nick_name=nickname,
- alarm=alarm,
- event_type=event_type,
- device_user_id=user_id,
- ))
- if equipment_info_list:
- # 根据日期获得星期几
- week = LocalDateTimeUtil.date_to_week(local_date_time)
- EquipmentInfoService.equipment_info_bulk_create(week, equipment_info_list)
- # 查询推送配置数据
- gateway_push_qs = GatewayPush.objects.filter(user_id=user_id, logout=False). \
- values('user_id', 'app_bundle_id', 'app_type', 'push_type', 'token_val', 'm_code', 'lang', 'm_code',
- 'tz')
- if not gateway_push_qs.exists():
- continue
- kwargs = {
- 'n_time': n_time,
- 'event_type': event_type,
- 'nickname': nickname,
- }
- # 推送到每台登录账号的手机
- for gateway_push in gateway_push_qs:
- app_bundle_id = gateway_push['app_bundle_id']
- push_type = gateway_push['push_type']
- token_val = gateway_push['token_val']
- lang = gateway_push['lang']
- tz = gateway_push['tz'] if gateway_push['tz'] else 0
- # 获取推送所需数据
- msg_title = PushObject.get_msg_title(nickname)
- msg_text = PushObject.get_gateway_msg_text(n_time, tz, lang, alarm)
- kwargs['msg_title'] = msg_title
- kwargs['msg_text'] = msg_text
- kwargs['app_bundle_id'] = app_bundle_id
- kwargs['token_val'] = token_val
- try:
- if 'loocam' in app_bundle_id:
- # 推送消息
- if push_type == 0: # ios apns
- PushObject.ios_apns_push(**kwargs)
- elif push_type == 1: # android gcm
- PushObject.android_fcm_push(**kwargs)
- elif push_type == 2: # android 极光推送
- PushObject.android_jpush(**kwargs)
- elif push_type == 3:
- huawei_push_object = HuaweiPushObject()
- huawei_push_object.send_push_notify_message(**kwargs)
- elif push_type == 4: # android 小米推送
- channel_id = 104551
- PushObject.android_xmpush(channel_id=channel_id, **kwargs)
- elif push_type == 5: # android vivo推送
- PushObject.android_vivopush(**kwargs)
- elif push_type == 6: # android oppo推送
- channel_id = 'DEVICE_REMINDER'
- PushObject.android_oppopush(channel_id=channel_id, **kwargs)
- elif push_type == 7: # android 魅族推送
- PushObject.android_meizupush(**kwargs)
- except Exception as e:
- logger.info('网关推送消息异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
- continue
- return response.json(0)
- except Exception as e:
- logger.info('---网关推送接口异常--- {}'.format(repr(e)))
- return response.json(500, repr(e))
- @staticmethod
- def scene_log_push(request_dict, response):
- """
- 网关智能场景日志推送
- @param request_dict: 请求参数
- @request_dict sceneId: 场景id
- @request_dict status: 状态
- @param response: 响应对象
- @return: response
- """
- logger = logging.getLogger('info')
- scene_id = request_dict.get('sceneId', None)
- status = request_dict.get('status', None)
- logger.info('---场景日志推送接口--- request_dict:{}'.format(request_dict))
- if not all([scene_id, status]):
- return response.json(444)
- smart_scene_qs = SmartScene.objects.filter(id=scene_id).values('scene_name', 'conditions', 'tasks', 'device_id',
- 'sub_device_id', 'user_id')
- if not smart_scene_qs.exists():
- return response.json(173)
- scene_name = smart_scene_qs[0]['scene_name']
- tasks = smart_scene_qs[0]['tasks']
- device_id = smart_scene_qs[0]['device_id']
- sub_device_id = smart_scene_qs[0]['sub_device_id']
- n_time = int(time.time())
- user_id = smart_scene_qs[0]['user_id']
- if sub_device_id:
- gateway_sub_device_qs = GatewaySubDevice.objects.filter(id=sub_device_id).values('nickname')
- nickname = gateway_sub_device_qs[0]['nickname'] if gateway_sub_device_qs.exists() else ''
- else:
- device_qs = Device_Info.objects.filter(id=device_id).values('NickName')
- nickname = device_qs[0]['NickName'] if device_qs.exists() else ''
- log_dict = {
- 'scene_id': scene_id,
- 'scene_name': scene_name,
- 'tasks': tasks,
- 'status': status,
- 'device_id': device_id,
- 'sub_device_id': sub_device_id,
- 'created_time': n_time,
- }
- tasks = eval(tasks)
- try:
- SceneLog.objects.create(**log_dict)
- # 推送日志
- gateway_push_qs = GatewayPush.objects.filter(user_id=user_id, logout=False). \
- values('user_id', 'app_bundle_id', 'app_type', 'push_type', 'token_val', 'm_code', 'lang', 'm_code',
- 'tz')
- if not gateway_push_qs.exists():
- return response.json(174)
- for task in tasks:
- event_type = task['event_type']
- if event_type == '1001':
- kwargs = {
- 'n_time': n_time,
- 'event_type': event_type,
- 'nickname': nickname,
- }
- event_info = task['value']
- # 推送到每台登录账号的手机
- for gateway_push in gateway_push_qs:
- app_bundle_id = gateway_push['app_bundle_id']
- push_type = gateway_push['push_type']
- token_val = gateway_push['token_val']
- kwargs['msg_title'] = PushObject.get_msg_title(nickname)
- kwargs['msg_text'] = event_info
- kwargs['app_bundle_id'] = app_bundle_id
- kwargs['token_val'] = token_val
- try:
- # 推送消息
- if push_type == 0: # ios apns
- PushObject.ios_apns_push(**kwargs)
- elif push_type == 1: # android gcm
- PushObject.android_fcm_push(**kwargs)
- elif push_type == 2: # android 极光推送
- PushObject.android_jpush(**kwargs)
- elif push_type == 3:
- huawei_push_object = HuaweiPushObject()
- huawei_push_object.send_push_notify_message(**kwargs)
- elif push_type == 4: # android 小米推送
- channel_id = 104551
- PushObject.android_xmpush(channel_id=channel_id, **kwargs)
- elif push_type == 5: # android vivo推送
- PushObject.android_vivopush(**kwargs)
- elif push_type == 6: # android oppo推送
- channel_id = 'DEVICE_REMINDER'
- PushObject.android_oppopush(channel_id=channel_id, **kwargs)
- elif push_type == 7: # android 魅族推送
- PushObject.android_meizupush(**kwargs)
- except Exception as e:
- logger.info('场景日志推送消息异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
- continue
- return response.json(0)
- except Exception as e:
- logger.info('---场景日志推送接口异常--- {}'.format(repr(e)))
- return response.json(500, repr(e))
- @classmethod
- def socket_msg_push(cls, request_dict, response):
- """
- 智能插座开关状态推送
- """
- try:
- serial_number = request_dict.get('serialNumber', None)
- device_time = request_dict.get('deviceTime', None)
- status = request_dict.get('status', None)
- if not all([serial_number, status, device_time]):
- return response.json(444)
- status = int(status)
- now_time = int(device_time) if device_time else int(time.time())
- # 获取主用户设备id
- log_dict = {
- 'status': status,
- 'device_id': serial_number,
- 'created_time': now_time,
- }
- SceneLog.objects.create(**log_dict)
- LOGGER.info('成功接收并保存,插座序列号{},状态:{}'.format(serial_number, status))
- return response.json(0)
- except Exception as e:
- print(repr(e))
- LOGGER.info('---插座开关日志推送接口异常--- {}'.format(repr(e)))
- return response.json(500, repr(e))
|