Example #1
0
def main_thread():
    global nextRaidQueue
    global lastPogoRestart
    global telnMore
    global pogoWindowManager
    global sleep
    global runWarningThreadEvent
    global windowLock
    global screenWrapper
    global lastScreenshotTaken

    log.info("main: Starting TelnetGeo Client")
    telnGeo = TelnetGeo(str(args.tel_ip), args.tel_port,
                        str(args.tel_password), args.tel_timeout_command,
                        args.tel_timeout_socket)

    log.info("main: Starting dbWrapper")
    dbWrapper = DbWrapper(str(args.db_method), str(args.dbip), args.dbport,
                          args.dbusername, args.dbpassword, args.dbname,
                          args.timezone)
    updateRaidQueue(dbWrapper)
    lastRaidQueueUpdate = time.time()

    if lastPogoRestart is None:
        lastPogoRestart = time.time()

    route = getJsonRoute(args.file, args.gym_distance,
                         args.max_count_gym_sum_up_around_gym)

    log.info("main: Route to be taken: %s, amount of coords: %s" %
             (str(route), str(len(route))))
    log.info("main: Max_distance before teleporting: %s" % args.max_distance)
    log.info("main: Checking if screen is on and pogo is running")

    if not sleep:
        turnScreenOnAndStartPogo()

    emptycount = 0
    locationCount = 0
    while True:
        log.info("main: Next round")
        curLat = 0.0
        curLng = 0.0
        i = 0  # index in route
        failcount = 0
        lastRoundEggHatch = False

        # loop over gyms:
        # walk to next gym
        # get to raidscreen
        # take screenshot
        # check time to restart pogo

        # process the entire route, prioritize hatched eggs in every second round (if anything has hatched)
        while i < len(route):
            while sleep:
                time.sleep(1)
            curTime = time.time()
            # update the raid queue every 5mins...
            if (curTime - lastRaidQueueUpdate) >= (5 * 60):
                updateRaidQueue(dbWrapper)
                lastRaidQueueUpdate = curTime

            # Restart pogo every now and then...
            if args.restart_pogo > 0:
                #log.debug("main: Current time - lastPogoRestart: %s" % str(curTime - lastPogoRestart))
                # if curTime - lastPogoRestart >= (args.restart_pogo * 60):
                locationCount += 1
                if locationCount > args.restart_pogo:
                    log.error("scanned " + str(args.restart_pogo) +
                              " locations, restarting pogo")
                    restartPogo()
                    locationCount = 0

            # let's check for speed and weather warnings while we're walking/teleporting...
            runWarningThreadEvent.set()
            lastLat = curLat
            lastLng = curLng
            egghatchLocation = False
            log.debug(
                "main: Checking for raidqueue priority. Current time: %s, Current queue: %s"
                % (str(time.time()), str(nextRaidQueue)))
            # determine whether we move to the next gym or to the top of our priority queue
            if not lastRoundEggHatch and len(
                    nextRaidQueue) > 0 and nextRaidQueue[0][0] < time.time():
                # the topmost item in the queue lays in the past...
                log.info(
                    'main: An egg has hatched, get there asap. Location: %s' %
                    str(nextRaidQueue[0]))
                egghatchLocation = True
                nextStop = heapq.heappop(nextRaidQueue)[
                    1]  # gets the location tuple
                curLat = nextStop.latitude
                curLng = nextStop.longitude
                time.sleep(1)
                lastRoundEggHatch = True
            else:
                # continue as usual
                log.info('main: Moving on with gym at %s' % route[i])
                curLat = route[i]['lat']
                curLng = route[i]['lng']
                # remove whitespaces that might be on either side...
                i += 1
                lastRoundEggHatch = False

            log.debug("main: next stop: %s, %s" % (str(curLat), str(curLng)))
            log.debug(
                'main: LastLat: %s, LastLng: %s, CurLat: %s, CurLng: %s' %
                (lastLat, lastLng, curLat, curLng))
            # get the distance from our current position (last) to the next gym (cur)
            distance = getDistanceOfTwoPointsInMeters(float(lastLat),
                                                      float(lastLng),
                                                      float(curLat),
                                                      float(curLng))
            log.info('main: Moving %s meters to the next position' % distance)
            delayUsed = 0
            if (args.speed == 0 or (args.max_distance and args.max_distance > 0
                                    and distance > args.max_distance)
                    or (lastLat == 0.0 and lastLng == 0.0)):
                log.info("main: Teleporting...")
                telnGeo.setLocation(curLat, curLng, 0)
                delayUsed = args.post_teleport_delay
            else:
                log.info("main: Walking...")
                telnGeo.walkFromTo(lastLat, lastLng, curLat, curLng,
                                   args.speed)
                delayUsed = args.post_walk_delay
            time.sleep(delayUsed)

            # ok, we should be at the next gym, check for errors and stuff
            # TODO: improve errorhandling by checking results and trying again and again
            # not using continue to always take a new screenshot...
            log.debug("main: Clearing event, acquiring lock")
            runWarningThreadEvent.clear()
            windowLock.acquire()
            log.debug("main: Lock acquired")
            log.debug("main: Checking if pogo is running...")
            if not telnMore.isPogoTopmost():
                log.warning("main: Starting Pogo")
                startPogo(False)
                windowLock.release()
                continue

            while not getToRaidscreen(12):
                if failcount > 5:
                    log.fatal(
                        "main: failed to find raidscreen way too often. Exiting"
                    )
                    sys.exit(1)
                failcount += 1
                log.error(
                    "main: Failed to find the raidscreen multiple times in a row. Stopping pogo and taking a "
                    "break of 5 minutes")
                stopPogo()
                time.sleep(300)
                startPogo(False)
            failcount = 0

            # well... we are on the raidtab, but we want to reopen it every now and then, so screw it
            reopenedRaidTab = False
            # if not egghatchLocation and math.fmod(i, 30) == 0:
            #    log.warning("main: Closing and opening raidtab every 30 locations scanned... Doing so")
            #    reopenRaidTab()
            #    tabOutAndInPogo()
            #    screenWrapper.getScreenshot('screenshot.png')
            #    reopenedRaidTab = True

            if args.last_scanned:
                log.info('main: Set new scannedlocation in Database')
                dbWrapper.setScannedLocation(str(curLat), str(curLng),
                                             str(curTime))

            log.info(
                "main: Checking raidcount and copying raidscreen if raids present"
            )
            countOfRaids = pogoWindowManager.readRaidCircles(
                'screenshot.png', 123)
            if countOfRaids == -1 and not reopenedRaidTab:
                # reopen raidtab and take screenshot...
                log.warning(
                    "main: Count present but no raid shown, reopening raidTab")
                reopenRaidTab()
                tabOutAndInPogo()
                screenWrapper.getScreenshot('screenshot.png')
                countOfRaids = pogoWindowManager.readRaidCircles(
                    'screenshot.png', 123)
        #    elif countOfRaids == 0:
        #        emptycount += 1
        #        if emptycount > 30:
        #            emptycount = 0
        #            log.error("Had 30 empty scans, restarting pogo")
        #            restartPogo()
            log.debug("main: countOfRaids: %s" % str(countOfRaids))
            if countOfRaids > 0:
                curTime = time.time()
                copyfile(
                    'screenshot.png', args.raidscreen_path + '/raidscreen_' +
                    str(curTime) + "_" + str(curLat) + "_" + str(curLng) +
                    "_" + str(countOfRaids) + '.png')
            log.debug("main: Releasing lock")
            windowLock.release()
