예제 #1
0
    def pushS4(self, op):
        """
        res = []
        res.append(dict(tid='tid1',
                        login_status=1))
        res.append(dict(tid='tid2',
                        login_status=2))
        """

        res = [] 
        corp = self.db.get("SELECT * FROM V_TERMINAL where tid = %s",
                            self.tid) 
        if corp:
            terminals = self.db.query("SELECT tid FROM V_TERMINAL WHERE cid= %s",
                                      corp['cid'])
            for terminal in terminals:
                t = QueryHelper.get_terminal_info(terminal['tid'], self.db, self.redis) 
                res.append(dict(tid=terminal['tid'],
                                biz_type=0,
                                login_status=t['login']))
        else:
            res = []

        packet = dict(packet_type="S4",
                      res=res)
        res = self.push(packet)

        return res
예제 #2
0
    def pushS7(tid, db, redis):
        """
        S7
        Information about basic info.

        res = []
        res.append(dict(tid=tid,
                        alias='jiajiajia',
                        icon_type=2,
                        owner_mobile='13011292217',
                        mannual_status=1,
                        ))
        """
        res = []
        terminal = QueryHelper.get_terminal_info(tid, db, redis)
        packet = dict(tid=tid,
                      biz_type=terminal.get('biz_type', 0),
                      alias=terminal['alias'],
                      icon_type=terminal['icon_type'],
                      owner_mobile=terminal['owner_mobile'],
                      mannual_status=terminal['mannual_status'])

        res.append(packet)

        packet = dict(packet_type="S7",
                      res=res)
        res = WSPushHelper.push_packet(tid, packet, db, redis)
예제 #3
0
파일: packettask.py 프로젝트: jcsy521/ydws
    def notify_to_parents(self, alias, location, mobile, region_id=None):
        """Push information to clinet through push.

        PUSH 1.0
        """
        flag = self.check_timestamp(int(location['timestamp']))
        if not flag: 
            return

        category = location.category
        dev_id = location.dev_id

        if not location['pbat']:
            terminal = QueryHelper.get_terminal_info(dev_id, self.db, self.redis) 
            location['pbat'] = terminal['pbat'] if terminal['pbat'] is not None else 0 

        if mobile:
            # 1: push to android
            android_push_list_key = get_android_push_list_key(mobile) 
            android_push_list = self.redis.getvalue(android_push_list_key) 
            if android_push_list: 
                for push_id in android_push_list: 
                    push_key = NotifyHelper.get_push_key(push_id, self.redis) 
                    NotifyHelper.push_to_android(category, dev_id, alias, location, push_id, push_key, region_id)
            # 2: push  to ios 
            ios_push_list_key = get_ios_push_list_key(mobile) 
            ios_push_list = self.redis.getvalue(ios_push_list_key) 
            if ios_push_list: 
                for ios_id in ios_push_list: 
                    ios_badge = NotifyHelper.get_iosbadge(ios_id, self.redis) 
                    NotifyHelper.push_to_ios(category, dev_id, alias, location, ios_id, ios_badge, region_id)
예제 #4
0
    def pushS6(tid, db, redis):
        """
        S6
        Information about basic info.

        res = []
        res.append(dict(tid=tid,
                        gps=8,
                        gsm=8,
                        pbat=8,
                        ))

        """
        res = []
        terminal = QueryHelper.get_terminal_info(tid, db, redis)
        packet = dict(tid=tid,
                      biz_type=terminal.get('biz_type', 0),
                      gps=terminal['gps'],
                      gsm=terminal['gsm'],
                      pbat=terminal['pbat'])
        res.append(packet)

        packet = dict(packet_type="S6",
                      res=res)

        res = WSPushHelper.push_packet(tid, packet, db, redis)
예제 #5
0
파일: public.py 프로젝트: jcsy521/ydws
def update_terminal_dynamic_info(db, redis, location):
    """Update terminal's dynamic info in db and redis.
    Then inclues gps, gsm, pbat.
    """
    # db
    tid = location.dev_id
    fields = []

    # NOTE: only gps, gsm, pbat should be updated
    keys = ['gps', 'gsm', 'pbat']
    for key in keys:
        if location.get(key, None) is not None:
            fields.append(key + " = " + str(location[key]))
    set_clause = ','.join(fields)
    if set_clause:
        db.execute("UPDATE T_TERMINAL_INFO"
                   "  SET " + set_clause +
                   "  WHERE tid = %s",
                   tid)
    # redis
    terminal_info = QueryHelper.get_terminal_info(tid, db, redis)
    if terminal_info:
        terminal_info_key = get_terminal_info_key(tid)
        for key in terminal_info:
            value = location.get(key, None)
            if value is not None:
                terminal_info[key] = value
        redis.setvalue(terminal_info_key, terminal_info)
예제 #6
0
    def pushS4(tid, db, redis):
        """
        S4
        Information about online, offline.

        e.g.

        res = []
        res.append(dict(tid='tid1',
                        login_status=1))
        res.append(dict(tid='tid2',
                        login_status=2))

        """

        res = []

        t = QueryHelper.get_terminal_info(tid, db, redis)
        if t:
            res.append(dict(tid=tid,
                            biz_type=t.get('biz_type', 0),
                            login_status=t['login'] if t['login'] == 0 else 1))

        packet = dict(packet_type="S4",
                      res=res)
        res = WSPushHelper.push_packet(tid, packet, db, redis)
예제 #7
0
파일: public.py 프로젝트: jcsy521/ydws
def update_terminal_info_ydwq(db, redis, t_info):
    """Update terminal's info in db and redis.
    """
    terminal_info_key = get_terminal_info_key(t_info['tid'])
    terminal_info = QueryHelper.get_terminal_info(t_info['tid'],
                                                  db, redis)

    # 1: db
    fields = []
    # gps, gsm, pbat, changed by position report
    keys = ['gps', 'gsm', 'pbat', 'login']
    for key in keys:
        value = t_info.get(key, None)
        if value is not None and value != terminal_info[key]:
            fields.append(key + " = " + str(t_info[key]))

    set_clause = ','.join(fields)
    if set_clause:
        db.execute("UPDATE T_TERMINAL_INFO"
                   "  SET " + set_clause +
                   "  WHERE tid = %s",
                   t_info['tid'])
    # 2: redis
    for key in terminal_info:
        value = t_info.get(key, None)
        if value is not None:
            terminal_info[key] = value
    redis.setvalue(terminal_info_key, terminal_info)

    return terminal_info
예제 #8
0
파일: public.py 프로젝트: jcsy521/ydws
def update_terminal_info(db, redis, t_info):
    """Update terminal's info in db and redis.

    :arg db: database instance 
    :arg redis: redis instance
    :arg terminal: dict, e.g.

        {
          'mobile':'',
          ...
        }

    NOTE: 
    Only those properties which are different from platform is needed to change.
    """
    tid = t_info['dev_id']
    terminal_info_key = get_terminal_info_key(tid)
    terminal_info = QueryHelper.get_terminal_info(tid,
                                                  db, redis)

    # 1: db
    set_clause_dct = []
    # gps, gsm, pbat, changed by position report
    keys = ['mobile', 'defend_status', 'login', 'keys_num', 'fob_status', 'mannual_status',
            'softversion', 'bt_mac', 'bt_name', 'dev_type']

    for key in keys:
        value = t_info.get(key, None)
        t_value = terminal_info.get(key, '')
        if value is not None and value != t_value:
            set_clause_dct.append(key + " = " + "'" + str(t_info[key]) + "'")

    if 'login_time' in t_info:
        set_clause_dct.append('login_time' + " = " + str(t_info['login_time']))
        login_time_key = get_login_time_key(tid)
        redis.setvalue(login_time_key, t_info['login_time'])

    set_clause = ','.join(set_clause_dct)
    if set_clause:
        sql_cmd = ("UPDATE T_TERMINAL_INFO "
                   "  SET " + set_clause +
                   "  WHERE tid = %s")
        db.execute(sql_cmd, tid)

    # 2: redis
    for key in terminal_info:
        value = t_info.get(key, None)
        if value is not None:
            terminal_info[key] = value
    redis.setvalue(terminal_info_key, terminal_info)

    # NOTE:wspush to client. terminal basic info
    WSPushHelper.pushS6(tid, db, redis)
    return terminal_info
