def get_captured_lat_lng(pokemon): lat, lng = 0, 0 if pokemon.get('captured_cell_id'): cell = CellId(pokemon.get('captured_cell_id')) lat, lng = cell.to_lat_lng().lat().degrees, cell.to_lat_lng().lng( ).degrees return {'lat': lat, 'lng': lng}
def post(self): log.msg("Got the TestKariosHandler req") from_tm = 0 to_tm = 0 #loc = [] topic = "location" try: from_tm = self.request.arguments['start_time'] to_tm = self.request.arguments['end_time'] except Exception: log.msg("No time given, will give all location") if (from_tm != 0 and to_tm != 0): loc = self.get_data.kdb_get_data(topic, from_tm, to_tm) else: log.msg("inside else") r = yield self.conn.read_absolute(self, ["location"], 0) length = r['queries'][0]['sample_size'] if length: if (length > 100): n = 100 else: n = length res = r['queries'][0]['results'][0]['values'] for i in range(0, n): val = CellId(res[i][1]) lat = val.to_lat_lng().lat().degrees longt = val.to_lat_lng().lng().degrees tm = res[i][0] / 1000 v = {"latitude": lat, "longitude": longt, "timestamp": tm} loc.append(v) data = loc self.write({"resp_code": True, "location": loc})
def test_get_linestring_with_s2_cellids(): from_point = CellId(5221390681063996525) to_point = CellId(5221390693823388667) ls = utils.get_linestring(from_point, to_point) assert isinstance(ls, LineString) assert [(round(c[0], 6), round(c[1], 6)) for c in ls.coords] == [(-0.137925, 51.521699), (-0.134456, 51.520027)]
def sub_cell(cell,i=0,dist=25): g = Geodesic.WGS84 # @UndefinedVariable olat = CellId.to_lat_lng(cell).lat().degrees olng = CellId.to_lat_lng(cell).lng().degrees p = g.Direct(olat, olng,(45+(90*i)),dist) c = CellId.from_lat_lng(LatLng.from_degrees(p['lat2'],p['lon2'])) return c.parent(cell.level()+1)
def kdb_get_data(self, topic, from_tm, to_tm): loc = [] result = [] temp = 0 j = k = 0 max_speed = 0 avg_speed = 0 dist = 0 if (from_tm != 0): r = yield self.conn.read_absolute(self, [topic], from_tm, to_tm) length = r['queries'][0]['sample_size'] if length: res = r['queries'][0]['results'][0]['values'] for rs in res: val = CellId(rs[1]) lat = val.to_lat_lng().lat().degrees longt = val.to_lat_lng().lng().degrees tm = rs[0] / 1000 v = { "latitude": lat, "longitude": longt, "timestamp": tm, "speed": 0, 'distance': -1 } loc.append(v) es = r['queries'][0]['results'][0]['tags']['speed'] if len(es): for x in es: x = float(x) loc[j]['speed'] = x j = j + 1 temp = temp + x max_speed = max(es) avg_speed = temp / len(es) avg_speed = float(format(avg_speed, '.2f')) result.append(avg_speed) result.append(float(max_speed)) try: ds = r['queries'][0]['results'][0]['tags']['distance'] if len(ds): for x in ds: x = float(x) dist = dist + x k = k + 1 if (dist == 0.0): continue loc[k]['distance'] = dist except Exception, e: log.msg("No distance recorded in DB for this vehicle") result.append(loc) data = result else: data = "NULL"
def get_sub_cells(self, cellid, level=1): sub_cells = [] start = CellId(id_=cellid).child_begin() end = CellId(id_=cellid).child_end() while (start.id() < end.id()): if level == 1: sub_cells.append(start.id()) else: sub_cells += self.get_sub_cells(start.id(), level - 1) start = start.next() return sub_cells
def _get_cell_id_from_latlong(self, radius=1000): # type: (Optional[int]) -> List[str] position_lat, position_lng, _ = self.api_wrapper.get_position() cells = get_cell_ids(position_lat, position_lng, radius) if self.config['debug']: self._log('Cells:', color='yellow') self._log('Origin: {},{}'.format(position_lat, position_lng), color='yellow') for cell in cells: cell_id = CellId(cell) lat_lng = cell_id.to_lat_lng() self._log('Cell : {},{}'.format(lat_lng.lat().degrees, lat_lng.lng().degrees), color='yellow') return cells
def kdb_get_data(self, topic, from_tm, to_tm): loc = [] r = yield self.conn.read_absolute(self, [topic], from_tm, to_tm) log.msg("test_read_absolute_without_tags: ", r) length = r['queries'][0]['sample_size'] if length: res = r['queries'][0]['results'][0]['values'] for rs in res: val = CellId(rs[1]) lat = val.to_lat_lng().lat().degrees longt = val.to_lat_lng().lng().degrees tm = rs[0] / 1000 v = {"latitude": lat, "longitude": longt, "timestamp": tm} loc.append(v) returnValue(loc)
def load(cell_id): if cell_id.parent(10).to_token() in lv10: return try: data = np.load( f"data/{cell_id.parent(5).to_token()}/{cell_id.parent(10).to_token()}.npy" ) except: return lv10.append(cell_id.parent(10).to_token()) for i in range(len(data)): pos[data[i]['cellid']] = (data[i]['lat'], data[i]['lng']) cell_id = CellId.from_token(data[i]['cellid']) p_16 = cell_id.parent(16).to_token() if p_16 not in lv16.keys(): lv16[p_16] = [] lv16[p_16].append(data[i]) p_15 = cell_id.parent(15).to_token() if p_15 not in lv15.keys(): lv15[p_15] = [] lv15[p_15].append(data[i]) p_14 = cell_id.parent(14).to_token() if p_14 not in lv14.keys(): lv14[p_14] = [] lv14[p_14].append(data[i]) global portals portals = np.concatenate((portals, data))
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
def getCells(self, radius=10, bothDirections=True): origin = CellId.from_lat_lng( LatLng.from_degrees( self.latitude, self.longitude ) ).parent(15) # Create walk around area walk = [origin.id()] right = origin.next() left = origin.prev() # Double the radius if we're only walking one way if not bothDirections: radius *= 2 # Search around provided radius for _ in range(radius): walk.append(right.id()) right = right.next() if bothDirections: walk.append(left.id()) left = left.prev() # Return everything return sorted(walk)
def getLatLongIndex(latitude, longitude): return CellId.from_lat_lng( LatLng.from_degrees( latitude, longitude ) ).id()
def getCellId(self): return CellId.from_lat_lng( LatLng.from_degrees( self.latitude, self.longitude ) ).parent(15)
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)))
def makeWildPokemon(location): # Cause the randomness to only shift every N minutes (thus new pokes every N minutes) offset = int(time() % 3600) / 10 seedid = str(location[0]) + str(location[1]) + str(offset) seed(seedid) # Now, collect the pokes for this can point pokes = [] for i in range(randint(0, 2)): coords = getRandomPoint(location) ll = LatLng.from_degrees(coords[0], coords[1]) cellId = CellId.from_lat_lng(ll).parent(20).to_token() pokes.append({ 'encounter_id': 'pkm' + seedid + str(i), 'last_modified_timestamp_ms': int((time() - 10) * 1000), 'latitude': coords[0], 'longitude': coords[1], 'pokemon_data': { 'pokemon_id': randint(1, 140), 'iv_attack': 999999 }, 'spawn_point_id': cellId, 'time_till_hidden_ms': randint(60, 600) * 1000 }) return pokes
def gen_csv_counted(filename, dbfile): dbin = sqlite3.connect(dbfile) dbout = sqlite3.connect(':memory:'); dbcur = dbout.cursor() dbcur.execute("CREATE TABLE encount (spawn VARCHAR, poke INT, count INT DEFAULT 0, \ PRIMARY KEY (spawn, poke) )") for i in range(151): encs = [x[0] for x in dbin.cursor().execute("SELECT spawn_id FROM encounters " "WHERE spawn_id IS NOT NULL AND pokemon_id = %d" % i).fetchall()] if len(encs) > 0: for e in encs: dbcur.execute("INSERT OR IGNORE INTO encount (spawn, poke) VALUES ('{}',{})".format(e,i)) dbcur.execute("UPDATE encount SET count = count + 1 WHERE spawn = '%s' AND poke = %d" % (e,i)) dbout.commit() f = open(filename,'w') pname = get_pokenames('pokes.txt') f.write('spawn_id, latitude, longitude, count, pokemon_id, pokemon_name\n') spwns = dbout.execute("SELECT spawn, poke, count FROM encount ORDER BY poke ASC, count DESC").fetchall() if len(spwns) > 0: for s,p,c in spwns: _ll = CellId.from_token(s).to_lat_lng() lat, lng, = _ll.lat().degrees, _ll.lng().degrees f.write("{},{},{},{},{},{}\n".format(s,lat,lng,c,p,pname[p])) print('Done!')
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("")
def getNeighbors(location): level = 15 origin = CellId.from_lat_lng(LatLng.from_degrees(location[0], location[1])).parent(level) max_size = 1 << 30 size = origin.get_size_ij(level) face, i, j = origin.to_face_ij_orientation()[0:3] walk = [origin.id(), origin.from_face_ij_same(face, i, j - size, j - size >= 0).parent(level).id(), origin.from_face_ij_same(face, i, j + size, j + size < max_size).parent(level).id(), origin.from_face_ij_same(face, i - size, j, i - size >= 0).parent(level).id(), origin.from_face_ij_same(face, i + size, j, i + size < max_size).parent(level).id(), origin.from_face_ij_same(face, i - size, j - size, j - size >= 0 and i - size >= 0).parent(level).id(), origin.from_face_ij_same(face, i + size, j - size, j - size >= 0 and i + size < max_size).parent(level).id(), origin.from_face_ij_same(face, i - size, j + size, j + size < max_size and i - size >= 0).parent(level).id(), origin.from_face_ij_same(face, i + size, j + size, j + size < max_size and i + size < max_size).parent(level).id()] #origin.from_face_ij_same(face, i, j - 2*size, j - 2*size >= 0).parent(level).id(), #origin.from_face_ij_same(face, i - size, j - 2*size, j - 2*size >= 0 and i - size >=0).parent(level).id(), #origin.from_face_ij_same(face, i + size, j - 2*size, j - 2*size >= 0 and i + size < max_size).parent(level).id(), #origin.from_face_ij_same(face, i, j + 2*size, j + 2*size < max_size).parent(level).id(), #origin.from_face_ij_same(face, i - size, j + 2*size, j + 2*size < max_size and i - size >=0).parent(level).id(), #origin.from_face_ij_same(face, i + size, j + 2*size, j + 2*size < max_size and i + size < max_size).parent(level).id(), #origin.from_face_ij_same(face, i + 2*size, j, i + 2*size < max_size).parent(level).id(), #origin.from_face_ij_same(face, i + 2*size, j - size, j - size >= 0 and i + 2*size < max_size).parent(level).id(), #origin.from_face_ij_same(face, i + 2*size, j + size, j + size < max_size and i + 2*size < max_size).parent(level).id(), #origin.from_face_ij_same(face, i - 2*size, j, i - 2*size >= 0).parent(level).id(), #origin.from_face_ij_same(face, i - 2*size, j - size, j - size >= 0 and i - 2*size >=0).parent(level).id(), #origin.from_face_ij_same(face, i - 2*size, j + size, j + size < max_size and i - 2*size >=0).parent(level).id()] return walk
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")
def get_s2_cell_center(lat, lng, level): lat_lng = LatLng.from_degrees(lat, lng) cell_id = CellId.from_lat_lng(lat_lng).parent(level) center = cell_id.to_lat_lng() return { 'lat': float(center.lat().degrees), 'lon': float(center.lng().degrees) }
def update_missing_s2_ids(): log.info("Looking for spawn points with missing s2 coordinates") for spawnpoint in db_load_spawn_points_missing_s2(): latlng = LatLng.from_degrees(spawnpoint["latitude"], spawnpoint["longitude"]) cell = CellId.from_lat_lng(latlng).parent(15) db_set_s2_cellid(spawnpoint["id"], cell.id()) log.info("Done establishing s2 points")
def get_cellid_center_coordinate(self, cellid): """ get one cell's center point's coordinate [longitude, latitude] :param cellid: lnglat_to_cellid生成的cellid :return:tuple(center_longitude, center_latitude) """ center = Cell(cell_id=CellId(cellid)).get_center() return (LatLng.longitude(center).degrees, LatLng.latitude(center).degrees)
def gen_que(ndbfile, fdbfile): if not os.path.isfile(fdbfile): log.critical('Fastmap DB missing!!') log.info('Run bootstrap.py!') return False db = sqlite3.connect(ndbfile) dbtmp = sqlite3.connect(':memory:') dbtmp.cursor().execute("CREATE TABLE queque (\ cell VARCHAR PRIMARY KEY,\ count INT DEFAULT (0) )") # tiling up spawns = [x[0] for x in sqlite3.connect(fdbfile).cursor()\ .execute("SELECT spawn_id FROM 'spawns' ORDER BY spawn_id").fetchall()] for spawn in spawns: cellid = CellId.from_token(spawn).parent(14).to_token() dbtmp.cursor().execute( "INSERT OR IGNORE INTO queque (cell) VALUES ('{}')".format(cellid)) dbtmp.cursor().execute( "UPDATE queque SET count = count + 1 WHERE cell = '{}'".format( cellid)) # tiling down cells = [x[0] for x in dbtmp.cursor()\ .execute("SELECT cell FROM 'queque' ORDER BY count DESC").fetchall()] dbtmp.close() del dbtmp db.cursor().execute("DELETE FROM _queue") for cell in cells: subcells = sub_cells(CellId.from_token(cell)) for subcell in subcells: db.cursor().execute( "INSERT OR IGNORE INTO _queue (cell_id) VALUES ('{}')".format( subcell.to_token())) db.cursor().execute("VACUUM") db.commit() log.info('Scan queue generated.') return True
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)
def remove_plan(): location = (request.args.get('lat', type=float), request.args.get('lng', type=float)) cid = CellId.from_lat_lng(LatLng.from_degrees(location[0],location[1])).parent(mapl.lvl_big) token = cid.to_token() lock_plans.acquire() if token in list_plans: list_plans.pop(list_plans.index(token)) lock_plans.release() return jsonify("")
def get_cell_walk(lat, lng, radius, level=15): origin = CellId.from_lat_lng(LatLng.from_degrees(lat, lng)).parent(level) walk = [origin] right = origin.next() left = origin.prev() for dummy in range(radius): walk.append(right) walk.append(left) right = right.next() left = left.prev() return sorted(walk)
def getPortals(cell): ret = [] try: for p in np.load( f"data/{cell.parent(5).to_token()}/{cell.parent(10).to_token()}.npy" ): if cell.contains(CellId.from_token(p['cellid'])): ret.append(p) except: pass return ret
async def _send_weather_webhook(self, s2cellId, weatherId, severe, warn, day, time): if self.__application_args.weather_webhook: log.debug("Send Weather Webhook") ll = CellId(s2cellId).to_lat_lng() latitude = ll.lat().degrees longitude = ll.lng().degrees 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, latitude, longitude) log.debug(data) payload = json.loads(data) self.__sendToWebhook(payload) else: log.debug("Weather Webhook Disabled")
def remove_plan(): location = (request.args.get('lat', type=float), request.args.get('lng', type=float)) cid = CellId.from_lat_lng(LatLng.from_degrees( location[0], location[1])).parent(mapl.lvl_big) token = cid.to_token() lock_plans.acquire() if token in list_plans: list_plans.pop(list_plans.index(token)) lock_plans.release() return jsonify("")
def get_cellid(lat, long): origin = CellId.from_lat_lng(LatLng.from_degrees(lat, long)).parent(15) walk = [origin.id()] next = origin.next() prev = origin.prev() for i in range(10): walk.append(prev.id()) walk.append(next.id()) next = next.next() prev = prev.prev() return sorted(walk)
def get_neighbors(lat, lon): origin = CellId.from_lat_lng(LatLng.from_degrees(lat, lon)).parent(15) walk = [origin.id()] next = origin.next() prev = origin.prev() for i in range(10): walk.append(prev.id()) walk.append(next.id()) next = next.next() prev = prev.prev() return walk
def _get_cellid(self, lat, long, radius=10): origin = CellId.from_lat_lng(LatLng.from_degrees(lat, long)).parent(15) walk = [origin.id()] # 10 before and 10 after next = origin.next() prev = origin.prev() for i in range(radius): walk.append(prev.id()) walk.append(next.id()) next = next.next() prev = prev.prev() return sorted(walk)
def get_neighbors(lat, lng): origin = CellId.from_lat_lng(LatLng.from_degrees(lat, lng)).parent(15) walk = [origin.id()] # 10 before and 10 after next = origin.next() prev = origin.prev() for i in range(10): walk.append(prev.id()) walk.append(next.id()) next = next.next() prev = prev.prev() return walk
def get_cellid(lat, lng, level=15): origin = CellId.from_lat_lng(LatLng.from_degrees(lat, lng)).parent(level) walk = [origin.id()] # 10 before and 10 after next = origin.next() prev = origin.prev() for i in range(10): walk.append(prev.id()) walk.append(next.id()) next = next.next() prev = prev.prev() return sorted(walk)
def cell_spiral(lat, lng, dist, level=15, step=100, res=3.6): cells = [] g = Geodesic.WGS84 # @UndefinedVariable for i in xrange(0, dist, step): for rad in xrange(int(360 / res)): p = g.Direct(lat, lng, rad * res, i) c = CellId.from_lat_lng(LatLng.from_degrees(p['lat2'], p['lon2'])) c = c.parent(level) if c not in cells: cells.append(c) return cells
def cell_spiral(lat, lng, dist, level=15, step=100, res=3.6): cells = [] g = Geodesic.WGS84 # @UndefinedVariable for i in xrange(0,dist,step): for rad in xrange(int(360/res)): p = g.Direct(lat, lng, rad*res, i) c = CellId.from_lat_lng(LatLng.from_degrees(p['lat2'],p['lon2'])) c = c.parent(level) if c not in cells: cells.append(c) return cells
def get_cellid(lat, long): origin = CellId.from_lat_lng(LatLng.from_degrees(lat, long)).parent(15) walk = [origin.id()] # 10 before and 10 after next = origin.next() prev = origin.prev() for i in range(10): walk.append(prev.id()) walk.append(next.id()) next = next.next() prev = prev.prev() return ''.join(map(encode, sorted(walk)))
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
def _get_cell_id_from_latlong(self, radius=10): position_lat, position_lng, _ = self.api.get_position() origin = CellId.from_lat_lng(LatLng.from_degrees(i2f(position_lat), i2f(position_lng))).parent(15) walk = [origin.id()] # 10 before and 10 after next_cell = origin.next() prev_cell = origin.prev() for _ in range(radius): walk.append(prev_cell.id()) walk.append(next_cell.id()) next_cell = next_cell.next() prev_cell = prev_cell.prev() return sorted(walk)
def get_cell_ids(lat, long, radius = 10): origin = CellId.from_lat_lng(LatLng.from_degrees(lat, long)).parent(15) walk = [origin.id()] right = origin.next() left = origin.prev() # Search around provided radius for i in range(radius): walk.append(right.id()) walk.append(left.id()) right = right.next() left = left.prev() # Return everything return sorted(walk)
def cover_cell(self, cid): lats = [] lngs = [] output = [] s2_cell = Cell(cid) lvl = s2_cell.level() for i in [0, 1]: for j in [0, 1]: lats.append(s2_cell.get_latitude(i, j)/pi*180) lngs.append(s2_cell.get_longitude(i, j)/pi*180) locations = self.cover_region((min(lats),min(lngs)),(max(lats),max(lngs))) for location in locations: testid = CellId.from_lat_lng(LatLng.from_degrees(location[0],location[1])).parent(lvl) if testid == cid: output.append(location) return output
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
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
def getCells(self, radius=10): origin = CellId.from_lat_lng( LatLng.from_degrees( self.latitude, self.longitude ) ).parent(15) # Create walk around area walk = [origin.id()] right = origin.next() left = origin.prev() # Search around provided radius for _ in range(radius): walk.append(right.id()) walk.append(left.id()) right = right.next() left = left.prev() # Return everything return sorted(walk)
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("")
def makeWildPokemon(location): # Cause the randomness to only shift every N minutes (thus new pokes every N minutes) offset = int(time() % 3600) / 10 seedid = str(location[0]) + str(location[1]) + str(offset) seed(seedid) # Now, collect the pokes for this can point pokes = [] for i in range(randint(0, 2)): coords = getRandomPoint(location) ll = LatLng.from_degrees(coords[0], coords[1]) cellId = CellId.from_lat_lng(ll).parent(20).to_token() pokes.append( { "encounter_id": "pkm" + seedid + str(i), "last_modified_timestamp_ms": int((time() - 10) * 1000), "latitude": coords[0], "longitude": coords[1], "pokemon_data": {"pokemon_id": randint(1, 140)}, "spawn_point_id": cellId, "time_till_hidden_ms": randint(60, 600) * 1000, } ) return pokes
def doScan(wid, sLat, sLng, api): #print ('scanning ({}, {})'.format(sLat, sLng)) api.set_position(sLat,sLng,0) cell_ids = util.get_cell_ids(lat=sLat, long=sLng, radius=80) timestamps = [0,] * len(cell_ids) while True: try: response_dict = api.get_map_objects(latitude = sLat, longitude = sLng, since_timestamp_ms = timestamps, cell_id = cell_ids) except ServerSideRequestThrottlingException: config['scanDelay'] += 0.5 print ('Request throttled, increasing sleep by 0.5 to {}').format(config['scanDelay']) time.sleep(config['scanDelay']) continue except: time.sleep(config['scanDelay']) api.set_position(sLat,sLng,0) time.sleep(config['scanDelay']) continue break try: cells = response_dict['responses']['GET_MAP_OBJECTS']['map_cells'] except TypeError: print ('thread {} error getting map data for {}, {}'.format(wid,sLat, sLng)) raise except KeyError: print ('thread {} error getting map data for {}, {}'.format(wid,sLat, sLng)) raise return for cell in cells: curTime = cell['current_timestamp_ms'] if 'wild_pokemons' in cell: for wild in cell['wild_pokemons']: if wild['time_till_hidden_ms']>0: timeSpawn = (curTime+(wild['time_till_hidden_ms']))-900000 gmSpawn = time.gmtime(int(timeSpawn/1000)) secSpawn = (gmSpawn.tm_min*60)+(gmSpawn.tm_sec) phash = '{},{}'.format(timeSpawn,wild['spawn_point_id']) shash = '{},{}'.format(secSpawn,wild['spawn_point_id']) pokeLog = {'time':timeSpawn, 'sid':wild['spawn_point_id'], 'lat':wild['latitude'], 'lng':wild['longitude'], 'pid':wild['pokemon_data']['pokemon_id'], 'cell':CellId.from_lat_lng(LatLng.from_degrees(wild['latitude'], wild['longitude'])).to_token()} spawnLog = {'time':secSpawn, 'sid':wild['spawn_point_id'], 'lat':wild['latitude'], 'lng':wild['longitude'], 'cell':CellId.from_lat_lng(LatLng.from_degrees(wild['latitude'], wild['longitude'])).to_token()} pokes[phash] = pokeLog spawns[shash] = spawnLog if 'forts' in cell: for fort in cell['forts']: if fort['enabled'] == True: if 'type' in fort: #got a pokestop stopLog = {'id':fort['id'],'lat':fort['latitude'],'lng':fort['longitude'],'lure':-1} if 'lure_info' in fort: stopLog['lure'] = fort['lure_info']['lure_expires_timestamp_ms'] stops[fort['id']] = stopLog if 'gym_points' in fort: gymLog = {'id':fort['id'],'lat':fort['latitude'],'lng':fort['longitude'],'team':0} if 'owned_by_team' in fort: gymLog['team'] = fort['owned_by_team'] gyms[fort['id']] = gymLog time.sleep(config['scanDelay'])
def safe_implementation(level=5): for c in CellId.walk(level): pass
try: cells = response_dict['responses']['GET_MAP_OBJECTS']['map_cells'] except TypeError, KeyError: print ('error getting map data for {}, {}'.format(sLat, sLng)) return for cell in cells: curTime = cell['current_timestamp_ms'] if 'wild_pokemons' in cell: for wild in cell['wild_pokemons']: if wild['time_till_hidden_ms']>0: timeSpawn = (curTime+(wild['time_till_hidden_ms']))-900000 gmSpawn = time.gmtime(int(timeSpawn/1000)) secSpawn = (gmSpawn.tm_min*60)+(gmSpawn.tm_sec) phash = '{},{}'.format(timeSpawn,wild['spawnpoint_id']) shash = '{},{}'.format(secSpawn,wild['spawnpoint_id']) pokeLog = {'time':timeSpawn, 'sid':wild['spawnpoint_id'], 'lat':wild['latitude'], 'lng':wild['longitude'], 'pid':wild['pokemon_data']['pokemon_id'], 'cell':CellId.from_lat_lng(LatLng.from_degrees(wild['latitude'], wild['longitude'])).to_token()} spawnLog = {'time':secSpawn, 'sid':wild['spawnpoint_id'], 'lat':wild['latitude'], 'lng':wild['longitude'], 'cell':CellId.from_lat_lng(LatLng.from_degrees(wild['latitude'], wild['longitude'])).to_token()} pokes[phash] = pokeLog spawns[shash] = spawnLog if 'forts' in cell: for fort in cell['forts']: if fort['enabled'] == True: if 'type' in fort: #got a pokestop stopLog = {'id':fort['id'],'lat':fort['latitude'],'lng':fort['longitude'],'lure':-1} if 'lure_info' in fort: stopLog['lure'] = fort['lure_info']['lure_expires_timestamp_ms'] stops[fort['id']] = stopLog if 'gym_points' in fort: gymLog = {'id':fort['id'],'lat':fort['latitude'],'lng':fort['longitude'],'team':0} if 'owned_by_team' in fort:
def default_walk(level=5): end = CellId.end(level) cell_id = CellId.begin(level) while cell_id != end: cell_id = cell_id.next()
def fast_implementation(level=5): for c in CellId.walk_fast(level): pass
def doScan(sLat, sLng, api): api.set_position(sLat, sLng, 0) cellids = get_cellid(sLat, sLng) api.get_map_objects( latitude=f2i(sLat), longitude=f2i(sLng), since_timestamp_ms=[TIMESTAMP] * len(cellids), cell_id=cellids ) response_dict = api.call() try: cells = response_dict['responses']['GET_MAP_OBJECTS']['map_cells'] except (TypeError, KeyError): print('error getting map data for {}, {}'.format(sLat, sLng)) return for cell in cells: # print(cell['s2_cell_id']) curTime = cell['current_timestamp_ms'] if 'wild_pokemons' in cell: for wild in cell['wild_pokemons']: if wild['time_till_hidden_ms'] > 0: timeSpawn = (curTime + (wild['time_till_hidden_ms'])) - 900000 gmSpawn = time.gmtime(int(timeSpawn / 1000)) secSpawn = (gmSpawn.tm_min * 60) + (gmSpawn.tm_sec) phash = '{},{}'.format(timeSpawn, wild['spawn_point_id']) shash = '{},{}'.format(secSpawn, wild['spawn_point_id']) pokeLog = { 'time': timeSpawn, 'sid': wild['spawn_point_id'], 'lat': wild['latitude'], 'lng': wild['longitude'], 'pid': wild['pokemon_data']['pokemon_id'], 'cell': CellId.from_lat_lng(LatLng.from_degrees(wild['latitude'], wild['longitude'])).to_token() } spawnLog = { 'time': secSpawn, 'sid': wild['spawn_point_id'], 'lat': wild['latitude'], 'lng': wild['longitude'], 'cell': CellId.from_lat_lng(LatLng.from_degrees(wild['latitude'], wild['longitude'])).to_token() } map_objects[POKES][phash] = pokeLog map_objects[SPAWNS][shash] = spawnLog if 'forts' in cell: for fort in cell['forts']: if fort['enabled']: if 'type' in fort: # Got a pokestop stopLog = { 'id': fort['id'], 'lat': fort['latitude'], 'lng': fort['longitude'], 'lure': -1 } if 'lure_info' in fort: stopLog['lure'] = fort['lure_info']['lure_expires_timestamp_ms'] map_objects[STOPS][fort['id']] = stopLog if 'gym_points' in fort: gymLog = { 'id': fort['id'], 'lat': fort['latitude'], 'lng': fort['longitude'], 'team': 0 } if 'owned_by_team' in fort: gymLog['team'] = fort['owned_by_team'] map_objects[GYMS][fort['id']] = gymLog