Beispiel #1
0
    def handleDeviceStatus(self, message=MessageDeviceStatus()):
        """ 注意: 包括 家庭模式 """
        import base64
        profile = message.params.get('profile', '')
        if profile:
            profile = base64.decodestring(profile)
            self.device.profile = profile
            self.device.save()
            return

        self.device.assign(message.values())
        self.device.alive_time = timestamp_current()
        self.device.save()

        # 写入 redis
        name = constants.DeviceStatusHash.format(self.device_id)
        data = hash_object(self.device)
        self.redis.hmset(name, data)

        # 写入日志
        log = model.LogDeviceStatus()
        log.device_id = self.device_id
        log.sys_time = timestamp_current()
        log.assign(message.params)
        # log.host_ver = message.host_ver
        # log.mcu_ver = message.mcu_ver
        # log.status_time = message.status_time
        # log.boot_time = message.boot_time
        log.save()
Beispiel #2
0
def create_cargo_address():
    """查询本人创建的共享设备信息
        支持 共享设备编号查询 或 设备编号查询
        如果共享记录未创建则创建,并返回
    """
    user = g.user
    name = request.values.get('name')
    phone = request.values.get('phone')
    address_ = request.values.get('address', '')
    is_default = request.values.get('is_default', 0, type=int)
    if not name or not phone or not address_:
        return ErrorReturn(ErrorDefs.ParameterInvalid,
                           u'必须提供联系人、手机号、收件地址').response
    if is_default:
        # 将其他记录设置为非默认
        model.CargoAddress.collection().update_many(
            {
                'user_id': user.id,
                'is_default': 1
            }, {'$set': {
                'is_default': 0
            }})
    address = model.CargoAddress()
    address.user_id = user.id
    address.name = name
    address.phone = phone
    address.address = address_
    address.is_default = is_default
    address.order = timestamp_current()
    address.update_time = timestamp_current()
    address.save()

    return CR(result=address.id).response
Beispiel #3
0
 def inspectThread(self):
     self.running = True
     while self.running:
         gevent.sleep(1)
         if timestamp_current() - self.live_time > 60:
             self.logger.warn('no payload on line long time.(>60s)')
             self.close()
             break
         if self.join_time and timestamp_current() - self.status_time > 10:
             self.logger.warn('line_status recv timeout.')
             self.close()
             break
Beispiel #4
0
def get_ticket():
    """上传微信 code , 与微信服务器交互,获得open_id,并返回token到前端"""
    main = instance.serviceManager.get('main')
    code = request.values.get('code')
    encryptedData = request.values.get('encryptedData')
    iv = request.values.get('encryptedData')

    if not code:
        return ErrorReturn(ErrorDefs.UserNotExist).response

    appid = main.getConfig().get('wx_settings').get('appid')
    secret = main.getConfig().get('wx_settings').get('secret')

    params = dict(appid=appid,
                  secret=secret,
                  js_code=code,
                  grant_type='authorization_code')
    url = main.getConfig().get('wx_settings').get('code2session_url')
    resp = requests.get(url, params)
    data = resp.json()
    open_id = ''
    session_key = ''
    union_id = ''

    # if data.get('errcode') == 0:
    open_id = data.get('openid')
    session_key = data.get('session_key')
    # union_id  = data.get('unionid')

    if not open_id:
        return ErrorReturn(ErrorDefs.AccessDenied, u'微信服务器返回错误:{}'.format(
            data.get('errcode'))).response

    user = model.User.get_or_new(platform='wx', account=open_id)
    user.platform = 'wx'
    user.last_login = timestamp_current()
    user.save()

    auth = AuthToken()
    auth.login_time = timestamp_current()
    auth.user_id = user.account
    auth.user_name = user.name
    auth.platform = 'wx'
    auth.open_id = open_id
    user.token = auth.encode()

    user.save()

    result = dict(open_id=open_id, union_id=union_id, token=user.token)
    return CR(result=result).response