예제 #9
0
파일: public.py 프로젝트: jcsy521/ydws
def update_fob_info(db, redis, fobinfo):
    """Update fob's information.

    NOTE: deprecated.
    Tracker has not fob now.
    """
    terminal_info_key = get_terminal_info_key(fobinfo['dev_id'])
    terminal_info = QueryHelper.get_terminal_info(fobinfo['dev_id'],
                                                  db, redis)

    if int(fobinfo['operate']) == GATEWAY.FOB_OPERATE.ADD:
        db.execute("INSERT INTO T_FOB(tid, fobid)"
                   "  VALUES(%s, %s)"
                   "  ON DUPLICATE KEY"
                   "  UPDATE tid = VALUES(tid),"
                   "         fobid = VALUES(fobid)",
                   fobinfo['dev_id'], fobinfo['fobid'])
        fob_list = terminal_info['fob_list']
        if fob_list:
            fob_list.append(fobinfo['fobid'])
        else:
            fob_list = [fobinfo['fobid'], ]
        terminal_info['fob_list'] = list(set(fob_list))
        terminal_info['keys_num'] = len(terminal_info['fob_list'])
        db.execute("UPDATE T_TERMINAL_INFO"
                   "  SET keys_num = %s"
                   "  WHERE tid = %s",
                   terminal_info['keys_num'], fobinfo['dev_id'])
        redis.setvalue(terminal_info_key, terminal_info)
    elif int(fobinfo['operate']) == GATEWAY.FOB_OPERATE.REMOVE:
        db.execute("DELETE FROM T_FOB"
                   "  WHERE fobid = %s"
                   "    AND tid = %s",
                   fobinfo['fobid'], fobinfo['dev_id'])
        fob_list = terminal_info['fob_list']
        if fob_list:
            if fobinfo['fobid'] in fob_list:
                fob_list.remove(fobinfo['fobid'])
        else:
            fob_list = []
        terminal_info['fob_list'] = list(set(fob_list))
        terminal_info['keys_num'] = len(terminal_info['fob_list'])
        db.execute("UPDATE T_TERMINAL_INFO"
                   "  SET keys_num = %s"
                   "  WHERE tid = %s",
                   terminal_info['keys_num'], fobinfo['dev_id'])
        redis.setvalue(terminal_info_key, terminal_info)
    else:
        pass
예제 #10
0
파일: corpsingle.py 프로젝트: jcsy521/ydws
 def get(self):
     """Just just to a new page. 
     """
     # NOTE: The se_id should can be found in platform.
     se_id = self.get_argument("se_id", "")
     single_event = QueryHelper.get_single_event_by_se_id(se_id, self.db)
     terminal = QueryHelper.get_terminal_info(single_event["tid"], self.db, self.redis)
     self.render(
         "single_point.html",
         single_id=single_event["sid"],
         alias=terminal["alias"],
         tid=single_event.get("tid", ""),
         start_time=single_event.get("start_time"),
         end_time=single_event.get("end_time"),
     )
예제 #11
0
파일: event.py 프로젝트: jcsy521/ydws
    def get(self):
        """Get event info.
        """
        status = WXErrorCode.SUCCESS
        try:
            body = self.request.body
            openid = self.getopenid()
            user = self.db.get("SELECT uid, mobile "
                               "  FROM T_USER "
                               "  WHERE openid = %s", 
                               openid)

            if user is None:
                mobile = ''
                status = WXErrorCode.USER_BIND
                message=WXErrorCode.ERROR_MESSAGE[status]
                self.render('error.html',
                            status=status,
                            message=message)
                return
            else:
                mobile = user['mobile']
            try:
                res = self.db.query("SELECT tid FROM T_TERMINAL_INFO "
                                    "  WHERE owner_mobile = %s",
                                    mobile)
            except MySQLdb.Error as e:
                logging.exception("[WEIXIN]event search terminals failed, Exception:%s",
                              e.args)
            if not res:
                res = []
            for r in res:
                terminal = QueryHelper.get_terminal_info(r['tid'], self.db, self.redis)  
                r['alias'] = terminal['alias']
            self.render("event.html",  
                        openid=openid, 
                        res=res)

        except Exception as e:
            status = WXErrorCode.FAILED
            logging.exception("[WEIXIN] get event failed, Execptin:%s ",
                              e.args)
            self.render('error.html', 
                        status=status,
                        message=WXErrorCode.ERROR_MESSAGE[status])
예제 #12
0
파일: checkertask.py 프로젝트: jcsy521/ydws
 def check_poweroff_timeout(self):
     logging.info("[CELERY] checkertask check poweroff timeout started.")
     try:
         terminals = self.db.query("SELECT tpt.tid, tpt.sms_flag, tpt.timestamp"
                                   "  FROM T_POWEROFF_TIMEOUT as tpt, T_TERMINAL_INFO as tti"
                                   "  WHERE tti.tid = tpt.tid"
                                   "  AND tti.service_status = 1"
                                   "  AND tti.login = %s"
                                   "  AND tpt.sms_flag = %s"
                                   "  AND tpt.timestamp < %s",
                                   GATEWAY.TERMINAL_LOGIN.OFFLINE, GATEWAY.POWEROFF_TIMEOUT_SMS.UNSEND, (time.time() - 2*60*60))
         for terminal in terminals:
             terminal_info = QueryHelper.get_terminal_info(terminal.tid, self.db, self.redis)
             if int(terminal_info['pbat']) < 5:
                 user = QueryHelper.get_user_by_tid(terminal.tid, self.db)
                 sms = SMSCode.SMS_POWEROFF_TIMEOUT % terminal_info['alias'] 
                 SMSHelper.send(user.owner_mobile, sms)
                 self.update_sms_flag(terminal.tid)
                 logging.info("[CELERY] Send poweroff timeout sms to user:%s, tid:%s", user.owner_mobile, terminal.tid)
     except Exception as e:
         logging.exception("[CELERY] Check terminal poweroff timeout exception.")
예제 #13
0
    def pushS5(tid, body, db, redis):
        """
        S5
        Information about alarm.

        res = []
        res.append(dict(tid=tid,
                        category=2, 
                        pbat=100,
                        type=1,
                        timestamp=1410939622,
                        longitude=419004000,
                        latitude=143676000,
                        clongitude=419004000,
                        clatitude=143676000,
                        name='test name',
                        speed=111,
                        degree=203,
                        gsm=0,
                        locate_error=100,
                        gps=25,
                        alias=111,
                        region_id=11
                    ))

        """
        res = []
        terminal = QueryHelper.get_terminal_info(tid, db, redis)
        body['biz_type'] = terminal.get('biz_type', 0)
        body['speed'] = int(round(body['speed']))

        res.append(body)

        packet = dict(packet_type="S5",
                      res=res)

        res = WSPushHelper.push_packet(tid, packet, db, redis)
예제 #14
0
파일: packettask.py 프로젝트: jcsy521/ydws
    def push_to_client(self, location):
        """Push information to weixin and wspush.
        """
        #NOTE: use timestamp first. If it does not work, use gps_time.
        if location.get('timestamp',''):
            timestamp = location['timestamp']
        else:
            timestamp = location['gps_time']
        flag = self.check_timestamp(int(timestamp))
        if not flag: 
            return

        tid = location['dev_id']
        terminal = QueryHelper.get_terminal_info(tid, self.db, self.redis)
        body = dict(tid=tid,
                    category=location['category'], 
                    type=location['type'], 
                    timestamp=timestamp,
                    gps_time=location['gps_time'],
                    latitude=location.get('lat',0),
                    longitude=location.get('lon',0),
                    clatitude=location.get('cLat',0),
                    clongitude=location.get('cLon',0),
                    name=location['name'] if location.get('name',None) is not None else '',
                    degree=location.get('degree',0),
                    speed=location.get('speed',0),
                    locate_error=location.get('locate_error',0),
                    region_id=location.get('region_id',-1),
                    # for terminal
                    alias=terminal.get('alias'),
                    gps=terminal.get('gps'),
                    gsm=terminal.get('gsm'),
                    pbat=terminal.get('pbat'))

        WSPushHelper.pushS5(tid, body, self.db, self.redis)
        WeixinPushHelper.push(tid, body, self.db, self.redis)
