示例#1
0
文件: s2.py 项目: JoaoCarabetta/s2-py
def s2_to_geo_boundary(s2_address, geo_json_conformant=False):
    """Boundaries of given s2 square
    
    Parameters
    ----------
    s2_address : string
        Unique s2 token
    geo_json : bool, optional
        If True, output coordinates is geo_json conformant (lng, lat)
        If False, coordinates are (lat, lng), by default False
    
    Returns
    -------
    list
        Geometry of given s2 square
    """

    cell = _token_to_cell(s2_address)

    return [
        _to_lonlat(LatLng.from_point(cell.get_vertex(i)))
        for i in [0, 1, 2, 3, 0]
    ] if geo_json_conformant else [
        _to_latlon(LatLng.from_point(cell.get_vertex(i)))
        for i in [0, 1, 2, 3]
    ]
示例#2
0
def neighbor_s2_circle(
        location,
        i_dir=0.0,
        j_dir=0.0):  # input location can be list, tuple or Point
    if type(location) in (list, tuple):
        ll_location = LatLng.from_degrees(location[0], location[1])
    elif type(location) is Point:
        ll_location = LatLng.from_point(location)
    elif type(location) is LatLng:
        ll_location = location
    else:
        return None

    cid_large = CellId.from_lat_lng(ll_location).parent(lvl_big)

    cid_small = cid_large.child_begin(lvl_small)
    vec_to_j = (Cell(ij_offs(cid_small, 0, 1)).get_center() -
                Cell(cid_small).get_center()).normalize()
    vec_to_i = (Cell(ij_offs(cid_small, 1, 0)).get_center() -
                Cell(cid_small).get_center()).normalize()

    vec_newlocation = ll_location.to_point() + safety * HEX_R / earth_Rrect * (
        i_dir * 3**0.5 * vec_to_i + j_dir * 1.5 * vec_to_j)

    return vec_newlocation  # output is Point
示例#3
0
    async def _send_weather_webhook(self, s2cellId, weatherId, severe, warn, day, time):
        if self.__application_args.weather_webhook:
            log.debug("Send Weather Webhook")

            cell = Cell(CellId(s2cellId))
            coords = []
            for v in range(0, 4):
                vertex = LatLng.from_point(cell.get_vertex(v))
                coords.append([vertex.lat().degrees, vertex.lng().degrees])

            data = weather_webhook_payload.format(s2cellId, coords, weatherId, severe, warn, day, time)

            log.debug(data)
            payload = json.loads(data)
            log.info("Sending weather webhook: %s" % str(payload))
            try:
                response = requests.post(
                    self.__application_args.webhook_url, data=json.dumps(payload),
                    headers={'Content-Type': 'application/json'},
                    timeout=5
                )
                if response.status_code != 200:
                    log.warning("Go status code other than 200 OK from webhook destination: %s" % str(response.status_code))
                else:
                    log.info("Success sending webhook")
            except Exception as e:
                log.warning("Exception occured while sending webhook: %s" % str(e))
        else:
            log.debug("Weather Webhook Disabled")
示例#4
0
    def locate_step(self, location):
        (lat, lon) = location
        origin = LatLng.from_degrees(lat, lon)
        parent = CellId.from_lat_lng(origin).parent(15)
        h = self.niantic.heartbit(location)
        hs = [h]

        for child in parent.children():
            latlng = LatLng.from_point(Cell(child).get_center())
            child_location = (latlng.lat().degrees, latlng.lng().degrees)
            hs.append(self.niantic.heartbit(child_location))

        visible = self.__parse_pokemons(hs)

        current_time_ms = int(round(time.time() * 1000))
        for poke in visible.values():
            pokeid = str(poke.pokemon.PokemonId)
            pokename = POKEMON_NAMES[pokeid]
            expires = poke.LastModifiedMs + poke.TimeTillHiddenMs

            self.data.pokemons[poke.SpawnPointId] = {
                "lat": poke.Latitude,
                "lng": poke.Longitude,
                "expires": expires,
                'expiresAfter': (expires - current_time_ms) / 1000,
                "id": poke.pokemon.PokemonId,
                "name": pokename
            }
        logger.debug('-- step {} {}: found {} pokemons, {} pokestops, {} gyms'.format(
            lat, lon,
            len(self.data.pokemons), len(self.data.pokestops), len(self.data.gyms)))