Beispiel #5
0
def cmd_position_now():
    """立即定位, 这里要进行请求阀控
     2018.10.21  禁止发送 lbs 定位请求,在实时监控过程中,gps信号okey的
     情况下,请求lbs,导致轨迹漂移
    """
    user = g.user
    device_id = request.values.get('device_id')
    main = instance.serviceManager.get('main')
    device = model.Device.get(device_id=device_id)
    cc = main.getCommandController(device.device_type)

    #设备上一次发送立即定位命令的时间
    # redis记录最近一次发送时间,直到key失效之前不能重复发送
    # 保证大量的客户端不会对设备发送大量的立即定位命令
    name = constants.DevicePositionRequestTimeKey.format(device_id)
    redis = instance.datasourceManager.get('redis').conn
    value = redis.get(name)
    if not value:
        cmd = cc.positionNowGps()
        cmd_send(device_id, cmd, online=True)
        # cmd = cc.positionNowLbs()
        # cmd_send(device_id, cmd, online=True)
        expire = main.getConfig().get('max_position_request_interval', 10)
        redis.set(name, timestamp_current(), expire)

    # cmd = cc.positionNowLbs()
    # main.sendCommand(device_id, cmd)
    # cmd = cc.positionNowGps()
    # main.sendCommand(device_id, cmd)
    return CR().response
def rebuild_device_followers():

    model.ShareDeviceFollower.collection().delete_many({})

    shares = model.SharedDeviceLink.find()
    # print shares
    for share in shares:
        devices = model.DeviceUserRelation.find(is_share_device=True,share_device_link = share.id)
        for device in devices:
            user = model.User.get(_id=  ObjectId(device.user_id) )
            print '=*'*20
            print share.name
        # print share.user_id
        # print user
        # wxuser = model.WxUser(open_id = user.account)
            follower = model.ShareDeviceFollower.get(share_id=share.id,user_id=user.id)
            if not follower:
                follower = model.ShareDeviceFollower()
                follower.user_id = user.id
                follower.open_id = user.account
                follower.share_id = share.id
                follower.device_id = share.device_id
                follower.create_time = timestamp_current()
                wxuser = model.WxUser.get(open_id=user.account)
                if wxuser:
                    follower.avatar_url = wxuser.avatarUrl
                    follower.nick_name = wxuser.nickName
                print follower.nick_name
                # print follower.dict()
                follower.save()
Beispiel #7
0
    def distribute_message(self,message):
        data = message.dict()

        data['name'] = message.__class__.__name__
        data['type_id'] = message.Type.value
        data['type_comment'] = message.Type.comment
        data['timestamp'] = timestamp_current()
        data['datetime'] = current_datetime_string()
        data['device_id'] = self.device_id
        data['device_type'] = self.device_type

        if data.has_key('extra'): del data['extra']
        if data.has_key('Type'): del data['Type']

        print data
        #将设备消息发布出去
        self.service.dataFanout('switch0',json.dumps(data))

        # 发布到隶属于设备编号的通道上去
        self.device_pub_channel.publish_or_produce(json.dumps(data))

        # # 写入日志数据库
        dbname = 'blue_earth_device_log'
        coll = self.mongo[dbname][self.device_id]
        coll.insert_one(data)
Beispiel #8
0
def init_outerbox():
    """室外机登录"""
    ip = request.remote_addr.split(':')[-1]
    box = model.OuterBox.get(ip=ip)  # 根据ip检查设备是否登记
    if not box:
        return ErrorReturn(ErrorDefs.ObjectNotExist, u'室外主机未登记')

    box.login_time = timestamp_current()
    box.save()

    data = {}
    garden = model.HomeGarden.get(id='8888')
    data['propcenter_ip'] = garden.property_call_server
    data['stream_server_url'] = garden.stream_server_url

    innerbox_list = []
    rs = model.InnerBox.find(garden_id=garden.id, building_id=box.building_id)
    for _ in rs:
        innerbox_list.append(dict(room_id=_.room_id, ip=_.ip))

    sentry_list = []
    rs = model.SentryApp.find(garden_id=garden.id)
    for _ in rs:
        sentry_list.append(dict(name=_.name, ip=_.ip))

    data['innerbox_list'] = innerbox_list
    data['sentry_list'] = sentry_list

    result = data
    return CR(result=result)
Beispiel #9
0
 def handleDeviceLogInfo(self, message=MessageDeviceLogInfo()):
     log = model.LogDeviceLogInfo()
     log.device_id = self.device_id
     log.sys_time = timestamp_current()
     log.device_time = message.time
     log.content = message.content
     log.save()
