class SetHomeWifi(HelperHandler):
    @gen.coroutine
    def _deal_request(self):
        logging.debug("SetHomeWifi, %s", self.dump_req())

        self.set_header("Content-Type", "application/json; charset=utf-8")
        user_dao = self.settings["user_dao"]
        pet_dao = self.settings["pet_dao"]
        broadcast_rpc =  self.settings["broadcast_rpc"]
        device_dao=self.settings["device_dao"]
        conf = self.settings["appconfig"]
        res = {"status": error_codes.EC_SUCCESS}

        uid = None
        imei=None
        pet_id=None
        wifi_ssid = None
        wifi_bssid = None
        get_wifi_list_time=None
        # wifi_power = None
        try:
            uid = int(self.get_argument("uid"))
            imei=self.get_argument("imei")
            pet_id=self.get_argument("pet_id")
            token = self.get_argument("token")
            st = yield self.check_token("SetHomeWifi", res, uid, token)
            if not st:
               return
            wifi_ssid = self.get_argument("wifi_ssid")
            wifi_bssid = self.get_argument("wifi_bssid")
            # wifi_power = self.get_argument("wifi_power")
            get_wifi_list_time= self.get_argument("get_wifi_list_time",float(time.mktime(datetime.datetime.now().timetuple())))
        except Exception, e:
            logging.warning("SetHomeWifi, invalid args, %s %s",
                            self.dump_req(), str(e))
            res["status"] = error_codes.EC_INVALID_ARGS
            self.res_and_fini(res)
            return

        try:

            #info = yield pet_dao.get_user_pets(uid, ("pet_id", ))
            #if info is None:
            #    logging.warning("SetHomeWifi, not found, %s", self.dump_req())
            #    res["status"] = error_codes.EC_PET_NOT_EXIST
            #    self.res_and_fini(res)
            #    return

            set_res = yield pet_dao.set_home_wifi(uid, {"wifi_ssid": wifi_ssid,
                                                        "wifi_bssid":
                                                        wifi_bssid})
            if set_res.matched_count <= 0:
                logging.warning("SetHomeWifi, set fail, %s", self.dump_req())
                res["status"] = error_codes.EC_SYS_ERROR
                self.res_and_fini(res)
            else:
                home_wifi = {"wifi_ssid": wifi_ssid, "wifi_bssid": wifi_bssid}
                if imei is not None and pet_id is not None:
                    final_common_wifi=[]
                    arround_ten_minutes_wifi = yield device_dao.get_arround_ten_minutes_wifi_info(imei,utils.stamp2data(float(get_wifi_list_time)))
                    if arround_ten_minutes_wifi is not None:
                        for col in arround_ten_minutes_wifi:
                            logging.info("around_ten_minutes_wifi:%s", col)
                            tmp = utils.change_wifi_info(col["wifi_info"], True)
                            new_common_wifi = utils.get_new_common_wifi(
                                [], tmp, home_wifi)
                            final_common_wifi.append(new_common_wifi)
                    yield pet_dao.add_common_wifi_info(long(pet_id),
                                                       new_common_wifi)
        except Exception, e:
            logging.warning("SetHomeWifi, error, %s %s", self.dump_req(),
                            self.dump_exp(e))
            res["status"] = error_codes.EC_SYS_ERROR
            self.res_and_fini(res)
            return