示例#5
0
    def writeplans():
        subplans = request.args.get('subplans', type=int)
        plans = []
        lock_plans.acquire()
        for token in list_plans:
            center = LatLng.from_point(
                Cell(CellId.from_token(token)).get_center())
            center = (center.lat().degrees, center.lng().degrees)
            for ind_sub in range(1, subplans + 1):
                plans.append({
                    'type': 'seikur0_s2',
                    'token': token,
                    'location': [center[0], center[1]],
                    'subplans': subplans,
                    'subplan_index': ind_sub
                })
        lock_plans.release()

        for plan in plans:
            filename = '{}_{}_{}.plan'.format(plan['token'],
                                              plan['subplan_index'],
                                              plan['subplans'])
            try:
                f = open(plandir + '/' + filename, 'w', 0)
                json.dump(plan, f, indent=1, separators=(',', ': '))
                print('[+] Plan file {} was written.'.format(filename))
            except Exception as e:
                print(
                    '[+] Error while writing plan file, error : {}'.format(e))
            finally:
                if 'f' in vars() and not f.closed:
                    f.close()

        return jsonify("")
示例#6
0
def main():
    origin_lat_i, origin_lng_i = f2i(origin_lat), f2i(origin_lng)
    api_endpoint, access_token, profile_response = login(origin_lat_i, origin_lng_i)

    with sqlite3.connect('database.db') as db:
        create_tables(db)

    while True:
        pos = 1
        x = 0
        y = 0
        dx = 0
        dy = -1
        steplimit2 = steplimit**2
        for step in range(steplimit2):
            #print('looping: step {} of {}'.format(step + 1, steplimit**2))
            # Scan location math
            if -steplimit2 / 2 < x <= steplimit2 / 2 and -steplimit2 / 2 < y <= steplimit2 / 2:
                step_lat = x * 0.0025 + origin_lat
                step_lng = y * 0.0025 + origin_lng
                step_lat_i = f2i(step_lat)
                step_lng_i = f2i(step_lng)
            if x == y or x < 0 and x == -y or x > 0 and x == 1 - y:
                (dx, dy) = (-dy, dx)

            (x, y) = (x + dx, y + dy)

            #print('[+] Searching for Pokemon at location {} {}'.format(step_lat, step_lng))
            origin = LatLng.from_degrees(step_lat, step_lng)
            parent = CellId.from_lat_lng(origin).parent(15)
            h = get_heartbeat(api_endpoint, access_token, profile_response, step_lat, step_lng, step_lat_i, step_lng_i)
            hs = [h]

            for child in parent.children():
                latlng = LatLng.from_point(Cell(child).get_center())
                child_lat, child_lng = latlng.lat().degrees, latlng.lng().degrees
                child_lat_i, child_lng_i = f2i(child_lat), f2i(child_lng)
                hs.append(get_heartbeat(api_endpoint, access_token, profile_response, child_lat, child_lng, child_lat_i, child_lng_i))
            visible = []

            data = []
            for hh in hs:
                for cell in hh.cells:
                    for poke in cell.WildPokemon:
                        disappear_ms = cell.AsOfTimeMs + poke.TimeTillHiddenMs
                        data.append((
                            poke.SpawnPointId,
                            poke.pokemon.PokemonId,
                            poke.Latitude,
                            poke.Longitude,
                            disappear_ms,
                        ))
            if data:
                print('Upserting {} pokemon'.format(len(data)))
                with sqlite3.connect('database.db') as db:
                    insert_data(db, data)
示例#7
0
 def add_plan():
     location = (request.args.get('lat', type=float),request.args.get('lng', type=float))
     all_loc,border,cid = mapl.get_area_cell(location,True)
     # grid = mapl.Hexgrid()
     # all_loc = grid.cover_cell(cid)
     center = LatLng.from_point(Cell(cid).get_center())
     center = (center.lat().degrees, center.lng().degrees)
     token = cid.to_token()
     lock_plans.acquire()
     list_plans.append(token)
     lock_plans.release()
     return jsonify((all_loc, border,[center,token],[]))