Beispiel #10
0
    def sendCommand(self,command):

        content = command
        content = self.command_controller.execute(content)
        if not content:
            return True

        self.logger.debug('SendCommand: {} {} {}'.format(content,self.device_id,self.device_type))
        command = MessageOnlineCommand()
        command.content = content
        command.sequence = self.seq_gen.next_id()
        packet = command.packet()
        packet.sequence = self.next_packet_sequence()
        try:
            self.conn.sendData(packet.to_bytes())
        except:
            self.logger.error('socket sendData error. {} {} {}'.format(content,self.device_id,self.device_type))
            self.close()
            return False
        # save send record
        send = model.CommandSend()
        send.device_id = self.device_id
        send.send_time = timestamp_current()
        send.sequence = packet.sequence
        send.command = command.content
        send.save()
        return True
Beispiel #11
0
    def messageProcessTask(self):
        """处理设备上报消息的工作队列"""
        while self.running:
            # 长久没有心跳包
            if timestamp_current() - self.last_heartbeat > 60 * 5:
                self.logger.warn('Heartbeat Lost. Close socket. {} {} '.format(
                    self.device_id, self.device_type))
                self.close()
                break
            try:
                message, date = self.queue.get(block=True, timeout=1)
                try:
                    self.logger.debug(
                        'message pop from queue: {} {}  {} {}'.format(
                            date, message.__class__.__name__, self.device_id,
                            self.device_type))

                    self.handleMessage(message)
                except:
                    self.logger.warn(traceback.print_exc())
                    self.close()
                    break
            except:
                pass

        self.logger.warn('messageTask() exiting.. {} {} '.format(
            self.device_id, self.device_type))
Beispiel #12
0
 def setTrading(self, code, allow=True):
     """指定证券代码进入可交易状态"""
     cfg = self.trading_codes.get(code, {'allow': False, 'start': 0})
     cfg['allow'] = allow
     if not allow:
         cfg['start'] = 0
     else:
         cfg['start'] = timestamp_current()
Beispiel #13
0
 def onConnected(self, conn, address):
     """连接上来 , 等待app发送join请求,超时 10s 断开连接 """
     self.logger.debug('app connected .  {}'.format(str(address)))
     self.conn = conn
     self.peer_address = address  # 连接上来的对方地址
     self.last_heartbeat = timestamp_current()
     # gevent.spawn_later(self.checkLogin,10)
     gevent.spawn(self.checkLogin)
Beispiel #14
0
def device_login():
    """设备主机登陆,服务器校验合法性,并返回接入服务器地址"""
    main = instance.serviceManager.get('main')
    id_ = request.values.get('id')
    type_ = request.values.get('type')
    ver = request.values.get('ver')
    time = request.values.get('time')
    sign = request.values.get('sign','').upper()


    if not id_ or not type_ or not ver or not time or not sign:
    # if not id_ or not type_ :
        return ErrorReturn(ErrorDefs.ParameterInvalid).response

    secret_key = main.getConfig().get('device_secret_key')

    value,_ = make_signature(secret_key,dict(id=id_,type=type_,ver=ver,time=time))
    if value != sign:
        instance.getLogger().error(u"数据签名计算错误")
        return ErrorReturn(ErrorDefs.ParameterInvalid).response

    device = model.SmartDevice.get(id = id_)
    if not device:
        return ErrorReturn(ErrorDefs.ObjectNotExist,u'设备不存在').response

    # 加入 认证处理时间
    data = dict(id=id_,type=type_,ver=ver,time=time,auth_time=timestamp_current())

    token = device_token_create(data,device.secret_key)

    main = instance.serviceManager.get('main')
    boxserver = main.getConfig().get('boxserver')
    host,port = boxserver.split(':')
    result = dict(token=token, server_ip=host, server_port=int(port),
                  server_time=timestamp_current()
                  )

    # server = model.DeviceServer.get(id=device.server_id)
    # if not server:
    #     return ErrorReturn(ErrorDefs.DeviceServerNotFound).response
    #
    # result = dict( token = token, server_ip = server.ip, server_port = server.port ,
    #     server_time = timestamp_current()
    # )

    return CR(result= result).response