Example #2
0
def main_thread():
    global nextRaidQueue
    global lastPogoRestart
    global telnMore
    global pogoWindowManager
    global sleep
    global runWarningThreadEvent
    global windowLock
    global screenWrapper
    global lastScreenshotTaken
    global lastScreenHash
    global lastScreenHashCount

    log.info("main: Starting TelnetGeo Client")
    telnGeo = TelnetGeo(str(args.tel_ip), args.tel_port,
                        str(args.tel_password), args.tel_timeout_command,
                        args.tel_timeout_socket)

    log.info("main: Starting dbWrapper")
    dbWrapper = DbWrapper(str(args.db_method), str(args.dbip), args.dbport,
                          args.dbusername, args.dbpassword, args.dbname,
                          args.timezone)
    updateRaidQueue(dbWrapper)
    lastRaidQueueUpdate = time.time()

    if lastPogoRestart is None:
        lastPogoRestart = time.time()

    route = getJsonRoute(args.file, args.gym_distance,
                         args.max_count_gym_sum_up_around_gym, args.route_file)

    log.info("main: Route to be taken: %s, amount of coords: %s" %
             (str(route), str(len(route))))
    log.info("main: Max_distance before teleporting: %s" % args.max_distance)
    log.info("main: Checking if screen is on and pogo is running")

    if not sleep:
        if args.no_initial_restart is False:
            turnScreenOnAndStartPogo()
        else:
            startPogo()

    log.info('Starting speedweatherWarning Thread....')
    w = Thread(target=checkSpeedWeatherWarningThread, name='speedWeatherCheck')
    w.daemon = True
    w.start()

    emptycount = 0
    locationCount = 0
    while True:
        log.info("main: Next round")
        curLat = 0.0
        curLng = 0.0
        i = 0  # index in route
        failcount = 0
        lastRoundEggHatch = False

        # loop over gyms:
        # walk to next gym
        # get to raidscreen
        # take screenshot
        # check time to restart pogo

        # process the entire route, prioritize hatched eggs in every second round (if anything has hatched)
        while i < len(route):
            while sleep:
                time.sleep(1)
            curTime = time.time()
            # update the raid queue every 5mins...
            if (curTime - lastRaidQueueUpdate) >= (5 * 60):
                updateRaidQueue(dbWrapper)
                lastRaidQueueUpdate = curTime

            windowLock.acquire()
            # Restart pogo every now and then...
            if args.restart_pogo > 0:
                # log.debug("main: Current time - lastPogoRestart: %s" % str(curTime - lastPogoRestart))
                # if curTime - lastPogoRestart >= (args.restart_pogo * 60):
                locationCount += 1
                if locationCount > args.restart_pogo:
                    log.error("scanned " + str(args.restart_pogo) +
                              " locations, restarting pogo")
                    restartPogo()
                    locationCount = 0
            windowLock.release()

            # let's check for speed and weather warnings while we're walking/teleporting...
            runWarningThreadEvent.set()
            lastLat = curLat
            lastLng = curLng
            egghatchLocation = False
            log.debug(
                "main: Checking for raidqueue priority. Current time: %s, Current queue: %s"
                % (str(time.time()), str(nextRaidQueue)))
            # determine whether we move to the next gym or to the top of our priority queue
            if not lastRoundEggHatch and len(
                    nextRaidQueue) > 0 and nextRaidQueue[0][0] < time.time():
                # the topmost item in the queue lays in the past...
                log.info(
                    'main: An egg has hatched, get there asap. Location: %s' %
                    str(nextRaidQueue[0]))
                egghatchLocation = True
                nextStop = heapq.heappop(nextRaidQueue)[
                    1]  # gets the location tuple
                curLat = nextStop.latitude
                curLng = nextStop.longitude
                time.sleep(1)
                lastRoundEggHatch = True
            else:
                # continue as usual
                log.info('main: Moving on with gym at %s' % route[i])
                curLat = route[i]['lat']
                curLng = route[i]['lng']
                # remove whitespaces that might be on either side...
                i += 1
                lastRoundEggHatch = False

            # store current position in file
            posfile = open(args.position_file + '.position', "w")
            posfile.write(str(curLat) + ", " + str(curLng))
            posfile.close()

            log.debug("main: next stop: %s, %s" % (str(curLat), str(curLng)))
            log.debug(
                'main: LastLat: %s, LastLng: %s, CurLat: %s, CurLng: %s' %
                (lastLat, lastLng, curLat, curLng))
            # get the distance from our current position (last) to the next gym (cur)
            distance = getDistanceOfTwoPointsInMeters(float(lastLat),
                                                      float(lastLng),
                                                      float(curLat),
                                                      float(curLng))
            log.info('main: Moving %s meters to the next position' % distance)
            delayUsed = 0
            if (args.speed == 0
                    or (args.max_distance and 0 < args.max_distance < distance)
                    or (lastLat == 0.0 and lastLng == 0.0)):
                log.info("main: Teleporting...")
                telnGeo.setLocation(curLat, curLng, 0)
                delayUsed = args.post_teleport_delay
                # Test for cooldown / teleported distance
                if args.cool_down_sleep:
                    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 < args.walk_after_teleport_distance < distance:
                    toWalk = getDistanceOfTwoPointsInMeters(
                        float(curLat), float(curLng),
                        float(curLat) + 0.0001,
                        float(curLng) + 0.0001)
                    log.error("Walking a bit: %s" % str(toWalk))
                    time.sleep(0.3)
                    telnGeo.walkFromTo(curLat, curLng, curLat + 0.0001,
                                       curLng + 0.0001, 11)
                    log.debug("Walking back")
                    time.sleep(0.3)
                    telnGeo.walkFromTo(curLat + 0.0001, curLng + 0.0001,
                                       curLat, curLng, 11)
                    log.debug("Done walking")
            else:
                log.info("main: Walking...")
                telnGeo.walkFromTo(lastLat, lastLng, curLat, curLng,
                                   args.speed)
                delayUsed = args.post_walk_delay
            log.info("Sleeping %s" % str(delayUsed))
            time.sleep(delayUsed)

            # ok, we should be at the next gym, check for errors and stuff
            # TODO: improve errorhandling by checking results and trying again and again
            # not using continue to always take a new screenshot...
            log.debug("main: Acquiring lock")

            while sleep or not runWarningThreadEvent.isSet():
                time.sleep(0.1)
            windowLock.acquire()
            log.debug("main: Lock acquired")
            if not takeScreenshot():
                windowLock.release()
                continue

            if args.last_scanned:
                log.info('main: Set new scannedlocation in Database')
                dbWrapper.setScannedLocation(str(curLat), str(curLng),
                                             str(curTime))

            log.info(
                "main: Checking raidcount and copying raidscreen if raids present"
            )
            countOfRaids = pogoWindowManager.readRaidCircles(
                os.path.join(args.temp_path, 'screenshot.png'), 123)
            if countOfRaids == -1:
                # reopen raidtab and take screenshot...
                log.warning(
                    "main: Count present but no raid shown, reopening raidTab")
                reopenRaidTab()
                # tabOutAndInPogo()
                if not takeScreenshot():
                    windowLock.release()
                    continue
                countOfRaids = pogoWindowManager.readRaidCircles(
                    os.path.join(args.temp_path, 'screenshot.png'), 123)
            #    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 args.weather:
                weather = checkWeather(
                    os.path.join(args.temp_path, 'screenshot.png'))
                if weather[0]:
                    log.debug('Submit Weather')
                    dbWrapper.updateInsertWeather(curLat, curLng, weather[1],
                                                  curTime)
                else:
                    log.error('Weather could not detected')

            if countOfRaids > 0:
                log.debug(
                    "main: New und old Screenshoot are different - starting OCR"
                )
                log.debug("main: countOfRaids: %s" % str(countOfRaids))
                curTime = time.time()
                copyFileName = args.raidscreen_path + '/raidscreen_' + str(
                    curTime) + "_" + str(curLat) + "_" + str(
                        curLng) + "_" + str(countOfRaids) + '.png'
                log.debug('Copying file: ' + copyFileName)
                copyfile(os.path.join(args.temp_path, 'screenshot.png'),
                         copyFileName)
                os.remove(os.path.join(args.temp_path, 'screenshot.png'))

            log.debug("main: Releasing lock")
            windowLock.release()