예제 #15
0
파일: inclastinfo.py 프로젝트: jcsy521/ydws
        def _on_finish(db):
            self.db = db
            try:
                data = DotDict(json_decode(self.request.body))
                track_lst = data.get("track_lst", [])
                # NOTE: nearly all timestamp's len is 10, here use 13
                current_time = int(time.time() * 1000)
                lastinfo_time = data.get("lastinfo_time")
            except Exception as e:
                status = ErrorCode.ILLEGAL_DATA_FORMAT
                logging.info(
                    "[UWEB] inlastfinfo for corp failed, message: %s, Exception: %s, request: \n%s",
                    ErrorCode.ERROR_MESSAGE[status],
                    e.args,
                    self.request.body,
                )
                self.write_ret(status)
                IOLoop.instance().add_callback(self.finish)
                return

            try:
                status = ErrorCode.SUCCESS
                REMOVE_GID_TID = []  # [(gid, tid),(gid,tid),]
                res_type = 0
                # NOTE: first time, lastinfo_time = -1, set the lsstinfo_time
                # as current_time
                if lastinfo_time == -1:
                    # logging.info("[UWEB] res_type=2, first time, cid:%s", self.current_user.cid)
                    res_type = 2
                    lastinfo_time = current_time

                corp = self.db.get("SELECT cid, name, mobile FROM T_CORP WHERE cid = %s", self.current_user.cid)
                if self.current_user.oid == UWEB.DUMMY_OID:
                    uid = self.current_user.cid
                    groups = self.db.query("SELECT id gid, name FROM T_GROUP WHERE corp_id = %s" "  ORDER BY id", uid)
                else:
                    uid = self.current_user.oid
                    groups = self.db.query("SELECT group_id FROM T_GROUP_OPERATOR WHERE oper_id = %s", uid)
                    gids = [g.group_id for g in groups]
                    groups = self.db.query(
                        "SELECT id gid, name FROM T_GROUP WHERE id IN %s" "  ORDER BY id", tuple(DUMMY_IDS + gids)
                    )

                corp_info = dict(name=corp["name"] if corp else "", cid=corp["cid"] if corp else "")

                corp_info_key = get_corp_info_key(uid)

                corp_info_tuple = self.redis.getvalue(corp_info_key)
                if corp_info_tuple:
                    corp_info_old, corp_info_time = corp_info_tuple
                else:
                    corp_info_old, corp_info_time = None, None

                if corp_info_old is not None:
                    if corp_info_old != corp_info:
                        # logging.info("[UWEB] res_type=2, corp_info changed, cid:%s", self.current_user.cid)
                        res_type = 2
                        self.redis.setvalue(corp_info_key, (corp_info, current_time))
                    else:
                        if lastinfo_time < corp_info_time:
                            # logging.info("[UWEB] res_type=2, corp_info time changed, lastinfo_time:%s < corp_info_time:%s, cid:%s",
                            # lastinfo_time, corp_info_time,
                            # self.current_user.cid)
                            res_type = 2
                else:
                    self.redis.setvalue(corp_info_key, (corp_info, current_time))

                _now_time = time.time()
                if (_now_time - _start_time) > 5:
                    logging.info(
                        "[UWEB] Inclastinfo step1_corp used time: %s > 5s, cid: %s",
                        _now_time - _start_time,
                        self.current_user.cid,
                    )

                res = DotDict(
                    name=corp_info["name"],
                    cid=corp_info["cid"],
                    online=0,
                    offline=0,
                    groups=[],
                    lastinfo_time=current_time,
                )

                group_info_key = get_group_info_key(uid)
                group_info_tuple = self.redis.getvalue(group_info_key)
                if group_info_tuple:
                    group_info_old, group_info_time = group_info_tuple
                else:
                    group_info_old, group_info_time = None, None
                if group_info_old is not None:
                    if group_info_old != groups:
                        # logging.info("[UWEB] res_type=2, group_info changed, cid:%s", self.current_user.cid)
                        res_type = 2
                        self.redis.setvalue(group_info_key, (groups, current_time))
                    else:
                        if lastinfo_time < group_info_time:
                            # logging.info("[UWEB] res_type=2, group_info time changed, lastinfo_time:%s < group_info_time:%s, cid:%s",
                            # lastinfo_time, group_info_time,
                            # self.current_user.cid)
                            res_type = 2
                else:
                    self.redis.setvalue(group_info_key, (groups, current_time))

                for group in groups:
                    group["trackers"] = {}
                    terminals = QueryHelper.get_terminals_by_group_id(group.gid, db)
                    tids = [str(terminal.tid) for terminal in terminals]
                    _now_time = time.time()
                    if (_now_time - _start_time) > 5:
                        logging.info(
                            "[UWEB] Inclastinfo step1_group_sql used time: %s > 5s, cid: %s, gid: %s",
                            _now_time - _start_time,
                            self.current_user.cid,
                            group.gid,
                        )

                    terminal_info_key = get_group_terminal_info_key(uid, group.gid)
                    terminal_info_tuple = self.redis.getvalue(terminal_info_key)
                    if terminal_info_tuple:
                        terminal_info_old, terminal_info_time = terminal_info_tuple
                    else:
                        terminal_info_old, terminal_info_time = None, None
                    if terminal_info_old is not None:
                        if terminal_info_old != tids:
                            # logging.info("[UWEB] res_type=2, terminal_info changed, cid:%s", self.current_user.cid)
                            res_type = 2
                            self.redis.setvalue(terminal_info_key, (tids, current_time))
                        else:
                            if lastinfo_time < terminal_info_time:
                                # logging.info("[UWEB] res_type=2, terminal_info time changed, lastinfo_time:%s < terminal_info_time:%s, cid:%s",
                                # lastinfo_time, terminal_info_time,
                                # self.current_user.cid)
                                res_type = 2
                    else:
                        self.redis.setvalue(terminal_info_key, (tids, current_time))
                    _now_time = time.time()
                    if (_now_time - _start_time) > 5:
                        logging.info(
                            "[UWEB] Inclastinfo step1_group used time: %s > 5s, cid: %s, gid: %s",
                            _now_time - _start_time,
                            self.current_user.cid,
                            group.gid,
                        )
                    for tid in tids:
                        _now_time = time.time()
                        if (_now_time - _start_time) > 5:
                            logging.info(
                                "[UWEB] Inclastinfo step2 used time: %s > 5s, cid: %s",
                                _now_time - _start_time,
                                self.current_user.cid,
                            )

                        group["trackers"][tid] = {}
                        # 1: get terminal info
                        terminal = QueryHelper.get_terminal_info(tid, self.db, self.redis)
                        if terminal["login"] == GATEWAY.TERMINAL_LOGIN.SLEEP:
                            terminal["login"] = GATEWAY.TERMINAL_LOGIN.ONLINE

                        if terminal["login"] == GATEWAY.TERMINAL_LOGIN.ONLINE:
                            res["online"] += 1
                        else:
                            res["offline"] += 1

                        # 2: get location
                        location = QueryHelper.get_location_info(tid, self.db, self.redis)
                        if location and not (location.clatitude or location.clongitude):
                            location_key = get_location_key(str(tid))
                            locations = [location]
                            # NOTE: offset latlon
                            # locations = get_locations_with_clatlon(locations, self.db)
                            location = locations[0]
                            self.redis.setvalue(location_key, location, EVENTER.LOCATION_EXPIRY)

                        if location and location["name"] is None:
                            location["name"] = ""

                        if location and location["type"] == 1:  # cellid
                            location["locate_error"] = 500  # mile

                        acc_status_info = QueryHelper.get_acc_status_info_by_tid(
                            self.client_id, tid, self.db, self.redis
                        )
                        acc_message = acc_status_info["acc_message"]
                        op_status = acc_status_info["op_status"]

                        # 1: build the basic_info
                        basic_info = dict(
                            defend_status=terminal["defend_status"] if terminal["defend_status"] is not None else 1,
                            mannual_status=terminal["mannual_status"] if terminal["mannual_status"] is not None else 1,
                            acc_message=acc_message,
                            op_status=op_status,
                            fob_status=terminal["fob_status"] if terminal["fob_status"] is not None else 0,
                            timestamp=location["timestamp"] if location else 0,
                            speed=location.speed if location else 0,
                            # NOTE: degree's type is Decimal,
                            # float() it before json_encode
                            degree=float(location.degree) if location else 0.00,
                            locate_error=location.get("locate_error", 20) if location else 20,
                            name=location.name if location else "",
                            type=location.type if location else 1,
                            latitude=location["latitude"] if location else 0,
                            longitude=location["longitude"] if location else 0,
                            clatitude=location["clatitude"] if location else 0,
                            clongitude=location["clongitude"] if location else 0,
                            login=terminal["login"] if terminal["login"] is not None else 0,
                            bt_name=terminal.get("bt_name", "") if terminal else "",
                            bt_mac=terminal.get("bt_mac", "") if terminal else "",
                            dev_type=terminal["dev_type"] if terminal.get("dev_type", None) is not None else "A",
                            gps=terminal["gps"] if terminal["gps"] is not None else 0,
                            gsm=terminal["gsm"] if terminal["gsm"] is not None else 0,
                            pbat=terminal["pbat"] if terminal["pbat"] is not None else 0,
                            mobile=terminal["mobile"],
                            owner_mobile=terminal["owner_mobile"],
                            alias=terminal["alias"],
                            # keys_num=terminal['keys_num'] if terminal['keys_num'] is not None else 0,
                            keys_num=0,
                            icon_type=terminal["icon_type"] if terminal.get("icon_type", None) is not None else 0,
                            fob_list=terminal["fob_list"] if terminal["fob_list"] else [],
                        )

                        _now_time = time.time()
                        if (_now_time - _start_time) > 5:
                            logging.info(
                                "[UWEB] Inclastinfo step2_basic used time: %s > 5s, cid: %s",
                                _now_time - _start_time,
                                self.current_user.cid,
                            )
                        # 2: build track_info
                        track_info = []
                        for item in track_lst:
                            if tid == item["track_tid"]:
                                track_key = get_track_key(tid)
                                self.redis.setvalue(track_key, 1, UWEB.TRACK_INTERVAL)
                                # endtime = int(basic_info['timestamp'])-1 if basic_info['timestamp'] else (current_time/1000)-1
                                endtime = int(basic_info["timestamp"]) - 1
                                points_track = []

                                logging.info(
                                    "[UWEB] tid: %s, track_time, %s, %s", tid, int(item["track_time"]) + 1, endtime
                                )
                                # NOTE: offset latlon
                                # points_track = get_locations_with_clatlon(points_track, self.db)
                                for point in points_track:
                                    if point["clatitude"] and point["clongitude"]:
                                        t = dict(
                                            latitude=point["latitude"],
                                            longitude=point["longitude"],
                                            clatitude=point["clatitude"],
                                            clongitude=point["clongitude"],
                                            type=point["type"],
                                            timestamp=point["timestamp"],
                                        )
                                        track_info.append(t)
                                break

                        _now_time = time.time()
                        if (_now_time - _start_time) > 5:
                            logging.info(
                                "[UWEB] Inclastinfo step2_track used time: %s > 5s, cid: %s",
                                _now_time - _start_time,
                                self.current_user.cid,
                            )
                        # 3: build trace_info
                        trace_info = []
                        points_trace = []
                        points_trace = points_trace[-5:]
                        # points_trace = get_locations_with_clatlon(points_trace, self.db)
                        len_trace = 0
                        if points_trace:
                            for point in points_trace:
                                if len_trace >= 5:
                                    break
                                if point["clatitude"] and point["clongitude"]:
                                    trace_info.append(point["clatitude"])
                                    trace_info.append(point["clongitude"])
                                    len_trace += 1
                                else:
                                    continue

                        _now_time = time.time()
                        if (_now_time - _start_time) > 5:
                            logging.info(
                                "[UWEB] Inclastinfo step2_trace used time: %s > 5s, cid: %s",
                                _now_time - _start_time,
                                self.current_user.cid,
                            )

                        # 4: build alert_info
                        alarm_info_key = get_alarm_info_key(tid)
                        alarm_info_all = self.redis.getvalue(alarm_info_key)
                        alarm_info_all = alarm_info_all if alarm_info_all else []
                        alarm_info = []

                        if alarm_info_all:
                            for alarm in alarm_info_all:
                                # NOTE: here, check alarm's keeptime when kept
                                # in reids, not timestamp alarm occurs
                                if alarm.get("keeptime", None) is None:
                                    alarm["keeptime"] = alarm["timestamp"]
                                if alarm["keeptime"] >= lastinfo_time / 1000:
                                    alarm_info.append(alarm)

                        for alarm in alarm_info:
                            alarm["alias"] = terminal["alias"]

                        _now_time = time.time()
                        if (_now_time - _start_time) > 5:
                            logging.info(
                                "[UWEB] Inclastinfo step2_alarm used time: %s > 5s, cid: %s",
                                _now_time - _start_time,
                                self.current_user.cid,
                            )
                        group["trackers"][tid]["basic_info"] = basic_info
                        group["trackers"][tid]["track_info"] = track_info
                        group["trackers"][tid]["trace_info"] = trace_info
                        group["trackers"][tid]["alarm_info"] = alarm_info

                        terminal_detail_key = get_group_terminal_detail_key(uid, group.gid, tid)
                        terminal_detail_tuple = self.redis.getvalue(terminal_detail_key)
                        if terminal_detail_tuple:
                            terminal_detail_old, terminal_detail_time = terminal_detail_tuple
                        else:
                            terminal_detail_old, terminal_detail_time = None, None

                        if res_type != 2:
                            if terminal_detail_old is not None:
                                if terminal_detail_old != group["trackers"][tid]:
                                    self.redis.setvalue(terminal_detail_key, (group["trackers"][tid], current_time))
                                    # logging.info("[UWEB] res_type=1, terminal detail changed cid:%s", self.current_user.cid)
                                    res_type = 1
                                else:
                                    if lastinfo_time < terminal_detail_time:
                                        # logging.info("[UWEB] res_type=1, terminal detail time changed cid:%s", self.current_user.cid)
                                        res_type = 1
                                    else:
                                        # logging.info("[UWEB] res_type=0, terminal detail no changed cid:%s", self.current_user.cid)
                                        REMOVE_GID_TID.append((group.gid, tid))
                            else:
                                self.redis.setvalue(terminal_detail_key, (group["trackers"][tid], current_time))
                        else:
                            pass
                    res.groups.append(group)

                if res_type == 0:
                    res = DotDict(lastinfo_time=current_time)
                    self.write_ret(status, dict_=DotDict(res=res, res_type=res_type))
                else:
                    if res_type == 1:
                        for gid, tid in REMOVE_GID_TID:
                            # logging.info("[UWEB] res_type=1, gid: %s, tid: %s is tobe removed. cid:%s",
                            #             gid, tid, self.current_user.cid)
                            for index, group in enumerate(res.groups):
                                if gid == group["gid"]:
                                    del res.groups[index]["trackers"][tid]
                                    # logging.info("[UWEB] res_type=1, gid: %s, tid: %s is removed. cid:%s",
                                    # gid, tid, self.current_user.cid)

                        _groups = deepcopy(res.groups)
                        for index, group in enumerate(_groups):
                            if not group["trackers"]:
                                res.groups.remove(group)
                                # logging.info("[UWEB] res_type=1, gid: %s, has no tracker, remove it. cid:%s",
                                #             gid, self.current_user.cid)

                    self.write_ret(status, dict_=DotDict(res=res, res_type=res_type))

                _now_time = time.time()
                if (_now_time - _start_time) > 5:
                    logging.info(
                        "[UWEB] Inclastinfo step3 used time: %s > 5s, cid: %s",
                        _now_time - _start_time,
                        self.current_user.cid,
                    )
            except Exception as e:
                logging.exception(
                    "[UWEB] cid: %s get corp lastinfo failed. Exception: %s", self.current_user.cid, e.args
                )
                status = ErrorCode.SERVER_BUSY
                self.write_ret(status)
            IOLoop.instance().add_callback(self.finish)