Beispiel #15
0
def add_device_into_group():
    """添加设备到组
    """
    user = g.user
    group_id = request.values.get('group_id')
    device_id = request.values.get('device_id')
    rel = model.DeviceGroupRelation.get(user_id = user.id,group_id=group_id,device_id=device_id)
    if rel:
        return CR().response
    rel = model.DeviceGroupRelation()
    rel.group_id = group_id
    rel.device_id = device_id
    rel.user_id = user.id
    rel.update_time = timestamp_current()
    rel.order = timestamp_current()
    rel.save()
    return CR(result=rel.id).response
def init_product_list():
    content = YamlConfigParser('./product-list.yaml').props.get('product_list')

    for profile in content:
        product = model.Product.get_or_new(sku=profile['sku'])
        # product = model.Product()
        object_assign(product, profile)
        product.update_time = timestamp_current()
        product.save()
Beispiel #17
0
def create_share_device_code():
    """生成分享码
        缓存中记录分享码生成时间
    """
    from mantis.BlueEarth import constants
    redis = instance.datasourceManager.get('redis').conn
    code = '1212'
    name = constants.DeviceShareCodeCreateTimeKey.format(code)
    redis.set(name, timestamp_current(), 3600)
    return CR(result=code).response
Beispiel #18
0
def create_favorite():
    """
     收藏产品
    """
    user = g.user
    sku = request.values.get('sku')
    comment = request.values.get('comment', '')
    product = model.Product.get(sku=sku)
    if not product:
        return ErrorReturn(ErrorDefs.ObjectNotExist, u'产品不存在').response
    favorite = model.Favorite()
    favorite.user_id = user.id
    favorite.sku = sku
    favorite.number = 1
    favorite.create_time = timestamp_current()
    favorite.order = timestamp_current()
    favorite.comment = comment
    favorite.save()
    return CR(result=favorite.id).response
Beispiel #19
0
    def onActive(self):
        """设备在线登录, 订阅本设备下行的消息"""
        self.logger.debug('device onActive. {} {}'.format(
            self.device_type, self.device_id))
        self.active = True
        gevent.spawn(self.threadHeartbeat)  # 定时心跳发送

        access_url = self.service.getConfig().get(
            'access_api_url')  #暴露给外部调用的web接口,接收命令控制
        self.redis.set(constants.DeviceAccessHttpAPI.format(self.device_id),
                       access_url)

        # 记录设备由哪个sever接入的
        # service_id = self.service.getConfig().get('id')
        # self.redis.hset(constants.DeviceServerRel,self.device_id,service_id)

        device = model.SmartDevice.get(id=self.device_id)
        if device:
            self.device = device
        else:
            self.logger.error('device not register', self.device_id)
            self.close()
            return

        CHECK_ACTIVE = False
        if CHECK_ACTIVE:
            if not device.active_time:  # 未激活
                self.logger.error('device not actived.', self.device_id)
                self.close()
                return

        device.alive_time = timestamp_current()
        device.save()

        self.service.deviceOnline(self)

        self.subscribeTraverseDownMessage()
        # 创建到华为iot的通道
        # self.iot_controller = iot.IotController(self)
        # self.iot_controller.onActive()

        # 设备上线,即刻发送设备状态查询
        self.traverseDown(MessageDeviceStatusQuery())

        # 要求设备返回所有状态 20190630
        msg_sensor_query = MessageSensorStatusQuery()
        msg_sensor_query.sensor_type = 0
        msg_sensor_query.sensor_id = 0
        self.traverseDown(msg_sensor_query)

        # 发送设备profile上报请求
        msg_upload_profile = MessageDeviceCommand()
        msg_upload_profile.command = 'upload_profile'
        self.traverseDown(msg_upload_profile)
Beispiel #20
0
    def traverseDown(self, message):
        """转发设备下行消息"""
        self.conn.sendData(message.marshall())

        if isinstance(message, MessageDeviceValueSet):
            log = model.LogDeviceValueSet()
            log.device_id = self.device_id
            log.sys_time = timestamp_current()
            log.param_name = message.param_name
            log.param_value = message.param_value
            log.save()

        if isinstance(message, MessageSensorValueSet):
            log = model.LogSensorValueSet()
            log.device_id = self.device_id
            log.sensor_id = message.sensor_id
            log.sensor_type = message.sensor_type
            log.sys_time = timestamp_current()
            log.param_name = message.param_name
            log.param_value = message.param_value
            log.save()