Example #3
0
def main_thread():
    global nextRaidQueue
    global lastPogoRestart
    global telnMore
    global sleep
    log.info("Starting VNC client")
    vncWrapper = VncWrapper(str(args.vnc_ip, ), 1, args.vnc_port,
                            args.vnc_password)
    log.info("Starting TelnetGeo Client")
    telnGeo = TelnetGeo(str(args.tel_ip), args.tel_port,
                        str(args.tel_password))
    #log.info("Starting Telnet MORE Client")
    #telnMore = TelnetMore(str(args.tel_ip), args.tel_port, str(args.tel_password))
    log.info("Starting pogo window manager")
    pogoWindowManager = PogoWindows(str(args.vnc_ip, ), 1, args.vnc_port,
                                    args.vnc_password, args.screen_width,
                                    args.screen_height, args.temp_path)
    log.info("Starting dbWrapper")
    dbWrapper = DbWrapper(str(args.dbip), args.dbport, args.dbusername,
                          args.dbpassword, args.dbname, args.timezone)
    updateRaidQueue(dbWrapper)

    route = getJsonRoute(args.file)
    lastPogoRestart = time.time()
    lastRaidQueueUpdate = time.time()
    log.info("Route to be taken: %s, amount of coords: %s" %
             (str(route), str(len(route))))
    #sys.exit(0)
    log.info("Max_distance before teleporting: %s" % args.max_distance)
    log.info("Checking if screen is on and pogo is running")

    if not sleep:
        turnScreenOnAndStartPogo()
    #sys.exit(0)
    while True:
        log.info("Next round")
        lastLat = 0.0
        lastLng = 0.0
        curLat = 0.0
        curLng = 0.0
        #loop over gyms:
        #walk to next gym
        #check errors (anything not raidscreen)
        #get to raidscreen (with the above command)
        #take screenshot and store coords in exif with it
        #check time to restart pogo and reset google play services
        i = 0  #index, iterating with it to either get to the next gym or the priority of our queue
        failcount = 0
        while i < len(route):
            while sleep:
                time.sleep(1)
                #TODO: check if not sleep -> start pogo, if sleep, stop it
            curTime = time.time()
            #update the raid queue every 5mins...
            if (curTime - lastRaidQueueUpdate) >= (5 * 60):
                updateRaidQueue(dbWrapper)
                lastRaidQueueUpdate = curTime

            #we got the latest raids. To avoid the mobile from killing apps,
            #let's restart pogo every 2hours or whatever TODO: consider args
            log.debug("Current time - lastPogoRestart: %s" %
                      str(curTime - lastPogoRestart))
            if (curTime - lastPogoRestart >= (120 * 60)):
                restartPogo()

            lastLat = curLat
            lastLng = curLng
            log.debug(
                "Checking for raidqueue priority. Current time: %s, Current queue: %s"
                % (str(time.time()), str(nextRaidQueue)))
            #determine whether we move to the next gym or to the top of our priority queue
            if (len(nextRaidQueue) > 0 and nextRaidQueue[0][0] < time.time()):
                #the topmost item in the queue lays in the past...
                log.info('An egg has hatched, get there asap. Location: %s' %
                         str(nextRaidQueue[0]))
                nextStop = heapq.heappop(nextRaidQueue)[
                    1]  #gets the location tuple
                curLat = nextStop.latitude
                curLng = nextStop.longitude
                time.sleep(1)
            else:
                #continue as usual
                log.info('Moving on with gym at %s' % route[i])
                curLat = route[i]['lat']
                curLng = route[i]['lng']
                #remove whitespaces that might be on either side...
                #curLat = curLat.strip()
                #curLng = curLng.strip()
                i += 1

            log.debug("next stop: %s, %s" % (str(curLat), str(curLng)))
            log.debug('LastLat: %s, LastLng: %s, CurLat: %s, CurLng: %s' %
                      (lastLat, lastLng, curLat, curLng))
            #get the distance from our current position (last) to the next gym (cur)
            distance = getDistanceOfTwoPointsInMeters(float(lastLat),
                                                      float(lastLng),
                                                      float(curLat),
                                                      float(curLng))
            log.info('Moving %s meters to the next position' % distance)
            if (args.speed == 0
                    or (args.max_distance and distance > args.max_distance)
                    or (lastLat == 0.0 and lastLng == 0.0)):
                log.info("Teleporting...")
                telnGeo.setLocation(curLat, curLng, 0)
                time.sleep(4)
            else:
                log.info('Walking...')
                telnGeo.walkFromTo(lastLat, lastLng, curLat, curLng,
                                   args.speed)
                time.sleep(2)

            #ok, we should be at the next gym, check for errors and stuff
            #TODO: improve errorhandling by checking results and trying again and again
            #not using continue to always take a new screenshot...
            #time.sleep(5)

            log.info(
                "Attempting to retrieve screenshot before checking windows")
            if (not vncWrapper.getScreenshot('screenshot.png')):
                log.error(
                    "Failed retrieving screenshot before checking windows")
                break
                #failcount += 1
                #TODO: consider proper errorhandling?
                #even restart entire thing? VNC dead means we won't be using the device
                #maybe send email? :D
                #break;
            attempts = 0
            while (not pogoWindowManager.checkRaidscreen(
                    'screenshot.png', 123)):
                if (attempts >= 15):
                    #weird count of failures... stop pogo, wait 5mins and try again, could be PTC login issue
                    telnMore.stopApp("com.nianticlabs.pokemongo")
                    time.sleep(360)
                    turnScreenOnAndStartPogo()
                    #restartPogo()
                    attempts = 0
                #not using continue since we need to get a screen before the next round... TODO: consider getting screen for checkRaidscreen within function
                found = pogoWindowManager.checkPostLoginOkButton(
                    'screenshot.png', 123)
                if not found and pogoWindowManager.checkCloseExceptNearbyButton(
                        'screenshot.png', 123):
                    log.info(
                        "Found close button (X) on a window other than nearby")
                    found = True
                if not found and pogoWindowManager.checkSpeedwarning(
                        'screenshot.png', 123):
                    log.info("Found speed warning")
                    found = True
                if not found and pogoWindowManager.checkPostLoginNewsMessage(
                        'screenshot.png', 123):
                    log.info("Found post login news message")
                    found = True
                if not found and pogoWindowManager.checkGameQuitPopup(
                        'screenshot.png', 123):
                    log.info("Found game quit popup")
                    found = True

                log.info("Previous checks found popups: %s" % str(not found))
                if not found:
                    log.info(
                        "Previous checks found nothing. Checking nearby open")
                    pogoWindowManager.checkNearby('screenshot.png', 123)
                try:
                    log.info(
                        "Attempting to retrieve screenshot checking windows")
                    vncWrapper.getScreenshot('screenshot.png')
                except:
                    log.error(
                        "Failed getting screenshot while checking windows")
                    #failcount += 1
                    #TODO: consider proper errorhandling?
                    #even restart entire thing? VNC dead means we won't be using the device
                    #maybe send email? :D
                    break

                vncWrapper.getScreenshot('screenshot.png')

                #TODO: take screenshot of raidscreen?
                #we should now see the raidscreen, let's take a screenshot of it
                time.sleep(1)
                attempts += 1
            log.info("Saving raid screenshot")
            countOfRaids = pogoWindowManager.readAmountOfRaids(
                'screenshot.png', 123)
            if countOfRaids > 0:
                curTime = time.time()
                copyfile(
                    'screenshot.png', args.raidscreen_path + '/raidscreen_' +
                    str(curTime) + "_" + str(countOfRaids) + '.png')