예제 #16
0
    def pushS3(tid, db, redis, t_info=None):
        """
        S3
        Information about organization.

        :arg tid: string
        :arg db: database instance
        :arg redis: redis instance
        :arg t_info: dict, record the terminal's basic info. it has higher privilege then tid. e.g.

            {
                'tid':'',
                'umobile':'',
                'group_id':'',
                'cid':''
            }

        group_1=dict(group_id=1,
                     group_name='jia',
                     tids=['tid1',
                           'tid2', 
                           'tid3'])

        group_2=dict(group_id=2,
                     group_name='jia',
                     tids=['tid1',
                           'tid2', 
                           'tid3'])
        res = []
        res.append(group_1)
        res.append(group_2)
        """
        res = []
        if not t_info:  # tid is avaliable
            t_info = QueryHelper.get_terminal_basic_info(tid, db)

        cid = t_info.get('cid', '')

        groups = db.query("SELECT * FROM T_GROUP WHERE corp_id = %s",
                          cid)
        for group in groups:
            terminals = db.query("SELECT * FROM T_TERMINAL_INFO"
                                 "  WHERE group_id = %s "
                                 "  AND service_status= 1",  # only success
                                 group['id'])

            tids = []
            for terminal in terminals:
                t = QueryHelper.get_terminal_info(terminal['tid'], db, redis)
                dct = dict(tid=terminal['tid'],
                           biz_type=t.get('biz_type', 0))
                tids.append(dct)

            res.append(dict(group_id=group['id'],
                            group_name=group['name'],
                            tids=tids,
                            ))

        packet = dict(packet_type="S3",
                      res=res)

        res = WSPushHelper.push_packet(tid, packet, db, redis, t_info)