Beispiel #21
0
def create_group():
    """创建设备组
    """
    user = g.user
    name = request.values.get('name')
    comment = request.values.get('comment','')

    if not name:
        return ErrorReturn(ErrorDefs.ParameterInvalid).response
    if model.Group.get(name=name):
        return ErrorReturn(ErrorDefs.ObjectHasExist,u'相同组名已存在').response

    group = model.Group()
    group.name = name
    group.comment = comment
    group.order = timestamp_current()
    group.user_id = user.id
    group.create_time = timestamp_current()
    group.update_time = timestamp_current()
    group.save()
    return CR(result=group.id).response
Beispiel #22
0
    def make_position(self):
        pos = model.Position()
        name = DevicePositionLastest.format(device_id=self.device_id)
        data = self.redis.hgetall(name)
        # if data:
        #     object_assign(pos,data)
        pos.device_id = self.device_id
        pos.device_type = self.device_type
        pos.report_time = timestamp_current()

        # 取出当前的信号值、电压值
        if data:
            pos.gsm = data.get('gsm', 0)
            pos.voltage = data.get('voltage', 0)
        return pos
Beispiel #23
0
def update_group_info():
    """更新设备组信息
     支持记录 置顶 settop = 1
    """
    user = g.user
    group_id = request.values.get('group_id')
    name = request.values.get("name")
    comment = request.values.get('comment')
    settop = request.values.get('set_top',0,type=int)
    group = model.Group.get(user_id=user.id,_id=ObjectId(group_id))
    if not group:
        return ErrorReturn(ErrorDefs.ObjectNotExist).response
    if name:
        group.name = name
    if comment:
        group.comment = comment
    if settop:
        group.order = -timestamp_current()

    if name or comment or settop:
        group.update_time = timestamp_current()
        group.save()

    return CR(result=group.id).response
Beispiel #24
0
    def checkTask(self, dest):
        from model import InnberBoxCheck, InnberBoxCheckSnapShot
        data = check_one_host(dest)
        if not data:
            return
        data['ip'], data['port'] = dest
        data['check_time_s'] = current_datetime_string()
        data['check_time'] = timestamp_current()

        check = InnberBoxCheck()
        check.assign(data)
        check.save()

        obj = InnberBoxCheckSnapShot.get_or_new(ip=dest[0])
        obj.assign(data)
        obj.save()
Beispiel #25
0
def update_cargo_address():
    """
    """
    user = g.user
    id = request.values.get('id')
    is_default = request.values.get('is_default', 0, type=int)
    order = request.values.get('order', 0, type=int)
    props = request.values.to_dict()
    address = model.CargoAddress.get(_id=ObjectId(id))
    if not address:
        return ErrorReturn(ErrorDefs.ObjectNotExist, u'请求对象不存在').response
    object_assign(address, props)
    address.is_default = is_default
    address.user_id = user.id
    address.update_time = timestamp_current()
    address.save()
    return CR(result=address.id).response
Beispiel #26
0
def get_device_share_info():
    """查询本人创建的共享设备信息
        支持 共享设备编号查询 或 设备编号查询
        如果共享记录未创建则创建,并返回
    """
    user = g.user
    share_id = request.values.get('share_id')
    # device_id = request.values.get('device_id')

    link = None
    # if share_id:
    #     link = model.SharedDeviceLink.get(user_id=user.id,_id=ObjectId(share_id))
    # device = model.DeviceUserRelation.get(user_id=user.id, device_id=device_id)
    # if not device:
    #     return ErrorReturn(ErrorDefs.ObjectNotExist,u'设备对象不存在').response

    # link = model.SharedDeviceLink.get(user_id=user.id,device_id=device_id)
    link = model.SharedDeviceLink.get(_id=ObjectId(share_id))

    result = link.dict()
    result['share_id'] = link.id
    result['create_time_str'] = timestamp_to_str(result['create_time'])

    expire_time = parse(link.expire_time) + relativedelta(days=+1)
    expire_time = datetime_to_timestamp(expire_time)
    # 共享设备是否过期
    if expire_time and expire_time < timestamp_current():
        result['is_expired'] = True

    # 访问上限
    if link.user_limit:
        num = model.DeviceUserRelation.collection().find({
            'share_device_link':
            link.id
        }).count()
        if num >= link.user_limit:
            result['is_limited'] = True

    if link.password:
        result['is_password_null'] = False
    else:
        result['is_password_null'] = True

    return CR(result=result).response
