def _move_to_location(self): routemanager = self._get_currently_valid_routemanager() if routemanager is None: raise InternalStopWorkerException # get the distance from our current position (last) to the next gym (cur) distance = get_distance_of_two_points_in_meters(float(self.last_location.lat), float(self.last_location.lng), float(self.current_location.lat), float(self.current_location.lng)) log.info('main: Moving %s meters to the next position' % distance) speed = routemanager.settings.get("speed", 0) max_distance = routemanager.settings.get("max_distance", None) if (speed == 0 or (max_distance and 0 < max_distance < distance) or (self.last_location.lat == 0.0 and self.last_location.lng == 0.0)): log.info("main: Teleporting...") self._communicator.setLocation(self.current_location.lat, self.current_location.lng, 0) # cur_time = math.floor(time.time()) # the time we will take as a starting point to wait for data... delay_used = self._devicesettings.get('post_teleport_delay', 7) # Test for cooldown / teleported distance TODO: check this block... if self._devicesettings.get('cool_down_sleep', False): if distance > 2500: delay_used = 8 elif distance > 5000: delay_used = 10 elif distance > 10000: delay_used = 15 log.info("Need more sleep after Teleport: %s seconds!" % str(delay_used)) # curTime = math.floor(time.time()) # the time we will take as a starting point to wait for data... if 0 < self._devicesettings.get('walk_after_teleport_distance', 0) < distance: # TODO: actually use to_walk for distance to_walk = get_distance_of_two_points_in_meters(float(self.current_location.lat), float(self.current_location.lng), float(self.current_location.lat) + 0.0001, float(self.current_location.lng) + 0.0001) log.info("Walking a bit: %s" % str(to_walk)) time.sleep(0.3) self._communicator.walkFromTo(self.current_location.lat, self.current_location.lng, self.current_location.lat + 0.0001, self.current_location.lng + 0.0001, 11) log.debug("Walking back") time.sleep(0.3) self._communicator.walkFromTo(self.current_location.lat + 0.0001, self.current_location.lng + 0.0001, self.current_location.lat, self.current_location.lng, 11) log.debug("Done walking") else: log.info("main: Walking...") self._communicator.walkFromTo(self.last_location.lat, self.last_location.lng, self.current_location.lat, self.current_location.lng, speed) # cur_time = math.floor(time.time()) # the time we will take as a starting point to wait for data... delay_used = self._devicesettings.get('post_walk_delay', 7) log.info("Sleeping %s" % str(delay_used)) time.sleep(float(delay_used)) cur_time = time.time() return cur_time
def _get_relations_in_range_within_time(self, queue, max_radius): relations = {} for event in queue: for other_event in queue: if (event[1].lat == other_event[1].lat and event[1].lng == other_event[1].lng and event not in relations.keys()): relations[event] = [] distance = get_distance_of_two_points_in_meters( event[1].lat, event[1].lng, other_event[1].lat, other_event[1].lng) # we will always build relations from the event at hand subtracted by the event inspected timedelta = event[0] - other_event[0] if 0 <= distance <= max_radius * 2 and 0 <= timedelta <= self.max_timedelta_seconds: if event not in relations.keys(): relations[event] = [] # avoid duplicates already_present = False for relation in relations[event]: if (relation[0][1].lat == other_event[1].lat and relation[0][1].lng == other_event[1].lng): already_present = True if not already_present: relations[event].append( Relation(other_event, distance, timedelta)) return relations
def _move_to_location(self): routemanager = self._get_currently_valid_routemanager() if routemanager is None: raise InternalStopWorkerException if self._db_wrapper.check_stop_quest(self.current_location.lat, self.current_location.lng): return False, False distance = get_distance_of_two_points_in_meters( float(self.last_location.lat), float(self.last_location.lng), float(self.current_location.lat), float(self.current_location.lng)) log.info('main: Moving %s meters to the next position' % distance) delay_used = 0 log.debug("Getting time") speed = routemanager.settings.get("speed", 0) max_distance = routemanager.settings.get("max_distance", None) if (speed == 0 or (max_distance and 0 < max_distance < distance) or (self.last_location.lat == 0.0 and self.last_location.lng == 0.0)): log.info("main: Teleporting...") self._communicator.setLocation(self.current_location.lat, self.current_location.lng, 0) cur_time = math.floor(time.time( )) # the time we will take as a starting point to wait for data... delay_used = self._devicesettings.get('post_teleport_delay', 7) # Test for cooldown / teleported distance TODO: check this block... if self.first_round: delay_used = 3 self.first_round = False else: if distance < 200: delay_used = 5 elif distance < 500: delay_used = 15 elif distance < 1000: delay_used = 30 elif distance > 1000: delay_used = 80 elif distance > 5000: delay_used = 200 elif distance > 10000: delay_used = 400 elif distance > 20000: delay_used = 800 log.info("Need more sleep after Teleport: %s seconds!" % str(delay_used)) else: log.info("main: Walking...") self._communicator.walkFromTo(self.last_location.lat, self.last_location.lng, self.current_location.lat, self.current_location.lng, speed) cur_time = math.floor(time.time( )) # the time we will take as a starting point to wait for data... delay_used = self._devicesettings.get('post_walk_delay', 7) log.info("Sleeping %s" % str(delay_used)) time.sleep(float(delay_used)) return cur_time, True
def _other_worker_closer_to_prioq(self, prioqcoord, origin): logger.debug('Check distances from worker to prioQ coord') temp_distance: float = 0.0 closer_worker = None if len(self._workers_registered) == 1: logger.debug('Route has only one worker - no distance check') return False current_worker_pos = self._routepool[origin].current_pos distance_worker = get_distance_of_two_points_in_meters( current_worker_pos.lat, current_worker_pos.lng, prioqcoord.lat, prioqcoord.lng) logger.debug("Worker {} distance to PrioQ {}: {}", origin, prioqcoord, distance_worker) temp_distance = distance_worker for worker in self._routepool.keys(): if worker == origin or self._routepool[worker].has_prio_event \ or self._routepool[origin].last_round_prio_event: continue worker_pos = self._routepool[worker].current_pos prio_distance = get_distance_of_two_points_in_meters( worker_pos.lat, worker_pos.lng, prioqcoord.lat, prioqcoord.lng) logger.debug("Worker {} distance to PrioQ {}: {}", worker, prioqcoord, prio_distance) if prio_distance < temp_distance: logger.debug("Worker {} closer then {} by {} meters", worker, origin, int(distance_worker) - int(prio_distance)) temp_distance = prio_distance closer_worker = worker if closer_worker is not None: with self._manager_mutex: self._routepool[closer_worker].has_prio_event = True self._routepool[closer_worker].prio_coords = prioqcoord logger.debug("Worker {} is closer to PrioQ event {}", closer_worker, prioqcoord) return True logger.debug("No Worker is closer to PrioQ event {} than {}", prioqcoord, origin) return False
def walkFromTo(self, startLat, startLng, destLat, destLng, speed): with self.__sendMutex: # calculate the time it will take to walk and add it to the timeout! distance = get_distance_of_two_points_in_meters( startLat, startLng, destLat, destLng) # speed is in kmph, distance in m # we want m/s -> speed / 3.6 speed_meters = speed / 3.6 seconds_traveltime = distance / speed_meters response = self.websocket_handler.send_and_wait( self.worker_id, self.worker_instance_ref, "geo walk {} {} {} {} {}\r\n".format(startLat, startLng, destLat, destLng, speed), self.__command_timeout + seconds_traveltime) return response
def walkFromTo(self, startLat, startLng, destLat, destLng, speed): self.__sendMutex.acquire() # calculate the time it will take to walk and add it to the timeout! distance = get_distance_of_two_points_in_meters( startLat, startLng, destLat, destLng) # speed is in kmph, distance in m # we want m/s -> speed / 3.6 speed_meters = speed / 3.6 seconds_traveltime = distance / speed_meters response = self.websocketHandler.send_and_wait( self.id, "geo walk %s %s %s %s %s\r\n" % (startLat, startLng, destLat, destLng, speed), self.__commandTimeout + seconds_traveltime) self.__sendMutex.release() return response
def _get_count_and_coords_in_circle_within_timedelta(self, middle, relations, earliest_timestamp, latest_timestamp, max_radius): inside_circle = [] highest_timedelta = 0 if self.useS2: region = s2sphere.CellUnion(S2Helper.get_S2cells_from_circle(middle.lat, middle.lng, self.max_radius, self.S2level)) for event_relations in relations: # exclude previously clustered events... if len(event_relations) == 4 and event_relations[3]: inside_circle.append(event_relations) continue distance = get_distance_of_two_points_in_meters(middle.lat, middle.lng, event_relations[1].lat, event_relations[1].lng) event_in_range = 0 <= distance <= max_radius if self.useS2: event_in_range = region.contains(s2sphere.LatLng.from_degrees(event_relations[1].lat, event_relations[1].lng).to_point()) # timedelta of event being inspected to the earliest timestamp timedelta_end = latest_timestamp - event_relations[0] timedelta_start = event_relations[0] - earliest_timestamp if timedelta_end < 0 and event_in_range: # we found an event starting past the current latest timestamp, let's update the latest_timestamp latest_timestamp_temp = latest_timestamp + abs(timedelta_end) if latest_timestamp_temp - earliest_timestamp <= self.max_timedelta_seconds: latest_timestamp = latest_timestamp_temp highest_timedelta = highest_timedelta + abs(timedelta_end) inside_circle.append(event_relations) elif timedelta_start < 0 and event_in_range: # we found an event starting before earliest_timestamp, let's check that... earliest_timestamp_temp = earliest_timestamp - \ abs(timedelta_start) if latest_timestamp - earliest_timestamp_temp <= self.max_timedelta_seconds: earliest_timestamp = earliest_timestamp_temp highest_timedelta = highest_timedelta + \ abs(timedelta_start) inside_circle.append(event_relations) elif timedelta_end >= 0 and timedelta_start >= 0 and event_in_range: # we found an event within our current timedelta and proximity, just append it to the list inside_circle.append(event_relations) return len(inside_circle), inside_circle, highest_timedelta, latest_timestamp
def _get_count_and_coords_in_circle_within_timedelta( self, middle, relations, earliest_timestamp, latest_timestamp, max_radius): inside_circle = [] highest_timedelta = 0 for event_relations in relations: # exclude previously clustered events... if len(event_relations) == 4 and event_relations[3]: inside_circle.append(event_relations) continue distance = get_distance_of_two_points_in_meters( middle.lat, middle.lng, event_relations[1].lat, event_relations[1].lng) # timedelta of event being inspected to the earliest timestamp timedelta_end = latest_timestamp - event_relations[0] timedelta_start = event_relations[0] - earliest_timestamp if timedelta_end < 0 and 0 <= distance <= max_radius: # we found an event starting past the current latest timestamp, let's update the latest_timestamp latest_timestamp_temp = latest_timestamp + abs(timedelta_end) if latest_timestamp_temp - earliest_timestamp <= self.max_timedelta_seconds: latest_timestamp = latest_timestamp_temp highest_timedelta = highest_timedelta + abs(timedelta_end) inside_circle.append(event_relations) elif timedelta_start < 0 and 0 <= distance <= max_radius: # we found an event starting before earliest_timestamp, let's check that... earliest_timestamp_temp = earliest_timestamp - abs( timedelta_start) if latest_timestamp - earliest_timestamp_temp <= self.max_timedelta_seconds: earliest_timestamp = earliest_timestamp_temp highest_timedelta = highest_timedelta + abs( timedelta_start) inside_circle.append(event_relations) elif timedelta_end >= 0 and timedelta_start >= 0 and 0 <= distance <= max_radius: # we found an event within our current timedelta and proximity, just append it to the list inside_circle.append(event_relations) return len( inside_circle), inside_circle, highest_timedelta, latest_timestamp
def _move_to_location(self): if not self._mapping_manager.routemanager_present(self._routemanager_name) \ or self._stop_worker_event.is_set(): raise InternalStopWorkerException routemanager_settings = self._mapping_manager.routemanager_get_settings( self._routemanager_name) distance = get_distance_of_two_points_in_meters( float(self.last_location.lat), float(self.last_location.lng), float(self.current_location.lat), float(self.current_location.lng)) logger.debug('Moving {} meters to the next position', round(distance, 2)) delay_used = 0 logger.debug("Getting time") speed = routemanager_settings.get("speed", 0) max_distance = routemanager_settings.get("max_distance", None) if (speed == 0 or (max_distance and 0 < max_distance < distance) or (self.last_location.lat == 0.0 and self.last_location.lng == 0.0)): logger.debug("main: Teleporting...") self._transporttype = 0 self._communicator.setLocation(self.current_location.lat, self.current_location.lng, 0) # the time we will take as a starting point to wait for data... cur_time = math.floor(time.time()) delay_used = self.get_devicesettings_value('post_teleport_delay', 7) speed = 16.67 # Speed can be 60 km/h up to distances of 3km if self.last_location.lat == 0.0 and self.last_location.lng == 0.0: logger.info('Starting fresh round - using lower delay') delay_used = self.get_devicesettings_value( 'post_teleport_delay', 7) else: if distance >= 1335000: speed = 180.43 # Speed can be abt 650 km/h elif distance >= 1100000: speed = 176.2820513 elif distance >= 1020000: speed = 168.3168317 elif distance >= 1007000: speed = 171.2585034 elif distance >= 948000: speed = 166.3157895 elif distance >= 900000: speed = 164.8351648 elif distance >= 897000: speed = 166.1111111 elif distance >= 839000: speed = 158.9015152 elif distance >= 802000: speed = 159.1269841 elif distance >= 751000: speed = 152.6422764 elif distance >= 700000: speed = 151.5151515 elif distance >= 650000: speed = 146.3963964 elif distance >= 600000: speed = 142.8571429 elif distance >= 550000: speed = 138.8888889 elif distance >= 500000: speed = 134.4086022 elif distance >= 450000: speed = 129.3103448 elif distance >= 400000: speed = 123.4567901 elif distance >= 350000: speed = 116.6666667 elif distance >= 328000: speed = 113.8888889 elif distance >= 300000: speed = 108.6956522 elif distance >= 250000: speed = 101.6260163 elif distance >= 201000: speed = 90.54054054 elif distance >= 175000: speed = 85.78431373 elif distance >= 150000: speed = 78.125 elif distance >= 125000: speed = 71.83908046 elif distance >= 100000: speed = 64.1025641 elif distance >= 90000: speed = 60 elif distance >= 80000: speed = 55.55555556 elif distance >= 70000: speed = 50.72463768 elif distance >= 60000: speed = 47.61904762 elif distance >= 45000: speed = 39.47368421 elif distance >= 40000: speed = 35.0877193 elif distance >= 35000: speed = 32.40740741 elif distance >= 30000: speed = 29.41176471 elif distance >= 25000: speed = 27.77777778 elif distance >= 20000: speed = 27.77777778 elif distance >= 15000: speed = 27.77777778 elif distance >= 10000: speed = 23.80952381 elif distance >= 8000: speed = 26.66666667 elif distance >= 5000: speed = 22.34137623 elif distance >= 4000: speed = 22.22222222 delay_used = distance / speed if delay_used > 7200: # There's a maximum of 2 hours wait time delay_used = 7200 logger.debug("Need more sleep after Teleport: {} seconds!", str(int(delay_used))) else: logger.info("main: Walking...") self._transporttype = 1 self._communicator.walkFromTo(self.last_location.lat, self.last_location.lng, self.current_location.lat, self.current_location.lng, speed) # the time we will take as a starting point to wait for data... cur_time = math.floor(time.time()) delay_used = self.get_devicesettings_value('post_walk_delay', 7) walk_distance_post_teleport = self.get_devicesettings_value( 'walk_after_teleport_distance', 0) if 0 < walk_distance_post_teleport < distance: # TODO: actually use to_walk for distance lat_offset, lng_offset = get_lat_lng_offsets_by_distance( walk_distance_post_teleport) to_walk = get_distance_of_two_points_in_meters( float(self.current_location.lat), float(self.current_location.lng), float(self.current_location.lat) + lat_offset, float(self.current_location.lng) + lng_offset) logger.info("Walking roughly: {}", str(to_walk)) time.sleep(0.3) self._communicator.walkFromTo( self.current_location.lat, self.current_location.lng, self.current_location.lat + lat_offset, self.current_location.lng + lng_offset, 11) logger.debug("Walking back") time.sleep(0.3) self._communicator.walkFromTo( self.current_location.lat + lat_offset, self.current_location.lng + lng_offset, self.current_location.lat, self.current_location.lng, 11) logger.debug("Done walking") time.sleep(1) delay_used -= ( to_walk / 3.05 ) - 1. # We already waited for a bit because of this walking part if delay_used < 0: delay_used = 0 if self._init: delay_used = 5 if self.get_devicesettings_value('last_action_time', None) is not None: timediff = time.time() - self.get_devicesettings_value( 'last_action_time', 0) logger.info("Timediff between now and last action time: {}", str(int(timediff))) delay_used = delay_used - timediff elif self.get_devicesettings_value( 'last_action_time', None) is None and not self._level_mode: logger.info( 'Starting first time - we wait because of some default pogo delays ...' ) delay_used = 20 else: logger.debug("No last action time found - no calculation") delay_used = -1 if self.get_devicesettings_value('screendetection', False) and \ self._WordToScreenMatching.return_memory_account_count() > 1 and delay_used >= self._rotation_waittime \ and self.get_devicesettings_value('account_rotation', False) and not self._level_mode: # Waiting time to long and more then one account - switch! (not level mode!!) logger.info('Could use more then 1 account - switch & no cooldown') self.switch_account() delay_used = -1 if delay_used < 0: self._current_sleep_time = 0 logger.info('No need to wait before spinning, continuing...') else: delay_used = math.floor(delay_used) logger.info("Real sleep time: {} seconds: next action {}", str(delay_used), str(datetime.now() + timedelta(seconds=delay_used))) cleanupbox = False lastcleanupbox = self.get_devicesettings_value( 'last_cleanup_time', None) self._current_sleep_time = delay_used self.worker_stats() if lastcleanupbox is not None: if time.time() - lastcleanupbox > 900: # just cleanup if last cleanup time > 15 minutes ago cleanupbox = True self._mapping_manager.routemanager_set_worker_sleeping( self._routemanager_name, self._id, delay_used) while time.time() <= int(cur_time) + int(delay_used): if delay_used > 200 and cleanupbox: self.clear_thread_task = 1 cleanupbox = False if not self._mapping_manager.routemanager_present(self._routemanager_name) \ or self._stop_worker_event.is_set(): logger.error("Worker {} get killed while sleeping", str(self._id)) self._current_sleep_time = 0 raise InternalStopWorkerException time.sleep(1) self._current_sleep_time = 0 self.set_devicesettings_value("last_location", self.current_location) self.last_location = self.current_location return cur_time, True
def _move_to_location(self): routemanager = self._walker_routemanager if routemanager is None: raise InternalStopWorkerException # get the distance from our current position (last) to the next gym (cur) distance = get_distance_of_two_points_in_meters( float(self.last_location.lat), float(self.last_location.lng), float(self.current_location.lat), float(self.current_location.lng)) logger.info('Moving {} meters to the next position', round(distance, 2)) delay_used = 0 speed = routemanager.settings.get("speed", 0) max_distance = routemanager.settings.get("max_distance", None) if (speed == 0 or (max_distance and 0 < max_distance < distance) or (self.last_location.lat == 0.0 and self.last_location.lng == 0.0)): self._communicator.setLocation(self.current_location.lat, self.current_location.lng, 0) # the time we will take as a starting point to wait for data... cur_time = math.floor(time.time()) delay_used = self._devicesettings.get('post_teleport_delay', 7) # Test for cooldown / teleported distance TODO: check this block... if self._devicesettings.get('cool_down_sleep', False): if distance > 2500: delay_used = 8 elif distance > 5000: delay_used = 10 elif distance > 10000: delay_used = 15 logger.debug("Need more sleep after Teleport: {} seconds!", str(delay_used)) # curTime = math.floor(time.time()) # the time we will take as a starting point to wait for data... walk_distance_post_teleport = self._devicesettings.get( 'walk_after_teleport_distance', 0) if 0 < walk_distance_post_teleport < distance: # TODO: actually use to_walk for distance lat_offset, lng_offset = get_lat_lng_offsets_by_distance( walk_distance_post_teleport) to_walk = get_distance_of_two_points_in_meters( float(self.current_location.lat), float(self.current_location.lng), float(self.current_location.lat) + lat_offset, float(self.current_location.lng) + lng_offset) logger.info("Walking roughly: {}", str(to_walk)) time.sleep(0.3) self._communicator.walkFromTo( self.current_location.lat, self.current_location.lng, self.current_location.lat + lat_offset, self.current_location.lng + lng_offset, 11) logger.debug("Walking back") time.sleep(0.3) self._communicator.walkFromTo( self.current_location.lat + lat_offset, self.current_location.lng + lng_offset, self.current_location.lat, self.current_location.lng, 11) logger.debug("Done walking") time.sleep(1) else: logger.info("main: Walking...") self._communicator.walkFromTo(self.last_location.lat, self.last_location.lng, self.current_location.lat, self.current_location.lng, speed) # the time we will take as a starting point to wait for data... cur_time = math.floor(time.time()) delay_used = self._devicesettings.get('post_walk_delay', 7) time.sleep(float(delay_used)) self._devicesettings["last_location"] = self.current_location self.last_location = self.current_location return cur_time, True
def _main_work_thread(self): current_thread().name = self.id log.debug("Sub called") # first check if pogo is running etc etc self._workMutex.acquire() try: self._initRoutine() except WebsocketWorkerRemovedException: log.error("Timeout during init of worker %s" % str(self.id)) self._stop_worker_event.set() self._workMutex.release() return self._workMutex.release() # loop = asyncio.get_event_loop() # TODO:loop.create_task(self._speed_weather_check_thread()) speedWeatherCheckThread = Thread( name='speedWeatherCheckThread%s' % self.id, target=self._speed_weather_check_thread) speedWeatherCheckThread.daemon = False speedWeatherCheckThread.start() currentLocation = self._last_known_state.get("last_location", None) if currentLocation is None: currentLocation = Location(0.0, 0.0) lastLocation = None while not self._stop_worker_event.isSet(): while MadGlobals.sleep and self._route_manager_nighttime is None: time.sleep(1) __time = time.time() log.debug("Worker: acquiring lock for restart check") self._workMutex.acquire() log.debug("Worker: acquired lock") # Restart pogo every now and then... if self._devicesettings.get("restart_pogo", 80) > 0: # log.debug("main: Current time - lastPogoRestart: %s" % str(curTime - lastPogoRestart)) # if curTime - lastPogoRestart >= (args.restart_pogo * 60): self._locationCount += 1 if self._locationCount > self._devicesettings.get( "restart_pogo", 80): log.error( "scanned " + str(self._devicesettings.get("restart_pogo", 80)) + " locations, restarting pogo") try: self._restartPogo() except WebsocketWorkerRemovedException: log.error("Timeout restarting pogo on %s" % str(self.id)) self._stop_worker_event.set() self._workMutex.release() return self._locationCount = 0 self._workMutex.release() log.debug("Worker: lock released") # TODO: consider adding runWarningThreadEvent.set() lastLocation = currentLocation self._last_known_state["last_location"] = lastLocation if MadGlobals.sleep: currentLocation = self._route_manager_nighttime.get_next_location( ) settings = self._route_manager_nighttime.settings else: currentLocation = self._route_manager_daytime.get_next_location( ) settings = self._route_manager_daytime.settings # TODO: set position... needs to be adjust for multidevice posfile = open(self.id + '.position', "w") posfile.write( str(currentLocation.lat) + ", " + str(currentLocation.lng)) posfile.close() log.debug("main: next stop: %s" % (str(currentLocation))) log.debug( 'main: LastLat: %s, LastLng: %s, CurLat: %s, CurLng: %s' % (lastLocation.lat, lastLocation.lng, currentLocation.lat, currentLocation.lng)) # get the distance from our current position (last) to the next gym (cur) distance = get_distance_of_two_points_in_meters( float(lastLocation.lat), float(lastLocation.lng), float(currentLocation.lat), float(currentLocation.lng)) log.info('main: Moving %s meters to the next position' % distance) delayUsed = 0 if MadGlobals.sleep: speed = self._route_manager_nighttime.settings.get("speed", 0) else: speed = self._route_manager_daytime.settings.get("speed", 0) if (speed == 0 or (settings["max_distance"] and 0 < settings["max_distance"] < distance) or (lastLocation.lat == 0.0 and lastLocation.lng == 0.0)): log.info("main: Teleporting...") try: self._communicator.setLocation(currentLocation.lat, currentLocation.lng, 0) except WebsocketWorkerRemovedException: log.error("Timeout setting location of %s" % str(self.id)) self._stop_worker_event.set() return delayUsed = self._devicesettings.get("post_teleport_delay", 7) # Test for cooldown / teleported distance TODO: check this block... if self._devicesettings.get("cool_down_sleep", False): if distance > 2500: delayUsed = 30 elif distance > 5000: delayUsed = 45 elif distance > 10000: delayUsed = 60 log.info("Need more sleep after Teleport: %s seconds!" % str(delayUsed)) if 0 < self._devicesettings.get("walk_after_teleport_distance", 0) < distance: toWalk = get_distance_of_two_points_in_meters( float(currentLocation.lat), float(currentLocation.lng), float(currentLocation.lat) + 0.0001, float(currentLocation.lng) + 0.0001) log.info("Walking a bit: %s" % str(toWalk)) time.sleep(0.3) try: self._communicator.walkFromTo( currentLocation.lat, currentLocation.lng, currentLocation.lat + 0.0001, currentLocation.lng + 0.0001, 11) log.debug("Walking back") time.sleep(0.3) self._communicator.walkFromTo( currentLocation.lat + 0.0001, currentLocation.lng + 0.0001, currentLocation.lat, currentLocation.lng, 11) except WebsocketWorkerRemovedException: log.error("Timeout walking a bit on %s" % str(self.id)) self._stop_worker_event.set() return log.debug("Done walking") else: log.info("main: Walking...") try: self._communicator.walkFromTo(lastLocation.lat, lastLocation.lng, currentLocation.lat, currentLocation.lng, speed) except WebsocketWorkerRemovedException: log.error("Timeout while walking with worker %s" % str(self.id)) self._stop_worker_event.set() return delayUsed = self._devicesettings.get("post_walk_delay", 7) log.info("Sleeping %s" % str(delayUsed)) time.sleep(float(delayUsed)) log.debug("main: Acquiring lock") while MadGlobals.sleep: # or not runWarningThreadEvent.isSet(): time.sleep(0.1) log.debug("Worker: acquiring lock") self._workMutex.acquire() log.debug("main: Lock acquired") try: if not self._takeScreenshot(): self._workMutex.release() log.debug("Worker: Lock released") continue except WebsocketWorkerRemovedException: log.error("Timeout grabbing a screenshot from %s" % str(self.id)) self._stop_worker_event.set() self._workMutex.release() return log.debug("Worker: Got screenshot") curTime = time.time() if self._applicationArgs.last_scanned: log.info('main: Set new scannedlocation in Database') self._db_wrapper.set_scanned_location(str(currentLocation.lat), str(currentLocation.lng), str(curTime)) log.info( "main: Checking raidcount and copying raidscreen if raids present" ) countOfRaids = self._pogoWindowManager.readRaidCircles( os.path.join(self._applicationArgs.temp_path, 'screenshot%s.png' % str(self.id)), self.id) if countOfRaids == -1: log.debug("Worker: Count present but no raid shown") log.warning( "main: Count present but no raid shown, reopening raidTab") try: self._reopenRaidTab() except WebsocketWorkerRemovedException: log.error("Timeout reopening the raidtab on %s" % str(self.id)) self._stop_worker_event.set() self._workMutex.release() return # tabOutAndInPogo() log.debug("Done reopening raidtab") try: if not self._takeScreenshot(): self._workMutex.release() log.debug("Worker: Lock released") continue except WebsocketWorkerRemovedException: log.error("Timeout grabbing screenshot from worker %s" % str(self.id)) self._stop_worker_event.set() self._workMutex.release() return countOfRaids = self._pogoWindowManager.readRaidCircles( os.path.join(self._applicationArgs.temp_path, 'screenshot%s.png' % str(self.id)), self.id) # elif countOfRaids == 0: # emptycount += 1 # if emptycount > 30: # emptycount = 0 # log.error("Had 30 empty scans, restarting pogo") # restartPogo() # not an elif since we may have gotten a new screenshot.. # detectin weather if self._applicationArgs.weather: log.debug("Worker: Checking weather...") weather = checkWeather( os.path.join(self._applicationArgs.temp_path, 'screenshot%s.png' % str(self.id))) if weather[0]: log.debug('Submit Weather') cell_id = S2Helper.lat_lng_to_cell_id( currentLocation.lat, currentLocation.lng) self._db_wrapper.update_insert_weather( cell_id, weather[1], curTime) else: log.error('Weather could not detected') if countOfRaids > 0: log.debug("Worker: Count of raids >0") log.debug( "main: New und old Screenshoot are different - starting OCR" ) log.debug("main: countOfRaids: %s" % str(countOfRaids)) curTime = time.time() copyFileName = self._applicationArgs.raidscreen_path + '/raidscreen_' + str(curTime) \ + "_" + str(currentLocation.lat) + "_" + str(currentLocation.lng) + "_" \ + str(countOfRaids) + '.png' log.debug('Copying file: ' + copyFileName) log.debug("Worker: Copying file to %s" % str(copyFileName)) copyfile( os.path.join(self._applicationArgs.temp_path, 'screenshot%s.png' % str(self.id)), copyFileName) os.remove( os.path.join(self._applicationArgs.temp_path, 'screenshot%s.png' % str(self.id))) log.debug("main: Releasing lock") self._workMutex.release() log.debug("Worker: Lock released")
def statistics_detection_worker_data(self): minutes = request.args.get('minutes', 120) worker = request.args.get('worker') # spawns mon = [] mon_iv = [] raid = [] quest = [] usage = [] data = self._db.statistics_get_detection_count(minutes=minutes, worker=worker) for dat in data: mon.append([dat[0] * 1000, int(dat[2])]) mon_iv.append([dat[0] * 1000, int(dat[3])]) raid.append([dat[0] * 1000, int(dat[4])]) quest.append([dat[0] * 1000, int(dat[5])]) usage.append({'label': 'Mon', 'data': mon}) usage.append({'label': 'Mon_IV', 'data': mon_iv}) usage.append({'label': 'Raid', 'data': raid}) usage.append({'label': 'Quest', 'data': quest}) # locations avg locations_avg = [] data = self._db.statistics_get_avg_data_time(minutes=minutes, worker=worker) for dat in data: dtime = datetime.datetime.fromtimestamp(dat[0]).strftime( self._datetimeformat) locations_avg.append({ 'dtime': dtime, 'ok_locations': dat[3], 'avg_datareceive': float(dat[4]), 'transporttype': dat[1], 'type': dat[5] }) # locations ok = [] nok = [] sumloc = [] locations = [] data = self._db.statistics_get_locations(minutes=minutes, worker=worker) for dat in data: ok.append([dat[0] * 1000, int(dat[3])]) nok.append([dat[0] * 1000, int(dat[4])]) sumloc.append([dat[0] * 1000, int(dat[2])]) locations.append({'label': 'Locations', 'data': sumloc}) locations.append({'label': 'Locations_ok', 'data': ok}) locations.append({'label': 'Locations_nok', 'data': nok}) # dataratio loctionratio = [] data = self._db.statistics_get_locations_dataratio(minutes=minutes, worker=worker) if len(data) > 0: for dat in data: loctionratio.append({'label': dat[3], 'data': dat[2]}) else: loctionratio.append({'label': '', 'data': 0}) # all spaws all_spawns = [] data = self._db.statistics_get_detection_count(grouped=False, worker=worker) all_spawns.append({'type': 'Mon', 'amount': int(data[0][2])}) all_spawns.append({'type': 'Mon_IV', 'amount': int(data[0][3])}) all_spawns.append({'type': 'Raid', 'amount': int(data[0][4])}) all_spawns.append({'type': 'Quest', 'amount': int(data[0][5])}) # raw detection data detections_raw = [] data = self._db.statistics_get_detection_raw(minutes=minutes, worker=worker) for dat in data: detections_raw.append({ 'type': dat[1], 'id': dat[2], 'count': dat[3] }) # location raw location_raw = [] last_lat = 0 last_lng = 0 distance = 0 data = self._db.statistics_get_location_raw(minutes=minutes, worker=worker) for dat in data: if last_lat != 0 and last_lng != 0: distance = round( get_distance_of_two_points_in_meters( last_lat, last_lng, dat[1], dat[2]), 2) last_lat = dat[1] last_lng = dat[2] if last_lat == 0 and last_lng == 0: last_lat = dat[1] last_lng = dat[2] if dat[1] == 0 and dat[2] == 0: distance = '' location_raw.append({ 'lat': dat[1], 'lng': dat[2], 'distance': distance, 'type': dat[3], 'data': dat[4], 'fix_ts': datetime.datetime.fromtimestamp(dat[5]).strftime( self._datetimeformat), 'data_ts': datetime.datetime.fromtimestamp(dat[6]).strftime( self._datetimeformat), 'transporttype': dat[8] }) workerstats = { 'avg': locations_avg, 'receiving': usage, 'locations': locations, 'ratio': loctionratio, 'allspawns': all_spawns, 'detections_raw': detections_raw, 'location_raw': location_raw } return jsonify(workerstats)
def _move_to_location(self): routemanager = self._walker_routemanager if routemanager is None: raise InternalStopWorkerException if self._db_wrapper.check_stop_quest(self.current_location.lat, self.current_location.lng): return False, False distance = get_distance_of_two_points_in_meters( float(self.last_location.lat), float(self.last_location.lng), float(self.current_location.lat), float(self.current_location.lng)) logger.debug('Moving {} meters to the next position', round(distance, 2)) delay_used = 0 logger.debug("Getting time") speed = routemanager.settings.get("speed", 0) max_distance = routemanager.settings.get("max_distance", None) if (speed == 0 or (max_distance and 0 < max_distance < distance) or (self.last_location.lat == 0.0 and self.last_location.lng == 0.0)): logger.debug("main: Teleporting...") self._transporttype = 0 self._communicator.setLocation(self.current_location.lat, self.current_location.lng, 0) # the time we will take as a starting point to wait for data... cur_time = math.floor(time.time()) delay_used = self._devicesettings.get('post_teleport_delay', 7) speed = 16.67 # Speed can be 60 km/h up to distances of 3km if self.last_location.lat == 0.0 and self.last_location.lng == 0.0: logger.info('Starting fresh round - using lower delay') delay_used = self._devicesettings.get('post_teleport_delay', 7) else: if distance >= 1335000: speed = 180.43 # Speed can be abt 650 km/h elif distance >= 1100000: speed = 176.2820513 elif distance >= 1020000: speed = 168.3168317 elif distance >= 1007000: speed = 171.2585034 elif distance >= 948000: speed = 166.3157895 elif distance >= 900000: speed = 164.8351648 elif distance >= 897000: speed = 166.1111111 elif distance >= 839000: speed = 158.9015152 elif distance >= 802000: speed = 159.1269841 elif distance >= 751000: speed = 152.6422764 elif distance >= 700000: speed = 151.5151515 elif distance >= 650000: speed = 146.3963964 elif distance >= 600000: speed = 142.8571429 elif distance >= 550000: speed = 138.8888889 elif distance >= 500000: speed = 134.4086022 elif distance >= 450000: speed = 129.3103448 elif distance >= 400000: speed = 123.4567901 elif distance >= 350000: speed = 116.6666667 elif distance >= 328000: speed = 113.8888889 elif distance >= 300000: speed = 108.6956522 elif distance >= 250000: speed = 101.6260163 elif distance >= 201000: speed = 90.54054054 elif distance >= 175000: speed = 85.78431373 elif distance >= 150000: speed = 78.125 elif distance >= 125000: speed = 71.83908046 elif distance >= 100000: speed = 64.1025641 elif distance >= 90000: speed = 60 elif distance >= 80000: speed = 55.55555556 elif distance >= 70000: speed = 50.72463768 elif distance >= 60000: speed = 47.61904762 elif distance >= 45000: speed = 39.47368421 elif distance >= 40000: speed = 35.0877193 elif distance >= 35000: speed = 32.40740741 elif distance >= 30000: speed = 29.41176471 elif distance >= 25000: speed = 27.77777778 elif distance >= 20000: speed = 27.77777778 elif distance >= 15000: speed = 27.77777778 elif distance >= 10000: speed = 23.80952381 elif distance >= 8000: speed = 26.66666667 elif distance >= 5000: speed = 22.34137623 elif distance >= 4000: speed = 22.22222222 delay_used = distance / speed if delay_used > 7200: # There's a maximum of 2 hours wait time delay_used = 7200 logger.debug("Need more sleep after Teleport: {} seconds!", str(delay_used)) else: logger.info("main: Walking...") self._transporttype = 1 self._communicator.walkFromTo(self.last_location.lat, self.last_location.lng, self.current_location.lat, self.current_location.lng, speed) # the time we will take as a starting point to wait for data... cur_time = math.floor(time.time()) delay_used = self._devicesettings.get('post_walk_delay', 7) walk_distance_post_teleport = self._devicesettings.get( 'walk_after_teleport_distance', 0) if 0 < walk_distance_post_teleport < distance: # TODO: actually use to_walk for distance lat_offset, lng_offset = get_lat_lng_offsets_by_distance( walk_distance_post_teleport) to_walk = get_distance_of_two_points_in_meters( float(self.current_location.lat), float(self.current_location.lng), float(self.current_location.lat) + lat_offset, float(self.current_location.lng) + lng_offset) logger.info("Walking roughly: {}", str(to_walk)) time.sleep(0.3) self._communicator.walkFromTo( self.current_location.lat, self.current_location.lng, self.current_location.lat + lat_offset, self.current_location.lng + lng_offset, 11) logger.debug("Walking back") time.sleep(0.3) self._communicator.walkFromTo( self.current_location.lat + lat_offset, self.current_location.lng + lng_offset, self.current_location.lat, self.current_location.lng, 11) logger.debug("Done walking") time.sleep(1) delay_used -= ( to_walk / 3.05 ) - 1. # We already waited for a bit because of this walking part if delay_used < 0: delay_used = 0 if self._init: delay_used = 5 if self._devicesettings.get('last_action_time', None) is not None: timediff = time.time() - self._devicesettings['last_action_time'] logger.info("Timediff between now and last action time: {}", str(float(timediff))) delay_used = delay_used - timediff else: logger.debug("No last action time found - no calculation") if delay_used < 0: logger.info('No more cooldowntime - start over') else: logger.info("Real sleep time: {} seconds!", str(delay_used)) cleanupbox = False lastcleanupbox = self._devicesettings.get('last_cleanup_time', None) if lastcleanupbox is not None: if time.time() - lastcleanupbox > 900: # just cleanup if last cleanup time > 15 minutes ago cleanupbox = True while time.time() <= int(cur_time) + int(delay_used): if delay_used > 200 and cleanupbox: self.clear_thread_task = 1 cleanupbox = False time.sleep(1) self._devicesettings["last_location"] = self.current_location self.last_location = self.current_location return cur_time, True
def _main_work_thread(self): current_thread().name = self.id log.info("Quests worker starting") _data_err_counter, data_error_counter = 0, 0 firstround = True t_asyncio_loop = Thread(name='mitm_asyncio_' + self.id, target=self.__start_asyncio_loop) t_asyncio_loop.daemon = True t_asyncio_loop.start() clearThread = Thread(name='clearThread%s' % self.id, target=self._clear_thread) clearThread.daemon = True clearThread.start() self.get_screen_size() self._delayadd = int(self._devicesettings.get("vps_delay", 0)) self._work_mutex.acquire() try: self._start_pogo() except WebsocketWorkerRemovedException: log.error("Timeout during init of worker %s" % str(self.id)) self._stop_worker_event.set() self._work_mutex.release() return self._work_mutex.release() self.loop_started.wait() reachedMainMenu = self._checkPogoMainScreen(15, True) if not reachedMainMenu: self._restartPogo() currentLocation = self._last_known_state.get("last_location", None) if currentLocation is None: currentLocation = Location(0.0, 0.0) lastLocation = None while not self._stop_worker_event.isSet(): while MadGlobals.sleep and self._route_manager_nighttime is None: time.sleep(1) log.debug("Worker: acquiring lock for restart check") self._work_mutex.acquire() log.debug("Worker: acquired lock") # check if pogo is topmost and start if necessary try: log.debug( "Calling _start_pogo routine to check if pogo is topmost") self._start_pogo() except WebsocketWorkerRemovedException: log.error("Timeout starting pogo on %s" % str(self.id)) self._stop_worker_event.set() self._work_mutex.release() return log.debug("Checking if we need to restart pogo") # Restart pogo every now and then... if self._devicesettings.get("restart_pogo", 80) > 0: # log.debug("main: Current time - lastPogoRestart: %s" % str(curTime - lastPogoRestart)) # if curTime - lastPogoRestart >= (args.restart_pogo * 60): self._locationCount += 1 if self._locationCount > self._devicesettings.get( "restart_pogo", 80): log.error( "scanned " + str(self._devicesettings.get("restart_pogo", 80)) + " locations, restarting pogo") self._restartPogo() self._locationCount = 0 self._work_mutex.release() log.debug("Worker: lock released") # TODO: consider adding runWarningThreadEvent.set() lastLocation = currentLocation self._last_known_state["last_location"] = lastLocation log.debug("Requesting next location from routemanager") if MadGlobals.sleep and self._route_manager_nighttime is not None: currentLocation = self._route_manager_nighttime.get_next_location( ) settings = self._route_manager_nighttime.settings while self._db_wrapper.check_stop_quest( currentLocation.lat, currentLocation.lng): self._route_manager_nighttime.del_from_route() currentLocation = self._route_manager_nighttime.get_next_location( ) elif MadGlobals.sleep: # skip to top while loop to get to sleep loop continue else: currentLocation = self._route_manager_daytime.get_next_location( ) settings = self._route_manager_daytime.settings while self._db_wrapper.check_stop_quest( currentLocation.lat, currentLocation.lng): self._route_manager_daytime.del_from_route() currentLocation = self._route_manager_daytime.get_next_location( ) self.__update_injection_settings() # TODO: set position... needs to be adjust for multidevice log.debug("Updating .position file") with open(self.id + '.position', 'w') as outfile: outfile.write( str(currentLocation.lat) + ", " + str(currentLocation.lng)) log.debug("main: next stop: %s" % (str(currentLocation))) log.debug( 'main: LastLat: %s, LastLng: %s, CurLat: %s, CurLng: %s' % (lastLocation.lat, lastLocation.lng, currentLocation.lat, currentLocation.lng)) # get the distance from our current position (last) to the next gym (cur) distance = get_distance_of_two_points_in_meters( float(lastLocation.lat), float(lastLocation.lng), float(currentLocation.lat), float(currentLocation.lng)) log.info('main: Moving %s meters to the next position' % distance) delayUsed = 0 log.debug("Getting time") if MadGlobals.sleep: speed = self._route_manager_nighttime.settings.get("speed", 0) else: speed = self._route_manager_daytime.settings.get("speed", 0) if (speed == 0 or (settings['max_distance'] and 0 < settings['max_distance'] < distance) or (lastLocation.lat == 0.0 and lastLocation.lng == 0.0)): log.info("main: Teleporting...") # TODO: catch exception... try: self._communicator.setLocation(currentLocation.lat, currentLocation.lng, 0) # the time we will take as a starting point to wait for data... curTime = math.floor(time.time()) except WebsocketWorkerRemovedException: log.error("Timeout setting location for %s" % str(self.id)) self._stop_worker_event.set() return delayUsed = self._devicesettings.get('post_teleport_delay', 7) # Test for cooldown / teleported distance TODO: check this block... if firstround: delayUsed = 3 firstround = False else: if distance < 200: delayUsed = 5 elif distance < 500: delayUsed = 15 elif distance < 1000: delayUsed = 30 elif distance > 1000: delayUsed = 80 elif distance > 5000: delayUsed = 200 elif distance > 10000: delayUsed = 400 elif distance > 20000: delayUsed = 800 log.info("Need more sleep after Teleport: %s seconds!" % str(delayUsed)) # curTime = math.floor(time.time()) # the time we will take as a starting point to wait for data... else: log.info("main: Walking...") try: self._communicator.walkFromTo(lastLocation.lat, lastLocation.lng, currentLocation.lat, currentLocation.lng, speed) # the time we will take as a starting point to wait for data... curTime = math.floor(time.time()) except WebsocketWorkerRemovedException: log.error("Timeout setting location for %s" % str(self.id)) self._stop_worker_event.set() return delayUsed = 0 log.info("Sleeping %s" % str(delayUsed)) time.sleep(float(delayUsed)) if self._applicationArgs.last_scanned: log.info('main: Set new scannedlocation in Database') # self.update_scanned_location(currentLocation.lat, currentLocation.lng, curTime) self.__add_task_to_loop( self.update_scanned_location(currentLocation.lat, currentLocation.lng, curTime)) log.debug("Acquiring lock") self._work_mutex.acquire() log.debug("Processing Stop / Quest...") to = 0 data_received = '-' while self._clear_quest or self._clear_box: time.sleep(1) reachedMainMenu = self._checkPogoMainScreen(15, True) if not reachedMainMenu: self._restartPogo() while not 'Stop' in data_received and int(to) < 3: curTime = time.time() self._open_gym(self._delayadd) data_received, data_error_counter = self.wait_for_data( data_err_counter=_data_err_counter, timestamp=curTime, proto_to_wait_for=104, timeout=25) _data_err_counter = data_error_counter if data_received is not None: if 'Gym' in data_received: log.debug('Clicking GYM') x, y = self._resocalc.get_close_main_button_coords( self )[0], self._resocalc.get_close_main_button_coords( self)[1] self._communicator.click(int(x), int(y)) time.sleep(2) self._turn_map(self._delayadd) if 'Mon' in data_received: time.sleep(2) log.debug('Clicking MON') x, y = self._resocalc.get_leave_mon_coords(self)[ 0], self._resocalc.get_leave_mon_coords(self)[1] self._communicator.click(int(x), int(y)) time.sleep(.5) self._turn_map(self._delayadd) if data_received is None: data_received = '-' to += 1 time.sleep(0.5) to = 0 if 'Stop' in data_received: while not 'Quest' in data_received and int(to) < 3: curTime = time.time() self._spin_wheel(self._delayadd) data_received, data_error_counter = self.wait_for_data( data_err_counter=_data_err_counter, timestamp=curTime, proto_to_wait_for=101, timeout=20) _data_err_counter = data_error_counter if data_received is not None: if 'Box' in data_received: log.error('Box is full ... Next round!') self._close_gym(self._delayadd) to = 3 self._clear_box = True roundcount = 0 break if 'Quest' in data_received: self._close_gym(self._delayadd) self._clear_quest = True break if 'SB' in data_received: log.error('Softban - waiting...') time.sleep(10) to += 1 if to == 3: self._close_gym(self._delayadd) else: data_received = '-' log.error( 'Did not get any data ... Maybe already spinned or softban.' ) to += 1 if to == 3: self._close_gym(self._delayadd) log.debug("Releasing lock") self._work_mutex.release() log.debug("Worker %s done, next iteration" % str(self.id)) t_asyncio_loop.join()
def _main_work_thread(self): current_thread().name = self.id log.info("MITM worker starting") _data_err_counter, data_error_counter = 0, 0 # first check if pogo is running etc etc t_mitm_data = Thread(name='mitm_receiver_' + self.id, target=self.start_mitm_receiver, args=(self._received_mapping,)) t_mitm_data.daemon = False t_mitm_data.start() t_asyncio_loop = Thread(name='mitm_asyncio_' + self.id, target=self.__start_asyncio_loop) t_asyncio_loop.daemon = False t_asyncio_loop.start() self._work_mutex.acquire() try: self._start_pogo() except WebsocketWorkerRemovedException: log.error("Timeout during init of worker %s" % str(self.id)) self._stop_worker_event.set() self._work_mutex.release() return self._work_mutex.release() self.loop_started.wait() currentLocation = self._last_known_state.get("last_location", None) if currentLocation is None: currentLocation = Location(0.0, 0.0) lastLocation = None while not self._stop_worker_event.isSet(): while MadGlobals.sleep and self._route_manager_nighttime is None: time.sleep(1) log.debug("Worker: acquiring lock for restart check") self._work_mutex.acquire() log.debug("Worker: acquired lock") # check if pogo is topmost and start if necessary try: log.debug("Calling _start_pogo routine to check if pogo is topmost") self._start_pogo() except WebsocketWorkerRemovedException: log.error("Timeout starting pogo on %s" % str(self.id)) self._stop_worker_event.set() self._work_mutex.release() return log.debug("Checking if we needto restart pogo") # Restart pogo every now and then... if self._devicesettings.get("restart_pogo", 80) > 0: # log.debug("main: Current time - lastPogoRestart: %s" % str(curTime - lastPogoRestart)) # if curTime - lastPogoRestart >= (args.restart_pogo * 60): self._locationCount += 1 if self._locationCount > self._devicesettings.get("restart_pogo", 80): log.error("scanned " + str(self._devicesettings.get("restart_pogo", 80)) + " locations, restarting pogo") self._restartPogo() self._locationCount = 0 self._work_mutex.release() log.debug("Worker: lock released") # TODO: consider adding runWarningThreadEvent.set() lastLocation = currentLocation self._last_known_state["last_location"] = lastLocation log.debug("Requesting next location from routemanager") if MadGlobals.sleep and self._route_manager_nighttime is not None: currentLocation = self._route_manager_nighttime.get_next_location() settings = self._route_manager_nighttime.settings elif MadGlobals.sleep: # skip to top while loop to get to sleep loop continue else: currentLocation = self._route_manager_daytime.get_next_location() settings = self._route_manager_daytime.settings # TODO: set position... needs to be adjust for multidevice log.debug("Updating .position file") with open(self.id + '.position', 'w') as outfile: outfile.write(str(currentLocation.lat)+", "+str(currentLocation.lng)) log.debug("main: next stop: %s" % (str(currentLocation))) log.debug('main: LastLat: %s, LastLng: %s, CurLat: %s, CurLng: %s' % (lastLocation.lat, lastLocation.lng, currentLocation.lat, currentLocation.lng)) # get the distance from our current position (last) to the next gym (cur) distance = get_distance_of_two_points_in_meters(float(lastLocation.lat), float(lastLocation.lng), float(currentLocation.lat), float(currentLocation.lng)) log.info('main: Moving %s meters to the next position' % distance) delayUsed = 0 log.debug("Getting time") if MadGlobals.sleep: speed = self._route_manager_nighttime.settings.get("speed", 0) else: speed = self._route_manager_daytime.settings.get("speed", 0) if (speed == 0 or (settings['max_distance'] and 0 < settings['max_distance'] < distance) or (lastLocation.lat == 0.0 and lastLocation.lng == 0.0)): log.info("main: Teleporting...") # TODO: catch exception... try: self._communicator.setLocation(currentLocation.lat, currentLocation.lng, 0) curTime = math.floor(time.time()) # the time we will take as a starting point to wait for data... except WebsocketWorkerRemovedException: log.error("Timeout setting location for %s" % str(self.id)) self._stop_worker_event.set() return delayUsed = self._devicesettings.get('post_teleport_delay', 7) # Test for cooldown / teleported distance TODO: check this block... if self._devicesettings.get('cool_down_sleep', False): if distance > 2500: delayUsed = 8 elif distance > 5000: delayUsed = 10 elif distance > 10000: delayUsed = 15 log.info("Need more sleep after Teleport: %s seconds!" % str(delayUsed)) # curTime = math.floor(time.time()) # the time we will take as a starting point to wait for data... if 0 < self._devicesettings.get('walk_after_teleport_distance', 0) < distance: toWalk = get_distance_of_two_points_in_meters(float(currentLocation.lat), float(currentLocation.lng), float(currentLocation.lat) + 0.0001, float(currentLocation.lng) + 0.0001) log.info("Walking a bit: %s" % str(toWalk)) try: time.sleep(0.3) self._communicator.walkFromTo(currentLocation.lat, currentLocation.lng, currentLocation.lat + 0.0001, currentLocation.lng + 0.0001, 11) log.debug("Walking back") time.sleep(0.3) self._communicator.walkFromTo(currentLocation.lat + 0.0001, currentLocation.lng + 0.0001, currentLocation.lat, currentLocation.lng, 11) except WebsocketWorkerRemovedException: log.error("Timeout setting location for %s" % str(self.id)) self._stop_worker_event.set() return log.debug("Done walking") else: log.info("main: Walking...") try: self._communicator.walkFromTo(lastLocation.lat, lastLocation.lng, currentLocation.lat, currentLocation.lng, speed) curTime = math.floor(time.time()) # the time we will take as a starting point to wait for data... except WebsocketWorkerRemovedException: log.error("Timeout setting location for %s" % str(self.id)) self._stop_worker_event.set() return delayUsed = self._devicesettings.get('post_walk_delay', 7) log.info("Sleeping %s" % str(delayUsed)) time.sleep(float(delayUsed)) if self._applicationArgs.last_scanned: log.info('main: Set new scannedlocation in Database') # self.update_scanned_location(currentLocation.lat, currentLocation.lng, curTime) self.__add_task_to_loop(self.update_scanned_location(currentLocation.lat, currentLocation.lng, curTime)) log.debug("Acquiring lock") self._work_mutex.acquire() log.debug("Waiting for data to be received...") data_received, data_error_counter = self.wait_for_data(data_err_counter=_data_err_counter, timestamp=curTime) _data_err_counter = data_error_counter log.debug("Releasing lock") self._work_mutex.release() log.debug("Worker %s done, next iteration" % str(self.id)) t_mitm_data.join() t_asyncio_loop.join()
def _move_to_location(self): if not self._mapping_manager.routemanager_present(self._routemanager_name) \ or self._stop_worker_event.is_set(): raise InternalStopWorkerException routemanager_settings = self._mapping_manager.routemanager_get_settings( self._routemanager_name) # get the distance from our current position (last) to the next gym (cur) distance = get_distance_of_two_points_in_meters( float(self.last_location.lat), float(self.last_location.lng), float(self.current_location.lat), float(self.current_location.lng)) logger.debug('Moving {} meters to the next position', round(distance, 2)) speed = routemanager_settings.get("speed", 0) max_distance = routemanager_settings.get("max_distance", None) if (speed == 0 or (max_distance and 0 < max_distance < distance) or (self.last_location.lat == 0.0 and self.last_location.lng == 0.0)): logger.debug("main: Teleporting...") self._communicator.setLocation(self.current_location.lat, self.current_location.lng, 0) # cur_time = math.floor(time.time()) # the time we will take as a starting point to wait for data... delay_used = self.get_devicesettings_value('post_teleport_delay', 7) # Test for cooldown / teleported distance TODO: check this block... if self.get_devicesettings_value('cool_down_sleep', False): if distance > 2500: delay_used = 8 elif distance > 5000: delay_used = 10 elif distance > 10000: delay_used = 15 logger.debug("Need more sleep after Teleport: {} seconds!", str(delay_used)) # curTime = math.floor(time.time()) # the time we will take as a starting point to wait for data... if 0 < self.get_devicesettings_value( 'walk_after_teleport_distance', 0) < distance: # TODO: actually use to_walk for distance to_walk = get_distance_of_two_points_in_meters( float(self.current_location.lat), float(self.current_location.lng), float(self.current_location.lat) + 0.0001, float(self.current_location.lng) + 0.0001) logger.info("Walking a bit: {}", str(to_walk)) time.sleep(0.3) self._communicator.walkFromTo( self.current_location.lat, self.current_location.lng, self.current_location.lat + 0.0001, self.current_location.lng + 0.0001, 11) logger.debug("Walking back") time.sleep(0.3) self._communicator.walkFromTo( self.current_location.lat + 0.0001, self.current_location.lng + 0.0001, self.current_location.lat, self.current_location.lng, 11) logger.debug("Done walking") else: logger.info("main: Walking...") self._communicator.walkFromTo(self.last_location.lat, self.last_location.lng, self.current_location.lat, self.current_location.lng, speed) # cur_time = math.floor(time.time()) # the time we will take as a starting point to wait for data... delay_used = self.get_devicesettings_value('post_walk_delay', 7) logger.info("Sleeping {}", str(delay_used)) time.sleep(float(delay_used)) cur_time = time.time() self.set_devicesettings_value("last_location", self.current_location) self.last_location = self.current_location self._waittime_without_delays = time.time() return cur_time, True
def _generate_locations(distance, geofence_helper): results = [] south, east, north, west = geofence_helper.get_polygon_from_fence() corners = [ Location(south, east), Location(south, west), Location(north, east), Location(north, west) ] # get the center center = get_middle_of_coord_list(corners) # get the farthest to the center... farthest_dist = 0 for corner in corners: dist_temp = get_distance_of_two_points_in_meters( center.lat, center.lng, corner.lat, corner.lng) if dist_temp > farthest_dist: farthest_dist = dist_temp # calculate step_limit, round up to reduce risk of losing stuff step_limit = math.ceil(farthest_dist / distance) # This will loop thorugh all the rings in the hex from the centre # moving outwards log.info("Calculating positions for init scan") num_cores = multiprocessing.cpu_count() with multiprocessing.Pool(processes=num_cores) as pool: temp = [ pool.apply(S2Helper._generate_star_locs, args=(center, distance, i)) for i in range(1, step_limit) ] results = [item for sublist in temp for item in sublist] results.append(Location(center.lat, center.lng)) # for ring in range(1, step_limit): # for i in range(0, 6): # # Star_locs will contain the locations of the 6 vertices of # # the current ring (90,150,210,270,330 and 30 degrees from # # origin) to form a star # star_loc = S2Helper.get_new_coords(center, distance * ring, # 90 + 60 * i) # for j in range(0, ring): # # Then from each point on the star, create locations # # towards the next point of star along the edge of the # # current ring # loc = S2Helper.get_new_coords(star_loc, distance * j, 210 + 60 * i) # results.append(loc) log.info("Filtering positions for init scan") # Geofence results. if geofence_helper is not None and geofence_helper.is_enabled(): results = geofence_helper.get_geofenced_coordinates(results) if not results: log.error('No cells regarded as valid for desired scan area. ' 'Check your provided geofences. Aborting.') sys.exit(1) log.info("Ordering location") results = S2Helper.order_location_list_rows(results) return results