예제 #17
0
파일: business.py 프로젝트: jcsy521/ydws
    def post(self):
        """Query businesses according to the given params.
        """
        corplist = self.db.query("SELECT id, cid, name FROM T_CORP")
        corps = self.get_argument('corps', None)
        begintime = int(self.get_argument('begintime',0))
        endtime = int(self.get_argument('endtime',0))
        interval=[begintime, endtime]
        if not corps:
            corps = self.db.query("SELECT cid FROM T_CORP")
            corps = [str(corp.cid) for corp in corps]
            sql = "SELECT id FROM T_GROUP WHERE corp_id IN %s" % (tuple(corps + DUMMY_IDS),)
            groups = self.db.query(sql)
            groups = [str(group.id) for group in groups] + [-1,]
        else:
            groups = self.db.query("SELECT id FROM T_GROUP WHERE corp_id = %s", corps) 
            groups = [str(group.id) for group in groups]

        fields = DotDict(umobile="tu.mobile LIKE '%%%%%s%%%%'",
                         tmobile="tt.mobile LIKE '%%%%%s%%%%'",
                         begintime="tt.begintime >= %s",
                         endtime="tt.begintime <= %s",
                         login="******")
        
        for key in fields.iterkeys():
            #BIG NOTE: if online is to be got, "tt.login != 0" is good
            if key == 'login' and self.get_argument(key, None) == '1':
                fields[key] = "tt.login != 0"
                continue

            v = self.get_argument(key, None)
            if v:
                if not check_sql_injection(v):
                    logging.error("Search business condition contain SQL inject. %s : %s", key, v)
                    self.render('errors/error.html',
                        message=ErrorCode.ERROR_MESSAGE[ErrorCode.SELECT_CONDITION_ILLEGAL])
                    return
                else:
                    fields[key] = fields[key] % (v,)
            else:
                fields[key] = None

        where_clause = ' AND '.join([v for v in fields.itervalues()
                                     if v is not None])
        try:
            sql = ("SELECT tt.tid, tt.login, tu.name as uname, tu.mobile as umobile, tt.mobile as tmobile,"
                   "  tt.softversion, tt.begintime, tt.endtime, tt.move_val, tt.static_val,"
                   "  tt.service_status, tt.bt_name, tt.bt_mac, tt.biz_type,"
                   "  tc.cnum, tcorp.name as ecname, tcorp.mobile as cmobile"
                   "  FROM T_TERMINAL_INFO as tt LEFT JOIN T_CAR as tc ON tt.tid = tc.tid"
                   "                             LEFT JOIN T_USER as tu ON tt.owner_mobile = tu.mobile"
                   "                             LEFT JOIN T_GROUP as tg ON tt.group_id = tg.id"
                   "                             LEFT JOIN T_CORP as tcorp ON tg.corp_id = tcorp.cid"
                   "  WHERE tt.service_status=1 AND tt.group_id IN %s ") % (tuple(groups + DUMMY_IDS),)
            if where_clause:
                sql += ' AND ' + where_clause

            businesses = self.db.query(sql)

            for i, business in enumerate(businesses):
                business['seq'] = i + 1
                #business['sms_status'] = self.get_sms_status(business['tmobile'])
                business['corp_name'] = ''
                #NOTE: if login !=0(offline), set login as 1(online)
                business['login'] = business['login'] if business['login']==0 else 1
                #biz = QueryHelper.get_biz_by_mobile(business['tmobile'], self.db)
                #business['biz_type'] = biz['biz_type'] if biz else 1
                terminal = QueryHelper.get_terminal_info(business['tid'], self.db, self.redis)
                business['pbat'] = terminal['pbat'] if terminal.get('pbat', None) is not None else 0 
                business['alias'] = business['cnum'] if business['cnum'] else business['tmobile']  

                for key in business:
                    if business[key] is None:
                        business[key] = ''

            # keep data in redis
            m = hashlib.md5()
            m.update(self.request.body)
            hash_ = m.hexdigest()
            mem_key = self.get_memcache_key(hash_)
            self.redis.setvalue(mem_key, businesses,
                                time=self.MEMCACHE_EXPIRY)
            
            self.render('business/search.html',
                        status=ErrorCode.SUCCESS,
                        message='',
                        interval=interval, 
                        businesses=businesses,
                        corplist=corplist,
                        hash_=hash_)
        except Exception as e:
            logging.exception("Search business failed. Exception: %s.",
                              e.args)
            self.render('errors/error.html',
                        message=ErrorCode.ERROR_MESSAGE[ErrorCode.SEARCH_BUSINESS_FAILURE])