Beispiel #27
0
    def handleSensorStatus(self, message=MessageSensorStatus()):
        # 写入 redis 记录设备当前最新的状态值
        name = constants.SensorStatusHash.format(
            device_id=self.device_id,
            sensor_type=message.sensor_type,
            sensor_id=message.sensor_id)
        data = message.params
        self.redis.hmset(name, data)

        # 发布到华为iot
        # self.iot_controller.onMessageSensorStatus( message )

        sensor = model.Sensor.get(device_id=message.device_id,
                                  id=message.sensor_id,
                                  type=message.sensor_type)
        if not sensor:
            sensor = model.Sensor()
            sensor.id = message.sensor_id
            sensor.type = message.sensor_type
            sensor.device_id = message.device_id
        params = {}
        if sensor.params:  # 合并新老的状态参数值
            try:
                params = json.loads(sensor.params)
                params.update(params)
            except:
                pass

        params.update(message.params)
        jsondata = json.dumps(params)
        sensor.params = jsondata
        sensor.save()

        # 写入日志
        log = model.LogSensorStatus()
        log.device_id = self.device_id
        log.sys_time = timestamp_current()
        log.sensor_id = message.sensor_id
        log.sensor_type = message.sensor_type
        log.datetime = datetime.datetime.now()
        log.assign(message.params)
        # log.params = json.dumps( message.params )
        log.save()
Beispiel #28
0
    def messageTask(self):
        import traceback

        while self.running:
            # 长久没有心跳包
            if timestamp_current() - self.last_heartbeat > MaxLiveTimeDeviceLandingServerKey:
                self.logger.warn('device heartbeat timer reached limit. close socket. {} {} '.format(self.device_id, self.device_type))
                self.close()
                break
            try:
                message,date = self.queue.get(block=True, timeout=1)
                try:
                    self.logger.debug('message pop from queue: {} {}  {} {}'.format(date,message.__class__.__name__,self.device_id,self.device_type))
                    self.handle(message)
                except:
                    self.logger.warn(traceback.print_exc())
            except:pass

        self.logger.warn('messageTask() exiting.. {} {} '.format(self.device_id, self.device_type))
Beispiel #29
0
    def checkLogin(self, message):
        from mantis.fanbei.smarthome.token import device_token_check

        device = model.SmartDevice.get(id=message.device_id)
        if not device:
            return False
        secret = device.secret_key
        data = device_token_check(message.token, secret)
        if not data:
            return False
        auth_time = data.get('auth_time', 0)
        self.device_id = data.get('id')
        self.device_type = data.get('type')
        TOKEN_VALID_TIME = self.service.getConfig().get(
            'token_valid_time', 300)
        # 校验token是否已过期
        if timestamp_current() - auth_time > TOKEN_VALID_TIME:
            instance.getLogger().error(u'过期无效token: ', message.token)
            return False

        return True
Beispiel #30
0
    def handle_lbs_alarm(self,message):
        """处理lbs报警"""
        alarm = model.AlarmData()
        alarm.alarm_source_type = AlarmSourceType.LBS_ALARM
        alarm.alarm_name = AlarmType.get_name(message.location_ext.alarm)

        pos = self.make_position()
        pos.timestamp = timestamp_current() # str_to_timestamp(message.location.ymdhms)

        object_assign(pos,message.location_ext.dict())
        pos.position_source = PositionSource.LBS
        self.convertLbsLocation(pos)
        self.savePosition(pos)
        data = hash_object(pos,excludes=('_id',))

        object_assign(alarm,data)

        alarm.alarm_name = AlarmType.get_name(message.location_ext.alarm)
        alarm.save()
        # 推送更新的报警包
        self.device_app_pub_channel.publish_or_produce(json.dumps(data))