示例#8
0
 def add_plan():
     location = (request.args.get('lat', type=float),
                 request.args.get('lng', type=float))
     all_loc, border, cid = mapl.get_area_cell(location, True)
     # grid = mapl.Hexgrid()
     # all_loc = grid.cover_cell(cid)
     center = LatLng.from_point(Cell(cid).get_center())
     center = (center.lat().degrees, center.lng().degrees)
     token = cid.to_token()
     lock_plans.acquire()
     list_plans.append(token)
     lock_plans.release()
     return jsonify((all_loc, border, [center, token], []))
示例#9
0
def get_area_cell(location, unfilled=False):
    border = []
    locs = []

    cid_large = CellId.from_lat_lng(
        LatLng.from_degrees(location[0], location[1])).parent(lvl_big)
    border.append(get_border_cell(cid_large))

    if unfilled:
        return [], border, cid_large

    corner = neighbor_s2_circle(
        LatLng.from_degrees(border[-1][0][0], border[-1][0][1]),
        safety_border * 0.5, safety_border / 3.0)
    j_maxpoint = LatLng.from_point(
        neighbor_s2_circle(
            LatLng.from_degrees(border[-1][1][0], border[-1][1][1]),
            safety_border * 0.5, (1 - safety_border) / 3.0))
    i_maxpoint = LatLng.from_point(
        neighbor_s2_circle(
            LatLng.from_degrees(border[-1][3][0], border[-1][3][1]),
            (1 - safety_border) * 0.5, safety_border / 3.0))

    base = corner
    p_start = base

    dist_j = j_maxpoint.get_distance(LatLng.from_point(p_start))
    last_dist_j = None
    j = 0
    while last_dist_j is None or dist_j < last_dist_j:
        dist_i = i_maxpoint.get_distance(LatLng.from_point(p_start))
        last_dist_i = None
        while last_dist_i is None or dist_i < last_dist_i:
            locs.append(LatLng.from_point(p_start))
            p_start = neighbor_s2_circle(p_start, 1.0, 0.0)
            last_dist_i = dist_i
            dist_i = i_maxpoint.get_distance(LatLng.from_point(p_start))
        base = neighbor_s2_circle(base, 0.0, 1.0)
        last_dist_j = dist_j
        dist_j = j_maxpoint.get_distance(LatLng.from_point(base))
        if j % 2 == 1:
            p_start = base
        else:
            p_start = neighbor_s2_circle(base, -0.5, 0.0)
        j += 1

    all_loc = []
    for loc in locs:
        all_loc.append([loc.lat().degrees, loc.lng().degrees])

    return all_loc, border, cid_large
示例#10
0
文件: s2.py 项目: JoaoCarabetta/s2-py
def s2_to_geo(s2_address):
    """Get geometry from s2 token
    
    Parameters
    ----------
    s2_address : string
        s2 unique token
    
    Returns
    -------
    list
        Geometry of s2 square
    """
    cell = _token_to_cell(s2_address)

    return _to_latlon(LatLng.from_point(cell.get_center()))
示例#11
0
def neighbor_s2_circle(location, i_dir=0.0, j_dir=0.0):  # input location can be list, tuple or Point
    if type(location) in (list, tuple):
        ll_location = LatLng.from_degrees(location[0], location[1])
    elif type(location) is Point:
        ll_location = LatLng.from_point(location)
    elif type(location) is LatLng:
        ll_location = location
    else:
        return None

    cid_large = CellId.from_lat_lng(ll_location).parent(lvl_big)

    cid_small = cid_large.child_begin(lvl_small)
    vec_to_j = (Cell(ij_offs(cid_small, 0, 1)).get_center() - Cell(cid_small).get_center()).normalize()
    vec_to_i = (Cell(ij_offs(cid_small, 1, 0)).get_center() - Cell(cid_small).get_center()).normalize()

    vec_newlocation = ll_location.to_point() + safety * HEX_R / earth_Rrect * (i_dir * 3 ** 0.5 * vec_to_i + j_dir * 1.5 * vec_to_j)

    return vec_newlocation  # output is Point