예제 #18
0
        def _on_finish(db):
            self.db = db
            try:
                data = DotDict(json_decode(self.request.body))
                biz_type = data.get("biz_type", UWEB.BIZ_TYPE.YDWS)
                track_list = data.get("track_list", [])
                version_type = int(data.get("version_type", 0))
                logging.info("[UWEB] Lastposition request: %s", 
                             data)
            except Exception as e:
                self.write_ret(ErrorCode.ILLEGAL_DATA_FORMAT) 
                self.finish()
                return

            try:
                res = OrderedDict() 
                usable = 1
                status = ErrorCode.SUCCESS
                if data.get('tids', None):
                    terminals = []
                    for tid in data.tids:
                        terminal = QueryHelper.get_terminal_info(tid, self.db, self.redis) 
                        if terminal:
                            terminals.append(DotDict(tid=tid))
                        else:
                            logging.exception("[UWEB] tid: %s can not be found.", 
                                              tid)
                else:
                    if self.current_user.oid != UWEB.DUMMY_OID: # operator,Note: operator also has cid, so we check oid firstly.
                        groups = self.db.query("SELECT group_id "
                                               "  FROM T_GROUP_OPERATOR"
                                               "  WHERE oper_id = %s", 
                                               self.current_user.oid)
                        gids = [g.group_id for g in groups]
                        terminals = self.db.query("SELECT tid FROM T_TERMINAL_INFO"
                                                  "  WHERE (service_status = %s"
                                                  "         OR service_status = %s)"
                                                  "    AND biz_type = %s"
                                                  "    AND group_id IN %s"
                                                  "    ORDER BY LOGIN DESC",
                                                  UWEB.SERVICE_STATUS.ON, 
                                                  UWEB.SERVICE_STATUS.TO_BE_ACTIVATED, 
                                                  biz_type,
                                                  tuple(DUMMY_IDS + gids))
                    elif self.current_user.cid != UWEB.DUMMY_CID: # Corp 
                        groups = self.db.query("SELECT id gid, name "
                                               "  FROM T_GROUP"
                                               "  WHERE corp_id = %s", 
                                               self.current_user.cid)
                        gids = [g.gid for g in groups]
                        terminals = self.db.query("SELECT tid FROM T_TERMINAL_INFO"
                                                  "  WHERE (service_status = %s"
                                                  "         OR service_status = %s)"
                                                  "    AND biz_type = %s"
                                                  "    AND group_id IN %s"
                                                  "    ORDER BY LOGIN DESC",
                                                  UWEB.SERVICE_STATUS.ON, 
                                                  UWEB.SERVICE_STATUS.TO_BE_ACTIVATED, 
                                                  biz_type,
                                                  tuple(DUMMY_IDS + gids))
                    else : # individual user
                        #NOTE: only show the terminals with login_permit is 1
                        terminals = self.db.query("SELECT tid FROM T_TERMINAL_INFO"
                                                  "  WHERE (service_status = %s"
                                                  "         OR service_status = %s)"
                                                  "    AND biz_type = %s"
                                                  "    AND owner_mobile = %s"
                                                  "    AND login_permit = 1"
                                                  "    ORDER BY login DESC",
                                                  UWEB.SERVICE_STATUS.ON, 
                                                  UWEB.SERVICE_STATUS.TO_BE_ACTIVATED, 
                                                  biz_type,
                                                  self.current_user.uid)
                _now_time = time.time()
                if (_now_time - _start_time) > 5:
                    logging.info("[UWEB] Lastinfo step1 used time: %s > 5s",
                                _now_time - _start_time)

                tids = [terminal.tid for terminal in terminals]
                for tid in tids:
                    _now_time = time.time()
                    if (_now_time - _start_time) > 5:
                        logging.info("[UWEB] Lastinfo step2 used time: %s > 5s",
                                    _now_time - _start_time)

                    res[tid] = {'car_info':{},
                                'track_info':[]}

                    # 0: get group info
                    group_info = get_group_info_by_tid(self.db, tid)

                    # 1: get terminal info 
                    terminal = QueryHelper.get_terminal_info(tid, self.db, self.redis) 
                    mobile = terminal['mobile']
                    if terminal['login'] == GATEWAY.TERMINAL_LOGIN.SLEEP:
                        terminal['login'] = GATEWAY.TERMINAL_LOGIN.ONLINE

                    # 2: get location 
                    location = QueryHelper.get_location_info(tid, self.db, self.redis)
                    if location and not (location.clatitude or location.clongitude):
                        location_key = get_location_key(str(tid))
                        locations = [location,] 
                        #locations = get_locations_with_clatlon(locations, self.db) 
                        location = locations[0]
                        if location.clatitude and location.clongitude:
                            self.redis.setvalue(location_key, location, EVENTER.LOCATION_EXPIRY)

                    if location and location['name'] is None:
                        location['name'] = location['name'] if location['name'] else ''


                    if location and location['type'] == 1: # cellid
                        location['locate_error'] = 500  # mile

                    avatar_full_path, avatar_path, avatar_name, avatar_time = self.get_avatar_info(mobile)
                    service_status = QueryHelper.get_service_status_by_tmobile(self.db, mobile)

                    acc_status_info = QueryHelper.get_acc_status_info_by_tid(self.client_id, tid, self.db, self.redis)
                    acc_message = acc_status_info['acc_message']

                    car_info=dict(defend_status=terminal['defend_status'] if terminal.get('defend_status', None) is not None else 1,
                                  service_status=service_status,
                                  mannual_status=terminal['mannual_status'] if terminal.get('mannual_status', None) is not None else 1,
                                  acc_message=acc_message,
                                  fob_status=terminal['fob_status'] if terminal.get('fob_status', None) is not None else 0,
                                  timestamp=location['timestamp'] if location else 0,
                                  speed=location.speed if location else 0,
                                  # NOTE: degree's type is Decimal, float() it before json_encode
                                  degree=float(location.degree) if location else 0.00,
                                  locate_error=location.get('locate_error', 20) if location else 20,
                                  name=location.name if location else '',
                                  type=location.type if location else 1,
                                  latitude=location['latitude'] if location else 0,
                                  longitude=location['longitude'] if location else 0, 
                                  clatitude=location['clatitude'] if location else 0,
                                  clongitude=location['clongitude'] if location else 0, 
                                  login=terminal['login'] if terminal['login'] is not None else 0,
                                  bt_name=terminal.get('bt_name', '') if terminal else '',
                                  bt_mac=terminal.get('bt_mac', '') if terminal else '',
                                  dev_type=terminal['dev_type'] if terminal.get('dev_type', None) is not None else 'A',
                                  gps=terminal['gps'] if terminal['gps'] is not None else 0,
                                  gsm=terminal['gsm'] if terminal['gsm'] is not None else 0,
                                  pbat=terminal['pbat'] if terminal['pbat'] is not None else 0,
                                  mobile=terminal['mobile'],
                                  owner_mobile = terminal['owner_mobile'],
                                  alias=terminal['alias'] if terminal['alias'] else terminal['mobile'],
                                  #keys_num=terminal['keys_num'] if terminal['keys_num'] is not None else 0,
                                  keys_num=0,
                                  group_id=group_info['group_id'],
                                  group_name=group_info['group_name'],
                                  icon_type=terminal['icon_type'],
                                  fob_list=terminal['fob_list'] if terminal['fob_list'] else [],
                                  avatar_path=avatar_path,
                                  avatar_time=avatar_time)

                    res[tid]['car_info'] = car_info
                
                lastposition_key = get_lastposition_key(self.current_user.uid)
                lastposition = self.redis.get(lastposition_key)

                lastposition_time_key = get_lastposition_time_key(self.current_user.uid)
                lastposition_time = self.redis.getvalue(lastposition_time_key)

                if lastposition == str(res):  
                    pass
                else:
                    lastposition_time = int(time.time())
                    self.redis.setvalue(lastposition_key, res) 
                    self.redis.setvalue(lastposition_time_key, lastposition_time)

                query_time = data.get('lastposition_time', None)
                # 2 check whether provide usable data   
                if int(data.get('cache', 0)) == 1:  # use cache
                    if int(query_time) == lastposition_time:
                        usable = 0 
                        res = {} 
                    else: 
                        usable = 1
                        for item in track_list:
                            track_tid = item['track_tid']
                            if track_tid not in tids:
                                logging.error("The terminal with tid: %s does not exist", 
                                              track_tid)
                            else:
                                track_time = item['track_time']
                                track_key = get_track_key(track_tid)
                                self.redis.setvalue(track_key, 1, UWEB.TRACK_INTERVAL)
                                car_info = res[track_tid]['car_info']
                                endtime = int(car_info['timestamp'])-1 if car_info['timestamp'] else int(lastposition_time)-1 
                                track_info = self.get_track_info(track_tid, int(track_time)+1, endtime)
                                res[track_tid]['track_info'] = track_info
                else: 
                    usable = 1
                    for item in track_list:
                        track_tid = item['track_tid']
                        if track_tid not in tids:
                            logging.error("The terminal with tid: %s does not exist", track_tid)
                        else:
                            track_time = item['track_time']
                            track_key = get_track_key(track_tid)
                            self.redis.setvalue(track_key, 1, UWEB.TRACK_INTERVAL)
                            car_info = res[track_tid]['car_info']
                            endtime = int(car_info['timestamp'])-1 if car_info['timestamp'] else int(time.time())-1
                            track_info = self.get_track_info(track_tid, int(track_time)+1, endtime) 
                            res[track_tid]['track_info'] = track_info
               
                if int(version_type) >= 1:
                    terminals = []
                    for k, v in res.iteritems():
                        v.update({'tid':k})
                        terminals.append(v)

                    self.write_ret(status, 
                                   dict_=DotDict(terminals=terminals,
                                                 usable=usable,
                                                 lastposition_time=lastposition_time))

                else:
                    self.write_ret(status, 
                                   dict_=DotDict(res=res,
                                                 usable=usable,
                                                 lastposition_time=lastposition_time))
                _now_time = time.time()
                if (_now_time - _start_time) > 5:
                    logging.info("[UWEB] Lastinfo step3 used time: %s > 5s",
                                _now_time - _start_time)
            except Exception as e:
                logging.exception("[UWEB] uid: %s get lastposition failed. Exception: %s", 
                                  self.current_user.uid, e.args) 
                status = ErrorCode.SERVER_BUSY
                self.write_ret(status)
            IOLoop.instance().add_callback(self.finish)