示例#2
0
    def _OnReportLocationInfoReq(self,
                                 conn_id,
                                 header,
                                 body,
                                 peer,
                                 need_send_ack=True):
        # Parse packet
        pk = terminal_packets.ReportLocationInfoReq()
        pk.Parse(body)

        # 电量突然跳零的处理
        electric_quantity = (int)(pk.electric_quantity)
        device_info_electric_quantity = yield self.new_device_dao.get_device_info(
            pk.imei, ("electric_quantity", ))
        if (int)(device_info_electric_quantity.get("electric_quantity", 0)) - (
                int
        )(electric_quantity) > 10 and (int)(device_info_electric_quantity.get(
                "electric_quantity", 0)) - (int)(electric_quantity) < 100:
            electric_quantity = (
                int
            )(device_info_electric_quantity.get("electric_quantity", 0)) - 5
        elif (int
              )(device_info_electric_quantity.get("electric_quantity", 0)) - (
                  int
              )(electric_quantity) > 10 and device_info_electric_quantity.get(
                  "electric_quantity", 0) == 200:
            electric_quantity = 100
        # 电量突然跳零的处理
        pk.electric_quantity = electric_quantity

        pet_info = yield self.pet_dao.get_pet_info(
            ("pet_id", "uid", "home_wifi", "common_wifi", "target_energy"),
            device_imei=pk.imei)

        now_calorie = pk.calorie
        if pet_info is not None:
            # 卡路里重启调零的处理
            # sn_end_num = int(header.sn[-4:])
            # if sn_end_num <= 3:
            temp_diary = datetime.datetime.combine(datetime.date.today(),
                                                   datetime.time.min)
            res_info = yield self.pet_dao.get_sport_info(
                pet_info["pet_id"], temp_diary, datetime.datetime.now())
            if res_info is not None and len(res_info) > 0:
                if res_info[0].get("calorie", 0) > now_calorie:
                    now_calorie = res_info[0].get("calorie", 0)
        pk.calorie = now_calorie
        # 卡路里突然调零的处理

        str_pk = str(pk)

        logger.debug(
            "OnReportLocationInfoReq, parse packet success, pk=\"%s\" id=%u peer=%s",
            str_pk, conn_id, peer)
        self._register_conn(conn_id, pk.imei)
        self.imei_timer_mgr.add_imei(pk.imei)

        self._OnOpLog('c2s header=%s pk=%s peer=%s' % (header, str_pk, peer),
                      pk.imei)

        self.updateDeviceStatus(pk.imei)
        if need_send_ack:
            ack = terminal_packets.ReportLocationInfoAck(header.sn)
            yield self._send_res(conn_id, ack, pk.imei, peer)
        locator_time = pk.location_info.locator_time
        locator_status = pk.location_info.locator_status
        lnglat = []
        lnglat2 = []
        lnglat3 = []
        radius = -1
        radius2 = -1
        radius3 = -1

        if pk.location_info.locator_status == terminal_packets.LOCATOR_STATUS_GPS:

            ret = convert_coordinate((float(pk.location_info.longitude),
                                      float(pk.location_info.latitude)), "gps")
            if ret is not None:
                lnglat = [ret[0], ret[1]]

        elif pk.location_info.locator_status == terminal_packets.LOCATOR_STATUS_STATION:
            bts_info, near_bts_infos = util.new_split_locator_station_info(
                pk.location_info.station_locator_data)
            ret = yield self.get_location_by_bts_info(pk.imei, bts_info,
                                                      near_bts_infos)
            if ret is not None:
                lnglat = [ret[0], ret[1]]
                radius = ret[2]
        elif pk.location_info.locator_status == terminal_packets.LOCATOR_STATUS_MIXED:
            bts_info, near_bts_infos = util.new_split_locator_station_info(
                pk.location_info.station_locator_data)

            ret = yield self.get_location_by_mixed(
                pk.imei, bts_info, near_bts_infos, pk.location_info.mac)

            if ret is not None:
                lnglat = [ret[0], ret[1]]
                radius = ret[2]

            ret2 = yield self.get_location_by_wifi(pk.imei,
                                                   pk.location_info.mac)
            if ret2 is not None:
                lnglat2 = [ret2[0], ret2[1]]
                radius2 = ret2[2]

            ret3 = yield self.get_location_by_bts_info(pk.imei, bts_info,
                                                       near_bts_infos)
            if ret3 is not None:
                lnglat3 = [ret3[0], ret3[1]]
                radius3 = ret3[2]

        else:
            logger.warning("imei:%s location fail", pk.imei)

        if pet_info is None:
            logger.error("imei:%s pk:%s not found pet_info", pk, str_pk)
        time_stamp = int(time.time())
        if len(lnglat) != 0:
            location_info = {"lnglat": lnglat,
                             "radius": radius,
                             "locator_time": locator_time,
                             "locator_status": locator_status,
                             "server_recv_time": time_stamp}
            if len(lnglat2) != 0:
                location_info["lnglat2"] = lnglat2
                location_info["radius2"] = radius2
            if len(lnglat3) != 0:
                location_info["lnglat3"] = lnglat3
                location_info["radius3"] = radius3
            logger.info("imei:%s pk:%s location:%s", pk, str_pk,
                        str(location_info))
            if pet_info is not None:
                yield self.pet_dao.add_location_info(pet_info["pet_id"],
                                                     pk.imei, location_info)
                # uid = pet_info.get("uid", None)
                # if uid is not None:
                #     msg = push_msg.new_location_change_msg(
                #         "%.7f" % lnglat[1], "%.7f" % lnglat[0],
                #         int(time.mktime(locator_time.timetuple())), radius)
                #     try:
                #         yield self.msg_rpc.push_android(uids=str(uid),
                #                                         payload=msg,
                #                                         pass_through=1)
                #         # ios去掉推送
                #         # yield self.msg_rpc.push_ios(uids=str(uid), payload=msg)
                #     except Exception, e:
                #         logger.exception(e)
        now_time = datetime.datetime.now()
        yield self.new_device_dao.update_device_info(
            pk.imei,
            status=pk.status,
            electric_quantity=pk.electric_quantity,
            j01_repoter_date=now_time,
            server_recv_time=time_stamp)

        battery_status = 0
        if pk.electric_quantity <= LOW_BATTERY:
            battery_status = 1
            if pk.electric_quantity <= ULTRA_LOW_BATTERY:
                battery_status = 2
        device_info = yield self.new_device_dao.get_device_info(pk.imei, (
            "battery_status", ))
        # if device_info is not None:
        if not utils.battery_status_isequal(
                device_info.get("battery_status", 0), battery_status):
            yield self.new_device_dao.update_device_info(
                pk.imei, **{"battery_status": battery_status})
            yield self._SendBatteryMsg(pk.imei, pk.electric_quantity,
                                       battery_status, now_time)
        if pet_info is not None:
            sport_info = {}
            sport_info["diary"] = datetime.datetime.combine(
                datetime.date.today(), datetime.time.min)
            sport_info["step_count"] = pk.step_count
            sport_info["distance"] = pk.distance
            sport_info["calorie"] = pk.calorie
            sport_info["target_energy"] = pet_info.get("target_energy", 0)
            yield self.pet_dao.add_sport_info(pet_info["pet_id"], pk.imei,
                                              sport_info)

            if pk.location_info.locator_status == terminal_packets.LOCATOR_STATUS_MIXED:
                wifi_info = utils.change_wifi_info(pk.location_info.mac, True)
                common_wifi = pet_info.get("common_wifi", None)
                home_wifi = pet_info.get("home_wifi", None)
                new_common_wifi = utils.get_new_common_wifi(
                    common_wifi, wifi_info, home_wifi)
                uid = pet_info.get("uid", None)
                if uid is not None:
                    is_in_home = utils.is_in_home(home_wifi, new_common_wifi,
                                                  wifi_info)
                    self._SendPetInOrNotHomeMsg(pk.imei, is_in_home)
                yield self.pet_dao.add_common_wifi_info(pet_info["pet_id"],
                                                        new_common_wifi)

        if pk.location_info.locator_status == terminal_packets.LOCATOR_STATUS_MIXED:
            yield self.new_device_dao.report_wifi_info(pk.imei,
                                                       pk.location_info.mac)

        raise gen.Return(True)