示例#12
0
    async def _send_weather_webhook(self, s2cellId, weatherId, severe, warn,
                                    day, time):
        if self.__application_args.weather_webhook:
            log.debug("Send Weather Webhook")

            cell = Cell(CellId(s2cellId))
            coords = []
            for v in range(0, 4):
                vertex = LatLng.from_point(cell.get_vertex(v))
                coords.append([vertex.lat().degrees, vertex.lng().degrees])

            data = weather_webhook_payload.format(s2cellId, coords, weatherId,
                                                  severe, warn, day, time)

            log.debug(data)
            payload = json.loads(data)
            self.__sendToWebhook(payload)
        else:
            log.debug("Weather Webhook Disabled")
示例#13
0
    def get_meta_cell(self):
        location = self.position[0:2]
        cells = self.find_close_cells(*location)

        # Combine all cells into a single dict of the items we care about.
        forts = []
        wild_pokemons = []
        catchable_pokemons = []
        nearby_pokemons = []
        for cell in cells:
            if "forts" in cell and len(cell["forts"]):
                forts += cell["forts"]
            if "wild_pokemons" in cell and len(cell["wild_pokemons"]):
                wild_pokemons += cell["wild_pokemons"]
            if "catchable_pokemons" in cell and len(cell["catchable_pokemons"]):
                catchable_pokemons += cell["catchable_pokemons"]
            if "nearby_pokemons" in cell and len(cell["nearby_pokemons"]):
                latlng = LatLng.from_point(Cell(CellId(cell["s2_cell_id"])).get_center())

                for p in cell["nearby_pokemons"]:
                    p["latitude"] = latlng.lat().degrees
                    p["longitude"] = latlng.lng().degrees
                    p["s2_cell_id"] = cell["s2_cell_id"]

                nearby_pokemons += cell["nearby_pokemons"]

        # If there are forts present in the cells sent from the server or we don't yet have any cell data, return all data retrieved
        if len(forts) > 1 or not self.cell:
            return {
                "forts": forts,
                "wild_pokemons": wild_pokemons,
                "catchable_pokemons": catchable_pokemons,
                "nearby_pokemons": nearby_pokemons
            }
        # If there are no forts present in the data from the server, keep our existing fort data and only update the pokemon cells.
        else:
            return {
                "forts": self.cell["forts"],
                "wild_pokemons": wild_pokemons,
                "catchable_pokemons": catchable_pokemons,
                "nearby_pokemons": nearby_pokemons
            }
示例#14
0
def send_weather_webhook(s2cellId, weatherId, severe, warn, day, time):
    if args.weather_webhook:
        log.debug("Send Weather Webhook")

        cell = Cell(CellId(s2cellId))
        coords = []
        for v in range(0, 4):
            vertex = LatLng.from_point(cell.get_vertex(v))
            coords.append([vertex.lat().degrees, vertex.lng().degrees])

        data = weather_webhook_payload.format(s2cellId, coords, weatherId,
                                              severe, warn, day, time)

        log.debug(data)
        payload = json.loads(data)
        response = requests.post(args.webhook_url,
                                 data=json.dumps(payload),
                                 headers={'Content-Type': 'application/json'})
    else:
        log.debug("Weather Webhook Disabled")
示例#15
0
    def get_search_points(self, cell_id):
        points = []

        # For cell level 15
        for c in Cell(CellId(cell_id)).subdivide():
            for cc in c.subdivide():
                latlng = LatLng.from_point(cc.get_center())
                point = (latlng.lat().degrees, latlng.lng().degrees)
                points.append(point)

        points[0], points[1] = points[1], points[0]
        points[14], points[15] = points[15], points[14]
        point = points.pop(2)
        points.insert(7, point)
        point = points.pop(13)
        points.insert(8, point)

        closest = min(points, key=lambda p: great_circle(self.bot.position, p).meters)
        index = points.index(closest)

        return points[index:] + points[:index]