예제 #19
0
파일: lastinfo.py 프로젝트: jcsy521/ydws
    def post(self):
        try:
            data = DotDict(json_decode(self.request.body))
        except Exception as e:
            status = ErrorCode.ILLEGAL_DATA_FORMAT
            logging.info("[UWEB] lastfinfo failed, message: %s, request: \n%s", 
                         ErrorCode.ERROR_MESSAGE[status], self.request.body)
            self.write_ret(status)
            return 

        try:
            cars_info = OrderedDict() 
            usable = 0 # nothing is modified, the cars_info is no use, use the data last time
            status = ErrorCode.SUCCESS
            
            terminals = self.db.query("SELECT tid FROM T_TERMINAL_INFO"
                                      "  WHERE service_status = %s"
                                      "    AND owner_mobile = %s"
                                      "    AND login_permit = 1"
                                      "    ORDER BY LOGIN DESC",
                                      UWEB.SERVICE_STATUS.ON, self.current_user.uid)
            tids = [terminal.tid for terminal in terminals]

            # 1 inquery data     
            for tid in tids:
                # 1: get terminal info 
                terminal = QueryHelper.get_terminal_info(tid, self.db, self.redis) 
                if terminal['login'] == GATEWAY.TERMINAL_LOGIN.SLEEP:
                    terminal['login'] = GATEWAY.TERMINAL_LOGIN.ONLINE

                # 2: get location 
                location = QueryHelper.get_location_info(tid, self.db, self.redis)
                if location and not (location.clatitude or location.clongitude):
                    location_key = get_location_key(str(tid))
                    locations = [location,] 
                    locations = get_locations_with_clatlon(locations, self.db) 
                    location = locations[0]
                    self.redis.setvalue(location_key, location, EVENTER.LOCATION_EXPIRY)

                if location and location['name'] is None:
                    location['name'] = ''

                if location and location['type'] == 1: # cellid 
                    location['locate_error'] = 500  # mile

                car_dct = {}
                car_info=dict(defend_status=terminal['defend_status'] if terminal['defend_status'] is not None else 1,
                              mannual_status=terminal['mannual_status'] if terminal['mannual_status'] is not None else 1,
                              fob_status=terminal['fob_status'] if terminal['fob_status'] is not None else 0,
                              timestamp=location['timestamp'] if location else 0,
                              speed=location.speed if location else 0,
                              # NOTE: degree's type is Decimal, float() it before json_encode
                              degree=float(location.degree) if location else 0.00,
                              locate_error=location.get('locate_error', 20) if location else 20,
                              name=location.name if location else '',
                              type=location.type if location else 1,
                              latitude=location['latitude'] if location else 0,
                              longitude=location['longitude'] if location else 0, 
                              clatitude=location['clatitude'] if location else 0,
                              clongitude=location['clongitude'] if location else 0, 
                              login=terminal['login'] if terminal['login'] is not None else 0,
                              bt_name=terminal.get('bt_name', '') if terminal else '',
                              bt_mac=terminal.get('bt_mac', '') if terminal else '',
                              gps=terminal['gps'] if terminal['gps'] is not None else 0,
                              gsm=terminal['gsm'] if terminal['gsm'] is not None else 0,
                              pbat=terminal['pbat'] if terminal['pbat'] is not None else 0,
                              mobile=terminal['mobile'],
                              owner_mobile=terminal['owner_mobile'],
                              alias=terminal['alias'],
                              #keys_num=terminal['keys_num'] if terminal['keys_num'] is not None else 0,
                              keys_num=0,
                              fob_list=terminal['fob_list'] if terminal['fob_list'] else [])

                car_dct[tid]=car_info
                cars_info.update(car_dct)
            
            lastinfo_key = get_lastinfo_key(self.current_user.uid)

            # BIG NOTE: here, compare lastinfo and cars_info as str
            lastinfo = self.redis.get(lastinfo_key)

            lastinfo_time_key = get_lastinfo_time_key(self.current_user.uid)
            lastinfo_time = self.redis.getvalue(lastinfo_time_key)

            if lastinfo == str(cars_info):  
                pass
            else:
                lastinfo_time = int(time.time())
                self.redis.setvalue(lastinfo_key, cars_info) 
                self.redis.setvalue(lastinfo_time_key, lastinfo_time)

            track_tid = data.get('track_tid', None)  # use cache
            track_info = []
            query_time = data.get('time', None) 
            track_time = data.get('track_time', query_time) 
            
            # 2 check whether provide usable data   
            if data.get('cache', None):  # use cache
                if query_time is not None: # use time
                    if int(query_time) < lastinfo_time:
                        usable = 1
                        if track_tid:
                            if track_tid not in tids:
                                logging.error("The terminal with tid: %s does not exist", track_tid)
                            else:
                                track_key = get_track_key(track_tid)
                                self.redis.setvalue(track_key, 1, UWEB.TRACK_INTERVAL)
                                if int(query_time) == -1:
                                    pass
                                elif lastinfo_time - query_time > 1: # every 30 second, ternimal generate a location 
                                    car_info = cars_info[track_tid]
                                    endtime = int(car_info['timestamp'])-1 if car_info['timestamp'] else int(lastinfo_time)-1 
                                    track  = self.db.query("SELECT id, latitude, longitude," 
                                                           "    clatitude, clongitude"
                                                           "  FROM T_LOCATION"
                                                           "  WHERE tid = %s"
                                                           "    AND NOT (latitude = 0 OR longitude = 0)"
                                                           "    AND (timestamp BETWEEN %s AND %s)"
                                                           "    AND type = 0"
                                                           "    ORDER BY timestamp",
                                                           track_tid, int(track_time)+1, endtime)
                                    track = get_locations_with_clatlon(track, self.db)
                                    for item in track:
                                        if item['clatitude'] and item['clongitude']:
                                            track_info.append(item['clatitude'])
                                            track_info.append(item['clongitude'])
                    else: 
                        cars_info = {}
                        usable = 0
                else: # no time
                    if lastinfo == cars_info: 
                        cars_info = {}
                        usable = 0
                    else: 
                        usable = 1
            else: 
                usable = 1

            self.write_ret(status, 
                           dict_=DotDict(cars_info=cars_info,
                                         track_info=track_info,
                                         usable=usable,
                                         lastinfo_time=lastinfo_time)) 
        except Exception as e:
            logging.exception("[UWEB] uid: %s, data: %s get lastinfo failed. Exception: %s", 
                              self.current_user.uid, data, e.args) 
            status = ErrorCode.SERVER_BUSY
            self.write_ret(status)
예제 #20
0
파일: runtime.py 프로젝트: jcsy521/ydws
def handle_runtime(info, address, connection, channel, exchange, gw_binding, db, redis):
    """
    S23
    runtime status packet: {login [0:unlogin | 1:login],
                            defend_status [0:undefend | 1:defend],
                            gps:gsm:pbat [0-100:0-9:0-100]} 

    0: success, then record new terminal's address
    1: invalid SessionID
    """
    try:
        head = info.head
        body = info.body
        dev_id = head.dev_id
        resend_key, resend_flag = get_resend_flag(redis, dev_id, head.timestamp, head.command)
        if len(body) == 3:
            body.append('-1')
            body.append('0')
            logging.info("[GW] old version is compatible, append fob_pbat, is_send")
        if len(body) == 4:
            body.append('0')
            logging.info("[GW] old version is compatible, append is_send")
        args = DotDict(success=GATEWAY.RESPONSE_STATUS.SUCCESS,
                       command=head.command,
                       mannual_status='')
        sessionID = QueryHelper.get_terminal_sessionID(dev_id, redis)
        if sessionID != head.sessionID:
            args.success = GATEWAY.RESPONSE_STATUS.INVALID_SESSIONID 
        else:
            if resend_flag:
                logging.warn("[GW] Recv resend packet, head: %s, body: %s and drop it!",
                             info.head, info.body)
                terminal_info = QueryHelper.get_terminal_info(head.dev_id, db, redis)
                args.mannual_status = terminal_info['mannual_status']
            else:
                redis.setvalue(resend_key, True, GATEWAY.RESEND_EXPIRY)
                hp = AsyncParser(body, head)
                runtime_info = hp.ret 
                update_terminal_status(redis, head.dev_id, address)
                terminal_info = update_terminal_info(db, redis, runtime_info)
                args.mannual_status = terminal_info['mannual_status']
                db.execute("INSERT INTO T_RUNTIME_STATUS"
                           "  VALUES(NULL, %s, %s, %s, %s, %s, %s, %s, %s)",
                           head.dev_id, runtime_info['login'], runtime_info['defend_status'],
                           runtime_info['gps'], runtime_info['gsm'], runtime_info['pbat'],
                           runtime_info['fob_pbat'], head.timestamp)

                is_send = int(runtime_info['is_send'])
                if is_send:
                    terminal_info = QueryHelper.get_terminal_info(head.dev_id, db, redis)
                    alias = QueryHelper.get_alias_by_tid(head.dev_id, redis, db)
                    communication_staus = u'正常'
                    communication_mode = u'撤防'
                    gsm_strength = u'强'
                    gps_strength = u'强'
                    if int(terminal_info['login']) == GATEWAY.TERMINAL_LOGIN.ONLINE:
                        communication_staus = u'正常'
                    else:
                        communication_staus = u'异常'

                    if int(terminal_info['mannual_status']) == UWEB.DEFEND_STATUS.YES:
                        communication_mode = u'强力设防'
                    elif int(terminal_info['mannual_status']) == UWEB.DEFEND_STATUS.SMART:
                        communication_mode = u'智能设防'
                    else:
                        communication_mode= u'撤防'

                    pbat = int(terminal_info.get('pbat', 0))

                    gsm = int(terminal_info.get('gsm', 0))
                    if gsm < 3:
                        gsm_strength = u'弱'
                    elif gsm < 6:
                        gsm_strength = u'较弱'

                    gps = int(terminal_info.get('gps', 0))
                    if gps < 10:
                        gps_strength = u'弱' 
                    elif gps < 20:
                        gps_strength = u'较弱' 
                    elif gps < 30:
                        gps_strength = u'较强' 

                    runtime_sms = SMSCode.SMS_RUNTIME_STATUS % (alias, communication_staus, communication_mode, int(pbat), gsm_strength, gps_strength)
                    SMSHelper.send(terminal_info.owner_mobile, runtime_sms)
                    logging.info("[GW] Send runtime_status sms to user: %s, tid: %s",
                                 terminal_info.owner_mobile, head.dev_id)

            update_terminal_status(redis, head.dev_id, address)

        if args['success'] == GATEWAY.RESPONSE_STATUS.SUCCESS: 
            acc_status_info_key = get_acc_status_info_key(dev_id) 
            acc_status_info = redis.getvalue(acc_status_info_key) 
            if acc_status_info and (not acc_status_info['t2_status']): # T2(query) is need
                args['success'] = 3 # acc_status is changed 
                logging.info("[GW] ACC_status is changed, dev_id: %s, acc_status_info: %s", 
                             dev_id, acc_status_info)

        rc = RuntimeRespComposer(args)
        request = DotDict(packet=rc.buf,
                          address=address,
                          dev_id=dev_id)
        append_gw_request(request, connection, channel, exchange, gw_binding)
    except:
        logging.exception("[GW] Handle runtime status report exception.")
        GWException().notify()
예제 #21
0
파일: lastinfo.py 프로젝트: jcsy521/ydws
    def post(self):
        try:
            data = DotDict(json_decode(self.request.body))
            track_lst = data.get('track_lst', [])
            current_time = int(time.time()) 
            lastinfo_time = data.get('lastinfo_time') 
            #NOTE: first time, lastinfo_time = -1, set the lsstinfo_time as current_time 
            if lastinfo_time == -1:
                lastinfo_time = current_time 
        except Exception as e:
            status = ErrorCode.ILLEGAL_DATA_FORMAT
            logging.info("[UWEB] lastfinfo for corp failed, message: %s, Exception: %s, request: \n%s", 
                         ErrorCode.ERROR_MESSAGE[status], e.args, self.request.body)
            self.write_ret(status)
            return 

        try:
            status = ErrorCode.SUCCESS
            corp = self.db.get("SELECT cid, name, mobile FROM T_CORP WHERE cid = %s", self.current_user.cid)
            if self.current_user.oid == UWEB.DUMMY_OID:
                groups = self.db.query("SELECT id gid, name FROM T_GROUP WHERE corp_id = %s", self.current_user.cid)
            else:
                groups = self.db.query("SELECT group_id FROM T_GROUP_OPERATOR WHERE oper_id = %s", self.current_user.oid)
                gids = [g.group_id for g in groups]
                groups = self.db.query("SELECT id gid, name FROM T_GROUP WHERE id IN %s", tuple(DUMMY_IDS + gids))
 
            res = DotDict(name=corp.name if corp else '',
                          cid=corp.cid if corp else '',
                          online=0,
                          offline=0,
                          groups=[],
                          lastinfo_time=current_time)
            for group in groups:
                group['trackers'] = {} 
                terminals = self.db.query("SELECT tid FROM T_TERMINAL_INFO"
                                          "  WHERE group_id = %s"
                                          "    AND (service_status = %s"
                                          "         OR service_status = %s)",
                                          group.gid, UWEB.SERVICE_STATUS.ON, 
                                          UWEB.SERVICE_STATUS.TO_BE_ACTIVATED)
                tids = [str(terminal.tid) for terminal in terminals]

                for tid in tids:
                    group['trackers'][tid] = {} 
                    # 1: get terminal info 
                    terminal = QueryHelper.get_terminal_info(tid, self.db, self.redis) 
                    if terminal['login'] == GATEWAY.TERMINAL_LOGIN.SLEEP:
                        terminal['login'] = GATEWAY.TERMINAL_LOGIN.ONLINE

                    if terminal['login'] == GATEWAY.TERMINAL_LOGIN.ONLINE:
                        res['online'] +=1
                    else:
                        res['offline'] +=1

                    # 2: get location 
                    location = QueryHelper.get_location_info(tid, self.db, self.redis)
                    if location and not (location.clatitude or location.clongitude):
                        location_key = get_location_key(str(tid))
                        locations = [location,] 
                        #locations = get_locations_with_clatlon(locations, self.db) 
                        location = locations[0]
                        self.redis.setvalue(location_key, location, EVENTER.LOCATION_EXPIRY)

                    if location and location['name'] is None:
                        location['name'] = ''

                    if location and location['type'] == 1: # cellid 
                        location['locate_error'] = 500  # mile
                    #1: build the basic_info
                    basic_info=dict(defend_status=terminal['defend_status'] if terminal['defend_status'] is not None else 1,
                                    mannual_status=terminal['mannual_status'] if terminal['mannual_status'] is not None else 1,
                                    fob_status=terminal['fob_status'] if terminal['fob_status'] is not None else 0,
                                    timestamp=location['timestamp'] if location else 0,
                                    speed=location.speed if location else 0,
                                    # NOTE: degree's type is Decimal, float() it before json_encode
                                    degree=float(location.degree) if location else 0.00,
                                    locate_error=location.get('locate_error', 20) if location else 20,
                                    name=location.name if location else '',
                                    type=location.type if location else 1,
                                    latitude=location['latitude'] if location else 0,
                                    longitude=location['longitude'] if location else 0, 
                                    clatitude=location['clatitude'] if location else 0,
                                    clongitude=location['clongitude'] if location else 0, 
                                    login=terminal['login'] if terminal['login'] is not None else 0,
                                    bt_name=terminal.get('bt_name', '') if terminal else '',
                                    bt_mac=terminal.get('bt_mac', '') if terminal else '',
                                    gps=terminal['gps'] if terminal['gps'] is not None else 0,
                                    gsm=terminal['gsm'] if terminal['gsm'] is not None else 0,
                                    pbat=terminal['pbat'] if terminal['pbat'] is not None else 0,
                                    mobile=terminal['mobile'],
                                    owner_mobile=terminal['owner_mobile'],
                                    alias=terminal['alias'],
                                    #keys_num=terminal['keys_num'] if terminal['keys_num'] is not None else 0,
                                    keys_num=0,
                                    icon_type=terminal['icon_type'] if terminal.get('icon_type', None) is not None else 0,
                                    fob_list=terminal['fob_list'] if terminal['fob_list'] else [])

                    #2: build track_info
                    track_info = []
                    for item in track_lst:
                        if tid == item['track_tid']:
                            track_key = get_track_key(tid)
                            self.redis.setvalue(track_key, 1, UWEB.TRACK_INTERVAL)
                            endtime = int(basic_info['timestamp'])-1 if basic_info['timestamp'] else int(current_time)-1
                            points_track = self.db.query("SELECT id, latitude, longitude," 
                                                         "   clatitude, clongitude, type, timestamp"
                                                         "  FROM T_LOCATION"
                                                         "  WHERE tid = %s"
                                                         "    AND NOT (latitude = 0 OR longitude = 0)"
                                                         "    AND (timestamp BETWEEN %s AND %s)"
                                                         "    AND type = 0"
                                                         "    ORDER BY timestamp",
                                                         tid,
                                                         int(item['track_time'])+1, endtime)

                            #points_track = get_locations_with_clatlon(points_track, self.db)
                            for point in points_track: 
                                if point['clatitude'] and point['clongitude']:
                                    t = dict(latitude=point['latitude'],
                                             longitude=point['longitude'],
                                             clatitude=point['clatitude'],
                                             clongitude=point['clongitude'],
                                             type=point['type'],
                                             timestamp=point['timestamp'])
                                    track_info.append(t)
                            break

                    #3: build trace_info
                    trace_info = []
                    points_trace = self.db.query("SELECT distinct id, latitude, longitude," 
                                                 "    clatitude, clongitude"
                                                 "  FROM T_LOCATION"
                                                 "  WHERE tid = %s"
                                                 "    AND NOT (latitude = 0 OR longitude = 0)"
                                                 "    AND (timestamp  between %s and %s)"
                                                 "    AND type = 0"
                                                 "    ORDER BY timestamp",
                                                 tid, int(current_time)-60*5, basic_info['timestamp'])

                    #points_trace = get_locations_with_clatlon(points_trace, self.db)
                    points_trace = points_trace[:5] 
                    len_trace = 0
                    if points_trace:
                        for point in points_trace:
                            if len_trace >= 5:
                                break
                            if point['clatitude'] and point['clongitude']:
                                trace_info.append(point['clatitude'])
                                trace_info.append(point['clongitude'])
                                len_trace += 1
                            else:
                                continue

                    #4: build alert_info
                    alarm_info_key = get_alarm_info_key(tid)
                    alarm_info_all = self.redis.getvalue(alarm_info_key)
                    alarm_info_all  = alarm_info_all if alarm_info_all else []
                    alarm_info = []
                    
                    if alarm_info_all:
                        for alarm in alarm_info_all:
                            #NOTE: here, check alarm's keeptime when kept in reids, not timestamp alarm occurs
                            if alarm.get('keeptime', None) is None: 
                                alarm['keeptime'] = alarm['timestamp']
                            if alarm['keeptime'] >= lastinfo_time/1000:
                               alarm_info.append(alarm)
                        
                    if alarm_info:
                        # NOTE: here, do not remove alarm_info, it will automagically disappear after 1 day 
                        #self.redis.delete(alarm_info_key)
                        #logging.info("[UWEB] lastinfo_time: %s, alarm_info_key: %s, alarm_info: %s", lastinfo_time,  alarm_info_key, alarm_info)
                        pass

                    for alarm in alarm_info:
                        alarm['alias'] = terminal['alias']

                    group['trackers'][tid]['basic_info'] = basic_info
                    group['trackers'][tid]['track_info'] = track_info 
                    group['trackers'][tid]['trace_info'] = trace_info
                    group['trackers'][tid]['alarm_info'] = alarm_info
                res.groups.append(group)
            self.write_ret(status, 
                           dict_=DotDict(res=res,
                                         res_type=3))
        except Exception as e:
            logging.exception("[UWEB] cid: %s get corp lastinfo failed. Exception: %s", 
                              self.current_user.cid, e.args) 
            status = ErrorCode.SERVER_BUSY
            self.write_ret(status)