示例#16
0
    def get_search_points(self, cell_id):
        points = []

        # For cell level 15
        for c in Cell(CellId(cell_id)).subdivide():
            for cc in c.subdivide():
                latlng = LatLng.from_point(cc.get_center())
                point = (latlng.lat().degrees, latlng.lng().degrees)
                points.append(point)

        points[0], points[1] = points[1], points[0]
        points[14], points[15] = points[15], points[14]
        point = points.pop(2)
        points.insert(7, point)
        point = points.pop(13)
        points.insert(8, point)

        closest = min(points, key=lambda p: great_circle(self.bot.position, p).meters)
        index = points.index(closest)

        return points[index:] + points[:index]
示例#17
0
def get_area_cell(location,unfilled=False):
    border = []
    locs = []

    cid_large = CellId.from_lat_lng(LatLng.from_degrees(location[0], location[1])).parent(lvl_big)
    border.append(get_border_cell(cid_large))

    if unfilled:
        return [], border, cid_large

    corner = neighbor_s2_circle(LatLng.from_degrees(border[-1][0][0], border[-1][0][1]), safety_border*0.5, safety_border/3.0)
    j_maxpoint = LatLng.from_point(neighbor_s2_circle(LatLng.from_degrees(border[-1][1][0], border[-1][1][1]), safety_border*0.5, (1-safety_border)/3.0))
    i_maxpoint = LatLng.from_point(neighbor_s2_circle(LatLng.from_degrees(border[-1][3][0], border[-1][3][1]), (1-safety_border)*0.5, safety_border/3.0))

    base = corner
    p_start = base

    dist_j = j_maxpoint.get_distance(LatLng.from_point(p_start))
    last_dist_j = None
    j = 0
    while last_dist_j is None or dist_j < last_dist_j:
        dist_i = i_maxpoint.get_distance(LatLng.from_point(p_start))
        last_dist_i = None
        while last_dist_i is None or dist_i < last_dist_i:
            locs.append(LatLng.from_point(p_start))
            p_start = neighbor_s2_circle(p_start, 1.0, 0.0)
            last_dist_i = dist_i
            dist_i = i_maxpoint.get_distance(LatLng.from_point(p_start))
        base = neighbor_s2_circle(base, 0.0, 1.0)
        last_dist_j = dist_j
        dist_j = j_maxpoint.get_distance(LatLng.from_point(base))
        if j % 2 == 1:
            p_start = base
        else:
            p_start = neighbor_s2_circle(base, -0.5, 0.0)
        j += 1

    all_loc = []
    for loc in locs:
        all_loc.append([loc.lat().degrees, loc.lng().degrees])

    return all_loc, border,cid_large
示例#18
0
    def writeplans():
        subplans = request.args.get('subplans', type=int)
        plans = []
        lock_plans.acquire()
        for token in list_plans:
            center = LatLng.from_point(Cell(CellId.from_token(token)).get_center())
            center = (center.lat().degrees, center.lng().degrees)
            for ind_sub in range(1,subplans+1):
                plans.append({'type': 'seikur0_s2', 'token': token, 'location': [center[0],center[1]], 'subplans': subplans, 'subplan_index': ind_sub})
        lock_plans.release()

        for plan in plans:
            filename = '{}_{}_{}.plan'.format(plan['token'],plan['subplan_index'],plan['subplans'])
            try:
                f = open(plandir+'/'+filename, 'w', 0)
                json.dump(plan, f, indent=1, separators=(',', ': '))
                print('[+] Plan file {} was written.'.format(filename))
            except Exception as e:
                print('[+] Error while writing plan file, error : {}'.format(e))
            finally:
                if 'f' in vars() and not f.closed:
                    f.close()

        return jsonify("")
示例#19
0
def get_cell_edge(cell, edge=0):
    
    cell_edge = LatLng.from_point(cell.get_vertex(edge))
    
    return cell_edge
示例#20
0
def get_vertex(cell, v):
    vertex = LatLng.from_point(cell.get_vertex(v))
    return (vertex.lat().degrees, vertex.lng().degrees)