コード例 #1
0
class MovementInterface:
    def __init__(self, stepper_pins, servo1_pin, servo2_pin):
        GPIO.setmode(GPIO.BCM)
        self.servo1 = Servo(servo1_pin)  # Серво сверху
        self.servo2 = Servo(servo2_pin)  # Серво снизу
        self.stepper = Stepper(stepper_pins)

    def shot(self):
        self.servo2.set_servo_angle(0)

    def prepare(self):
        self.servo2.set_servo_angle(0)
        self.servo1.set_servo_angle(-20, hold=True)
        for angle in range(-20, 160):
            duty_cycle = angle / 20 + 3.
            self.servo1.servo_pwm.ChangeDutyCycle(duty_cycle)
            sleep(0.0125)
        sleep(2)
        for angle in range(160, 127, -1):
            duty_cycle = angle / 20 + 3.
            self.servo1.servo_pwm.ChangeDutyCycle(duty_cycle)
            sleep(0.0125)
        self.servo2.set_servo_angle(0)
        self.servo2.set_servo_angle(-30)
        self.servo1.set_servo_angle(-20)


    def turn(self, degree_value):
        self.stepper.turn_degree(degree_value)
コード例 #2
0
ファイル: pump.py プロジェクト: bambooSocks/db4-group5
    def __init__(self, step_pin):
        self.stepper = Stepper(step_pin, None)
        self.isRunning = False

        self.maxSpeedDelay = 100
        self.minSpeedDelay = 2000
        self.setSpeed(0)
コード例 #3
0
    def __init__(self):
        GPIO.setup(self.HOME_DOWN_GPIO, GPIO.IN, pull_up_down = GPIO.PUD_UP)
        GPIO.setup(self.HOME_UP_GPIO, GPIO.IN, pull_up_down = GPIO.PUD_UP)
        self.__stepper = Stepper(self.MICROSTEPS * self.GEAR_RATIO, self.DIRECTION_GPIO, self.PULSE_GPIO, self.BACKLASH_STEPS)

        steps = 0
        while self.is_home_down():
            self.__stepper.pulse(self.UP_DIRECTION)
            steps += 1
            if (steps > self.__stepper.total_steps()):
                raise ValueError("Cannot home the elevation stepper. It is likely not moving or the sensor is broken.")
        while not self.is_home_down():
            self.__stepper.pulse(self.DOWN_DIRECTION)
            steps += 1
            if (steps > self.__stepper.total_steps()):
                raise ValueError("Cannot home the elevation stepper. It is likely not moving or the sensor is broken.")

        steps = 0
        self.__amplitude = 0
        while not self.is_home_up():
            self.__stepper.pulse(self.UP_DIRECTION)
            steps += 1
            self.__amplitude += 1
            if (steps > self.__stepper.total_steps()):
                raise ValueError("Cannot home the elevation stepper. It is likely not moving or the sensor is broken.")
        self.__stepper.reset_position()
コード例 #4
0
ファイル: pump.py プロジェクト: bambooSocks/db4-group5
class VariablePump:
    def __init__(self, step_pin):
        self.stepper = Stepper(step_pin, None)
        self.isRunning = False

        self.maxSpeedDelay = 100
        self.minSpeedDelay = 2000
        self.setSpeed(0)

    # speed is float between 0 - 1
    def setSpeed(self, speed):
        assert (speed <= 1) and (speed >= 0)

        speedRange = self.minSpeedDelay - self.maxSpeedDelay
        speedDelay = self.minSpeedDelay - (speedRange * speed)
        self.stepper.set_step_time(speedDelay)

    # do not use outside of the class
    def __loop(self):
        while self.isRunning:
            self.stepper.steps(1000)

    def startMotor(self):
        self.isRunning = True
        _thread.start_new_thread(self.__loop, ())

    def stopMotor(self):
        self.isRunning = False
コード例 #5
0
    def __init__(self):
        self.is_initialized = False
        rospy.init_node('manipulator_interface', anonymous=False)
        self.sub = rospy.Subscriber('manipulator_command', Manipulator,
                                    self.callback)

        rospy.on_shutdown(self.shutdown)

        try:
            self.claw_stepper = Stepper(STEPPER_NUM_STEPS, STEPPER_CLAW_PINS,
                                        STEPPER_CLAW_PWM_PINS, COMPUTER)
            self.claw_direction = 0
            self.vertical_stepper = Stepper(STEPPER_NUM_STEPS,
                                            STEPPER_VERTICAL_PINS,
                                            STEPPER_VERTICAL_PWM_PINS,
                                            COMPUTER)
            self.vertical_stepper_direction = 0
        except NameError:
            rospy.logfatal(
                'Could not initialize stepper.py. Is /computer parameter set correctly? '
                'Shutting down node...')
            rospy.signal_shutdown('')

        self.claw_stepper.disable()
        self.vertical_stepper.disable()

        rospy.loginfo('Initialized with {0} RPM steppers.'.format(STEPPER_RPM))
        self.is_initialized = True
        self.spin()
コード例 #6
0
class AzimuthController:
    DIRECTION_GPIO = 38
    PULSE_GPIO = 40
    HOME_GPIO = 22
    MICROSTEPS = 400
    GEAR_RATIO = 48
    LEFT_DIRECTION = True
    RIGHT_DIRECTION = not LEFT_DIRECTION
    HOMING_DIRECTION = LEFT_DIRECTION
    BACKLASH_STEPS = 12

    def __init__(self):
        GPIO.setup(self.HOME_GPIO, GPIO.IN, pull_up_down = GPIO.PUD_UP)
        self.__stepper = Stepper(self.MICROSTEPS * self.GEAR_RATIO, self.DIRECTION_GPIO, self.PULSE_GPIO, self.BACKLASH_STEPS)

        steps = 0
        while self.is_home():
            self.__stepper.pulse(self.HOMING_DIRECTION)
            steps += 1
            if (steps > self.total_steps()):
                raise ValueError("Cannot home the azimuth stepper. It is likely not moving or the sensor is broken.")
        while not self.is_home():
            self.__stepper.pulse(self.HOMING_DIRECTION)
            steps += 1
            if (steps > self.total_steps()):
                raise ValueError("Cannot home the azimuth stepper. It is likely not moving or the sensor is broken.")
        self.__stepper.reset_position()

    def is_home(self):
        return not GPIO.input(self.HOME_GPIO)

    def position(self):
        return self.__stepper.position()

    def total_steps(self):
        return self.__stepper.total_steps()

    def move_left(self, steps):
        return self.move(self.LEFT_DIRECTION, steps)

    def move_right(self, steps):
        return self.move(self.RIGHT_DIRECTION, steps)

    def move(self, direction, steps):
        self.__stepper.move(direction, steps)
        return True

    def move_to(self, position, max_steps = sys.maxint):
        if position < 0 or position >= self.total_steps():
            raise ValueError("Invalid position")

        steps_from_left = (position - self.position()) % self.total_steps()
        steps_from_right = (self.position() - position) % self.total_steps()

        if steps_from_left <= steps_from_right:
            self.move(self.LEFT_DIRECTION, min(steps_from_left, max_steps))
            return steps_from_left <= max_steps
        else:
            self.move(self.RIGHT_DIRECTION, min(steps_from_right, max_steps))
            return steps_from_right <= max_steps
コード例 #7
0
class Shelly(BaseTurtle):

    bipolar1 = Stepper()
    bipolar2 = Stepper(2)

    def __init__(self):
        self.readingarray = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

    def start(self):
        rcpy.set_state(rcpy.RUNNING)
        time.sleep(.5)
        mpu9250.initialize(enable_magnetometer=False)
        time.sleep(.5)

    def reset(self):
        self.xyz = [0, 0, 0]
        return 0

    def move(self, action_vector):

        t_0 = time.time()
        t_stop = t_0 + 0.50
        t_sensing = t_0 + 0.10  # was .25
        t1 = t_0

        max_accel = [0, 0, 0]
        min_accel = [0, 0, 0]
        sum_accel = [0, 0, 0]

        max_gyro = [0, 0, 0]
        min_gyro = [0, 0, 0]
        motor.motor1.set(action_vector[0] * 0.35)
        motor.motor2.set(action_vector[1] * 0.36)
        count = 0
        while t1 <= t_stop:
            if t1 <= t_sensing:
                data = mpu9250.read()
                max_accel = np.maximum(max_accel, data['accel'])
                min_accel = np.minimum(min_accel, data['accel'])
                sum_accel = np.add(data['accel'], sum_accel)
                max_gyro = np.maximum(max_gyro, data['gyro'])
                min_gyro = np.minimum(min_gyro, data['gyro'])
                count += 1
            t1 = time.time()

        motor.motor1.set(action_vector[0] * 0.00)
        motor.motor2.set(action_vector[1] * 0.00)
        if max_gyro[Z] > 100.0:
            return 'TL'
        elif min_gyro[Z] < -100.0:  # was -150
            return 'TR'
        elif sum_accel[1] > 0:
            return 'F'
        else:
            return 'R'

    def stop(self):
        rcpy.exit()
コード例 #8
0
def test_stepper():
    A = 18
    B = 23
    C = 24
    D = 25

    stepper = Stepper(A, B, C, D)
    stepper.do_full_turn()
    time.sleep(1)
コード例 #9
0
ファイル: tastaturMove.py プロジェクト: gatzo23/roboterCar
 def __init__(self):
     Thread.__init__(self)
     self.window = curses.initscr()
     #Klasse für die drei Schrittmotoren
     self.stepperMotor = Stepper()
     self.wheels = Wheel()
     curses.noecho()
     self.window.keypad(True)
     self.daemon = True
     self.start()
コード例 #10
0
ファイル: handyMove.py プロジェクト: gatzo23/roboterCar
 def __init__(self, dataFromClient, socketConnection):
     Thread.__init__(self)
     self.dataFromClient = dataFromClient
     self.komm_handy = socketConnection
     self.motorCamera = Stepper()
     self.wheels = Wheel()
     # angabe wie gerade gefahren wird. 0=halt 1=vorwärts 2=rückwärts 3=links 4=rechts
     self.richtung = 0
     self.verglRichtung1 = 90  # der Motor startet bei 90Grad in der Mitte
     self.verglRichtung2 = 90  # der Motor startet bei 90Grad in der Mitte
     self.daemon = True
     self.start()
コード例 #11
0
def setup():
	global Light
	Light = mraa.Gpio(8)  
	Light.dir(mraa.DIR_OUT) 

	global sensorPin
	sensorPin = mraa.Aio(5)

	global BaseStepper
	BaseStepper = Stepper(10,11,9,'eighth_step')

	global ReceiverStepper
	ReceiverStepper = Stepper(7,6,2,'eighth_step')
	ReceiverStepper.rotateMotor(45)
コード例 #12
0
ファイル: solver.py プロジェクト: 5l1v3r1/sndust
 def __init__(self, spec: SolverSpec, stepper: Stepper):
     self._ode = spec.integrator(stepper, spec.time_start, stepper.initial_value(), spec.time_bound, max_step=spec.max_timestep, \
                                     atol=spec.absolute_tol, rtol=spec.relative_tol, vectorized=False)
     self._steps = 0
     self._avg_steptime = 0.0
     self._tot_steptime = 0.0
     self._stepper = stepper
コード例 #13
0
    def __init__(self, debug=False):
        """
        0 : pallete
        1 : Cyan
        2 : Magenta
        3 : Yellow
        4 : Black
        5 : White
        """
        self.palettePosition = 0
        self.stepsPerCup = 63.3333
        self.maxPalettePosition = 19 * self.stepsPerCup
        self.palette_colors = {}
        self.debug = debug
        self.activeCup = 0

        # self.mixerStepper = StepperBasic(12,6,13,19)

        if debug:
            self.steppers = []
            self.steppers.append(Stepper(0))
            for i in range(1, 5):
                self.steppers.append(StepperTest(i))

        # set up position switches for the mixer arm
        for pin in [18, 26]:
            GPIO.setup(pin, GPIO.IN)
            #print("testing pin {}".format(pin))
            val = GPIO.input(pin)
            #print(pin, val)
        for out_pin in self.pin_list:
            GPIO.setup(out_pin, GPIO.OUT)
            GPIO.output(out_pin, GPIO.LOW)
コード例 #14
0
def setup():
	global LED
	LED = mraa.Gpio(7)  
	LED.dir(mraa.DIR_OUT) 

	global Light
	Light = mraa.Gpio(8)  
	Light.dir(mraa.DIR_OUT) 

	global sensorPin
	sensorPin = mraa.Aio(5)

	global BaseStepper
	BaseStepper = Stepper(7,6,2)

	global ReceiverStepper
	ReceiverStepper = Stepper(10,11,9)
コード例 #15
0
def move_a_bit(a):
    stepper = Stepper(a, 2000, 1000)

    df = pd.DataFrame(index=np.arange(0, 1500 * 2),
                      columns=('v', 's', 'd', 't'))

    t = 0.0
    s = 0
    try:
        stepper.target_pos = 1500
        while True:
            d = stepper.step()
            m = 1 << stepper.micro
            if d == 0 or stepper.pos / m >= 300:
                stepper.set_target_speed(6000)
                break
            t += d
            df.loc[s] = [1e6 / d / m, stepper.pos / m, d / 1e6, t / 1e6]
            s += 1
        while True:
            d = stepper.step()
            m = 1 << stepper.micro
            if d == 0:
                break
            if 1e6 / d / m < 200:
                i = 1
            df.loc[s] = [1e6 / d / m, stepper.pos / m, d / 1e6, t / 1e6]
            t += d
            s += 1
    except:
        print("FAIL")
    return df.dropna()
コード例 #16
0
def stepper_move(steps,dir,speed):
    #stepper variables
    # [stepPin, directionPin, enablePin]
    #print steps
    testStepper = Stepper([24, 22, 23])
    if dir in VALID_MOVE_DIR:
        #test stepper
        testStepper.step(steps, dir,speed) #steps, dir, speed, stayOn
        data={"Stepper move": "done",
         "dir": dir,
         "steps": steps,
         "speed": speed
         }
    else:
        data={'Move': 'ERROR',
            'error': 'Invalid direction.'}

    return data
コード例 #17
0
ファイル: bot.py プロジェクト: yuanchenyang/PokemonGo-Bot
 def start(self):
     self._setup_logging()
     self._setup_api()
     if self.config.stats:
         ## exit early and just show stats
         print '[ stats mode, exiting ... ]'
         exit()
     self.stepper = Stepper(self)
     random.seed()
コード例 #18
0
ファイル: hardware.py プロジェクト: Fips22/smart-irrigation
    def __init__(self, configFile="hardware.cfg", config=None):

        if config == None:

            f = open('hardware.cfg')

            hardconfobj = ujson.loads(f.read())

            self.config = hardconfobj["valve"]

            f.close()

        else:
            self.config = config

        #self.config["homeSencePin"]
        #self.config["homePosToValve"] in mm
        #self.config["valveToValve"] in mm
        #self.config["valveAmmount"]
        #self.config["maxSteps"]

        # mm von ventil zu ventil * schritte pro umdrehung / gewindesteigung
        self.stepsValveToValve = int(
            self.config["valveToValve"] *
            ((4075.7728395061727 / 2) / self._m5_steigung))
        print(self.stepsValveToValve)

        self.stepshomePosToValve = int(
            self.config["homePosToValve"] *
            ((4075.7728395061727 / 2) / self._m5_steigung))

        self.homingIsrunning = False
        self.valveReachedCB = None
        self.homingCB = None

        self.homepin = Pin(self.config["homeSencePin"], Pin.IN)

        pin = self.config["stepperPins"]

        self.valveStepper = Stepper(pin[0], pin[1], pin[2], pin[3],
                                    self.config["steps-s"],
                                    self.config["maxSteps"])
コード例 #19
0
ファイル: raspberryTest.py プロジェクト: mattvenn/v2
def testStepper():
    print '=== Stepper Test ==='
    print 'to do: Stepper PINs to output'
    stepper = Stepper()
    stepper.turn(45,100)
    stepper.turnAsync(-45,50)
    while(not stepper.isMovementFinished()):
        time.sleep(0.02)
コード例 #20
0
    def __init__(self):
        self.is_initialized = False
        rospy.init_node('manipulator_interface', anonymous=False)
        self.pub = rospy.Publisher('pwm', Pwm, queue_size=1)
        self.sub = rospy.Subscriber('manipulator_command', Manipulator, self.callback)

        self.neutral_pulse_width = servo_position_to_microsecs(0)

        rospy.sleep(0.1)  # Initial set to zero seems to disappear without a short sleep here
        self.servo_set_to_zero()
        rospy.on_shutdown(self.shutdown)
        self.claw_direction = 0.0
        self.claw_position = 0.0  # 1 = open, -1 = closed
        self.claw_speed = 1.0

        try:
            self.valve_stepper = Stepper(STEPPER_NUM_STEPS,
                                         STEPPER_VALVE_PINS,
                                         STEPPER_VALVE_ENABLE_PIN,
                                         COMPUTER)
            self.valve_direction = 0

            self.agar_stepper = Stepper(STEPPER_NUM_STEPS,
                                        STEPPER_AGAR_PINS,
                                        STEPPER_AGAR_ENABLE_PIN,
                                        COMPUTER)
            self.agar_direction = 0
        except NameError:
            rospy.logfatal('Could not initialize stepper.py. Is /computer parameter set correctly? '
                           'Shutting down node...')
            rospy.signal_shutdown('')

        self.valve_stepper.disable()
        self.agar_stepper.disable()

        rospy.loginfo('Initialized with {0} RPM steppers.'.format(STEPPER_RPM))
        self.is_initialized = True
        self.spin()
コード例 #21
0
def accel_2_integer(steps, a):

    stepper = Stepper(a, 10000, 700)
    stepper.target_pos = steps

    df = pd.DataFrame(index=np.arange(0, steps * 16),
                      columns=('v', 's', 'd', 't', 'adj_d', 'micro', 'shift'))

    t = 0
    s = 0
    while True:
        d = stepper.step()
        if d == 0 or s > steps * 16:
            break

        m = 1 << stepper.micro
        v = 1e6 / d / m
        p = stepper.pos / m
        ad = d * m
        t += d
        df.loc[s] = [v, p, d, t / 1e6, ad, m, stepper.shift]
        s += 1
    return df.dropna()
コード例 #22
0
ファイル: scanTEST.py プロジェクト: pratapbhanusolanki/3D
def setup():
    global LED
    LED = mraa.Gpio(7)
    LED.dir(mraa.DIR_OUT)

    global sensorPin
    sensorPin = mraa.Aio(2)

    global myStepper
    myStepper = Stepper()

    global myServo
    myServo = Servo()
    myServo.attach(9)
    myServo.write(30)
コード例 #23
0
ファイル: fibre.py プロジェクト: akatumba/pyofss
    def __init__(self,
                 name="fibre",
                 length=1.0,
                 alpha=None,
                 beta=None,
                 gamma=0.0,
                 sim_type=None,
                 traces=1,
                 local_error=1.0e-6,
                 method="RK4IP",
                 total_steps=100,
                 self_steepening=False,
                 raman_scattering=False,
                 rs_factor=0.003,
                 use_all=False,
                 centre_omega=None,
                 tau_1=12.2e-3,
                 tau_2=32.0e-3,
                 f_R=0.18):

        use_cache = not (method.upper().startswith('A'))

        self.name = name
        self.length = length
        self.linearity = Linearity(alpha, beta, sim_type, use_cache,
                                   centre_omega)
        self.nonlinearity = Nonlinearity(gamma, sim_type, self_steepening,
                                         raman_scattering, rs_factor, use_all,
                                         tau_1, tau_2, f_R)

        class Function():
            """ Class to hold linear and nonlinear functions. """
            def __init__(self, l, n, linear, nonlinear):
                self.l = l
                self.n = n
                self.linear = linear
                self.nonlinear = nonlinear

            def __call__(self, A, z):
                return self.l(A, z) + self.n(A, z)

        self.function = Function(self.l, self.n, self.linear, self.nonlinear)

        self.stepper = Stepper(traces, local_error, method, self.function,
                               self.length, total_steps)
コード例 #24
0
def duster(settings, model_id, zone_id):
    assert ONLY_MODEL_2 and model_id == 2, "ONLY HAVE HYDRO DATA FOR MODEL_IDX=2"

    print(f"M{model_id} (Z{zone_id}) loading input...(slow for now)")
    p = load_particle(settings["particle_inputfile"], \
                      settings["hydrorun_inputfile"], \
                      model_id, zone_id)

    output_d = f"output_M{model_id:03d}"
    os.makedirs(output_d, exist_ok=True)
    output_f = os.path.join(output_d, f"dust{zone_id:04}")

    net = Network(settings["network_file"])

    print(
        f"M{model_id} (Z{zone_id}) loaded, beginnging run: output[{output_f}]")

    gas = SNGas(p, net)
    step = Stepper(gas, net)
    spec    = SolverSpec(time_start = p.times[p.first_idx], time_bound = p.times[p.last_idx], absolute_tol = settings["abs_tol"], \
                     relative_tol = settings["rel_tol"], max_timestep = settings["max_dt"])

    print(f"time_start = {p.times[p.first_idx]}")

    solv = Solver(spec, step)
    obs = Observer(output_f, net, gas, step, solv, settings)

    msg = f"M{model_id} (Z{zone_id}) ok"
    try:
        solv(obs)
    except Exception as e:
        msg = f"M{model_id} (Z{zone_id}) did not finish ok\n{repr(e)}"
        print(msg)
        traceback.print_exc(file=sys.stdout)


#        obs.dump(solv._steps)
    finally:
        #        obs.runout(solv._steps, settings["align_tend_value"], res=settings["align_tend_resolution"])
        ## TIMING
        from stepper import S_DEBUG, S_FASTMATH, S_NOPYTHON, S_PARALLEL
        print(
            f"DEBUG={S_DEBUG}, NOPYTHON={S_NOPYTHON}, FASTMATH={S_FASTMATH}, PARALLEL={S_PARALLEL}"
        )
    return msg
コード例 #25
0
def stepper_test():
    #stepper variables
    # [stepPin, directionPin, enablePin]

    testStepper = Stepper([24, 22, 23])

    #test stepper
    testStepper.step(20000, "CW"); #steps, dir, speed, stayOn

    sleep(2)
    # test stepper
    testStepper.step(64000, "CCW");  # steps, dir, speed, stayOn

    return {"Stepper test": "done"}
コード例 #26
0
ファイル: pump.py プロジェクト: bambooSocks/db4-group5
class PrecisionPump:
    def __init__(self, step_pin, dir_pin):
        self.stepper = Stepper(step_pin, dir_pin)
        self.stepper.set_step_time(750)
        self.dir = 1

        self.stepsPerML = 5680  #TODO: determine proper amount

    def feed(self, ml_amount):
        stepsToTake = ml_amount * self.stepsPerML * self.dir
        self.stepper.steps(stepsToTake)

    # just for testing
    def step(self, steps):
        self.stepper.steps(steps)

    def reverse(self):
        self.dir = 1 if self.dir == 1 else -1
コード例 #27
0
ファイル: pi_adafruit.py プロジェクト: nlbutts/PowderScale
def dispense(value):
    value = float(value)
    try:
        print("Setting up OGR")
        ogr = ScaleOGR(False, False)
        stepper = Stepper(1000000)
        f = Filter(0.2)

        print("Setting up camera")
        camera = PiCamera()
        camera.close()
        camera = PiCamera()
        camera.resolution = (1920, 1088)
        camera.framerate = 30
        rawCapture = PiRGBArray(camera, size=(1920, 1088))

        print("Getting images")
        for frame in camera.capture_continuous(rawCapture,
                                               format="bgr",
                                               use_video_port=True):
            image = rawCapture.array
            num = ogr.process(image)
            fv = f.filter(num)
            print('Detected number: {:} -- Filtered number: {:}'.format(
                num, fv))
            rawCapture.truncate(0)

            if fv < value:
                stepper.run(1000, 1)
            else:
                stepper.stop()
                camera.close()

        pass
    except Exception as e:
        print(e)
        print("The scale is probably not on, turn it on and try again")
        pass
コード例 #28
0
from machine import Pin, I2C, PWM, Timer
from stepper import Stepper
import utime as time

pin_dir = Pin(14)
pin_step = Pin(13)
pin_en = Pin(0)

steppy = Stepper(pin_en, pin_dir, pin_step)

steppy.on()
steppy.max_speed = 10000
steppy.acc = 5
for i in range(0, 1):
    steppy.target = steppy.deg_to_steps(360)
    while (steppy.pos != steppy.target):
        _ = steppy.run()
    #steppy.off()
    time.sleep(1.0)

    steppy.target = 0
    while (steppy.pos != steppy.target):
        _ = steppy.run()
    #steppy.off()
    time.sleep(1.0)

print("Done!")

#pwm = PWM(pin_step)
#
#pwm.freq(1000)
コード例 #29
0
    load_config()  # Cargamos "config.json"

    # Capturamos webcam
    print "[START] Preparando cámara...."
    camera_recording = False

    while camera_recording is not True:
        camera = cv2.VideoCapture(0)
        time.sleep(1)

        # Esperamos a que la cámara esté preparada
        camera_recording, _ = camera.read()
    print "[DONE] Cámara lista!"

    print "[INFO] Inicializamos los motores..."
    pan_motor = Stepper("Base", 16, 19, 26)
    pan_motor.set_speed(5)
    print(pan_motor.print_info())

    tilt_motor = Stepper("Top", 16, 6, 13)
    tilt_motor.set_speed(5)
    print(tilt_motor.print_info())

    if test_motors == "True":
        motor_test()

    # Loop sobre la camara
    while True:

        # Leemos el primer frame e imprimimos el texto
        (video_signal, frame) = camera.read()
コード例 #30
0
 def __init__(self):
     GPIO.setmode(GPIO.BCM)
     self.areas = 16
     self.sonicMotor = Stepper()
     self.wheels = Wheel()
     self.motorPosition = 0  #gibt an ob der SonicMotor links oder rechts steht 0=links
コード例 #31
0
 def start(self):
     self._setup_logging()
     self._setup_api()
     self._setup_ignored_pokemon()
     self.stepper = Stepper(self)
     random.seed()
コード例 #32
0
from stepper import Stepper
from time import sleep

stepper = Stepper()

try:
    print "start"
    stepper.start()
    for i in range(1, 5):
        stepper.setSpeed(i * 200)
        print i * 200
        sleep(1)
    print "stop"
    stepper.stop()
    sleep(.2)
    print "flip"
    stepper.flipDirection()
    stepper.start()
    sleep(5)
    print "stop"
    stepper.stop()

except KeyboardInterrupt:
    print("\nCtrl-C pressed.  Stopping PIGPIO and exiting...")
finally:
    stepper.stop()
コード例 #33
0
ファイル: bot.py プロジェクト: IAmTipsy/PokemonGo-Bot
class PokemonGoBot(object):

    def __init__(self, config):
        self.config = config
        self.pokemon_list=json.load(open('pokemon.json'))
        self.item_list=json.load(open('items.json'))
        self.noballs = False

    def start(self):
        self._setup_logging()
        self._setup_api()
        self.stepper = Stepper(self)
        random.seed()

    def take_step(self):
        self.stepper.take_step()

    def work_on_cell(self, cell, position):
        if 'catchable_pokemons' in cell:
            print '[#] Something rustles nearby!'
            for pokemon in cell['catchable_pokemons']:
                worker = PokemonCatchWorker(pokemon, self)
                worker.work()
        if 'wild_pokemons' in cell:
            for pokemon in cell['wild_pokemons']:
                worker = PokemonCatchWorker(pokemon, self)
                worker.work()
                
        # After [self.noballs = True] and first spining, check if 50 pokeballs was gathered, if so stop spining
        if self.noballs and self.ballstock[1] >= 50:
            print ('[#] Gathered 50/50 pokeballs, continue catching!')
            self.noballs = False
        elif self.noballs and self.ballstock[1] < 50:
            print ('[#] Gathered ' + str(self.ballstock[1]) + '/50 pokeballs, continue farming...') 
        
        if self.config.spinstop or self.noballs:
            if 'forts' in cell:
                # Only include those with a lat/long
                forts = [fort for fort in cell['forts'] if 'latitude' in fort and 'type' in fort]

                # Sort all by distance from current pos- eventually this should build graph & A* it
                forts.sort(key=lambda x: distance(self.position[0], self.position[1], fort['latitude'], fort['longitude']))
                for fort in cell['forts']:
                    worker = SeenFortWorker(fort, self)
                    hack_chain = worker.work()
                    if hack_chain > 10:
                        print('[-] Anti-ban resting....')
                        break

    def _setup_logging(self):
        self.log = logging.getLogger(__name__)
        # log settings
        # log format
        logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(module)10s] [%(levelname)5s] %(message)s')
        # log level for http request class
        logging.getLogger("requests").setLevel(logging.WARNING)
        # log level for main pgoapi class
        logging.getLogger("pgoapi").setLevel(logging.INFO)
        # log level for internal pgoapi class
        logging.getLogger("rpc_api").setLevel(logging.INFO)

    def _setup_api(self):
        # instantiate pgoapi
        self.api = PGoApi()
        # provide player position on the earth

        self._set_starting_position()

        if not self.api.login(self.config.auth_service, self.config.username, self.config.password):
            print('Login Error, server busy')
            exit(0)

        # chain subrequests (methods) into one RPC call

        # get player inventory call
        # ----------------------
        self.api.get_player().get_inventory()

        inventory_req = self.api.call()

        inventory_dict = inventory_req['responses']['GET_INVENTORY']['inventory_delta']['inventory_items']

        # get player balls stock
        # ----------------------
        balls_stock = {1:0,2:0,3:0,4:0}

        for item in inventory_dict:
            try:
                if item['inventory_item_data']['item']['item'] == 1:
                    #print('Poke Ball count: ' + str(item['inventory_item_data']['item']['count']))
                    balls_stock[1] = item['inventory_item_data']['item']['count']
                if item['inventory_item_data']['item']['item'] == 2:
                    #print('Great Ball count: ' + str(item['inventory_item_data']['item']['count']))
                    balls_stock[2] = item['inventory_item_data']['item']['count']
                if item['inventory_item_data']['item']['item'] == 3:
                    #print('Ultra Ball count: ' + str(item['inventory_item_data']['item']['count']))
                    balls_stock[3] = item['inventory_item_data']['item']['count']
            except:
                continue
        
        self.ballstock = balls_stock
        
        # get player pokemon[id] group by pokemon[pokemon_id]
        # ----------------------
        pokemon_stock = {}

        for pokemon in inventory_dict:
            try:
                id1 = pokemon['inventory_item_data']['pokemon']['pokemon_id']
                id2 = pokemon['inventory_item_data']['pokemon']['id']
                id3 = pokemon['inventory_item_data']['pokemon']['cp']
                #DEBUG - Hide
                #print(str(id1))
                if id1 not in pokemon_stock:
                    pokemon_stock[id1] = {}
                #DEBUG - Hide
                #print(str(id2))
                pokemon_stock[id1].update({id3:id2})
            except:
                continue

        #DEBUG - Hide
        #print pokemon_stock

        for id in pokemon_stock:
            #DEBUG - Hide
            #print id
            sorted_cp = pokemon_stock[id].keys()
            if len(sorted_cp) > 1:
                sorted_cp.sort()
                sorted_cp.reverse()
                #DEBUG - Hide
                #print sorted_cp

                #Hide for now. If Unhide transfer all poke duplicates exept most CP.
                #for x in range(1, len(sorted_cp)):
                    #DEBUG - Hide
                    #print x
                    #print pokemon_stock[id][sorted_cp[x]]
                    #self.api.release_pokemon(pokemon_id=pokemon_stock[id][sorted_cp[x]])
                    #response_dict = self.api.call()

        # get player profile call
        # ----------------------
        self.api.get_player()

        response_dict = self.api.call()
        #print('Response dictionary: \n\r{}'.format(json.dumps(response_dict, indent=2)))
        currency_1="0"
        currency_2="0"

        player = response_dict['responses']['GET_PLAYER']['profile']

        ### @@@ TODO: Convert this to d/m/Y H:M:S
        creation_date = datetime.datetime.fromtimestamp(player['creation_time'] / 1e3)

        pokecoins = '0'
        stardust = '0'

        if 'amount' in player['currency'][0]:
            pokecoins = player['currency'][0]['amount']
        if 'amount' in player['currency'][1]:
            stardust = player['currency'][1]['amount']

        try:
            print('[#]')
            print('[#] Username: '******'username']))
            print('[#] Acccount Creation: ' + str(creation_date))
            print('[#] Bag Storage: ' + str(self.getInventoryCount('item')) + '/' + str(player['item_storage']))
            print('[#] Pokemon Storage: ' + str(self.getInventoryCount('pokemon')) + '/' + str(player['poke_storage']))
            print('[#] Stardust: ' + str(stardust))
            print('[#] Pokecoins: ' + str(pokecoins))
            print('[#] PokeBalls: ' + str(self.ballstock[1]))
            print('[#] GreatBalls: ' + str(self.ballstock[2]))
            print('[#] UltraBalls: ' + str(self.ballstock[3]))
            self.getPlayerInfo()
            print('[#]')
        except:
             print('Exception during print player profile')
        self.update_inventory();

    def update_inventory(self):
        self.api.get_inventory()
        response = self.api.call()
        self.inventory = list()
        if 'responses' in response:
            if 'GET_INVENTORY' in response['responses']:
                if 'inventory_delta' in response['responses']['GET_INVENTORY']:
                    if 'inventory_items' in response['responses']['GET_INVENTORY']['inventory_delta']:
                        for item in response['responses']['GET_INVENTORY']['inventory_delta']['inventory_items']:
                            if not 'inventory_item_data' in item:
                                continue
                            if not 'item' in item['inventory_item_data']:
                                continue
                            if not 'item' in item['inventory_item_data']['item']:
                                continue
                            if not 'count' in item['inventory_item_data']['item']:
                                continue
                            self.inventory.append(item['inventory_item_data']['item'])

    def _set_starting_position(self):
        self.position = self._get_pos_by_name(self.config.location)
        self.api.set_position(*self.position)

        print('[x] Address found: ' + self.config.location.decode('utf-8'))
        print('[x] Position in-game set as: ' + str(self.position))

        if self.config.test:
            return

    def _get_pos_by_name(self, location_name):
        geolocator = GoogleV3(api_key=self.config.gmapkey)
        loc = geolocator.geocode(location_name)

        print

        #self.log.info('Your given location: %s', loc.address.encode('utf-8'))
        #self.log.info('lat/long/alt: %s %s %s', loc.latitude, loc.longitude, loc.altitude)

        return (loc.latitude, loc.longitude, loc.altitude)


    ###########################################
    ## @eggins pretty print functions
    ###########################################

    ## - Get count of inventory items and return the output for each
    def getInventoryCount(self, what):
        # Get contents of inventory
        self.api.get_inventory()
        response_dict = self.api.call()
        if 'responses' in response_dict:
            if 'GET_INVENTORY' in response_dict['responses']:
                if 'inventory_delta' in response_dict['responses']['GET_INVENTORY']:
                    if 'inventory_items' in response_dict['responses']['GET_INVENTORY']['inventory_delta']:
                        pokecount = 0
                        itemcount = 1
                        for item in response_dict['responses']['GET_INVENTORY']['inventory_delta']['inventory_items']:
                            #print('item {}'.format(item))
                            if 'inventory_item_data' in item:
                                if 'pokemon' in item['inventory_item_data']:
                                    pokecount = pokecount + 1
                                if 'item' in item['inventory_item_data']:
                                    if 'count' in item['inventory_item_data']['item']:
                                        itemcount = itemcount + item['inventory_item_data']['item']['count']
        if 'pokemon' in what:
            return pokecount
        if 'item' in what:
            return itemcount
        return '0'

    ## - Get more player information
    def getPlayerInfo(self):
        # Get contents of inventory
        self.api.get_inventory()
        response_dict = self.api.call()
        if 'responses' in response_dict:
            if 'GET_INVENTORY' in response_dict['responses']:
                if 'inventory_delta' in response_dict['responses']['GET_INVENTORY']:
                    if 'inventory_items' in response_dict['responses']['GET_INVENTORY']['inventory_delta']:
                        pokecount = 0
                        itemcount = 1
                        for item in response_dict['responses']['GET_INVENTORY']['inventory_delta']['inventory_items']:
                            #print('item {}'.format(item))
                            if 'inventory_item_data' in item:
                                if 'player_stats' in item['inventory_item_data']:
                                    playerdata = item['inventory_item_data']['player_stats']

                                    nextlvlxp = (int(playerdata['next_level_xp']) - int(playerdata['experience']))

                                    if 'level' in playerdata:
                                        print('[#] -- Level: ' + str(playerdata['level']))

                                    if 'experience' in playerdata:
                                        print('[#] -- Experience: ' + str(playerdata['experience']))
                                        print('[#] -- Experience until next level: ' + str(nextlvlxp))

                                    if 'pokemons_captured' in playerdata:
                                        print('[#] -- Pokemon Captured: ' + str(playerdata['pokemons_captured']))

                                    if 'poke_stop_visits' in playerdata:
                                        print('[#] -- Pokestops Visited: ' + str(playerdata['poke_stop_visits']))
コード例 #34
0
class PokemonGoBot(object):
    def __init__(self, config):
        self.config = config
        self.pokemon_list = config.pokemons
        self.item_list = config.items

    def start(self):
        self._setup_api()
        self.stepper = Stepper(self)
        random.seed()

    def setup_logging(self, logger):
        self._setup_logging()
        self.logger = logger
    
    def take_step(self):
        self.stepper.take_step()

    def work_on_cell(self, cell, position, include_fort_on_path):
        if self.config.evolve_all:
            # Run evolve all once. Flip the bit.
            print('[#] Attempting to evolve all pokemons ...')
            worker = EvolveAllWorker(self)
            worker.work()
            self.config.evolve_all = []

        self._filter_ignored_pokemons(cell)

        if (self.config.mode == "all" or self.config.mode ==
                "poke") and 'catchable_pokemons' in cell and len(cell[
                    'catchable_pokemons']) > 0:
            self.logger.info('[#] Something rustles nearby!')
            # Sort all by distance from current pos- eventually this should
            # build graph & A* it
            cell['catchable_pokemons'].sort(
                key=
                lambda x: distance(self.position[0], self.position[1], x['latitude'], x['longitude']))

        if (self.config.mode == "all" or self.config.mode == "poke"
            ) and 'wild_pokemons' in cell and len(cell['wild_pokemons']) > 0:
            # Sort all by distance from current pos- eventually this should
            # build graph & A* it
            cell['wild_pokemons'].sort(
                key=
                lambda x: distance(self.position[0], self.position[1], x['latitude'], x['longitude']))
            for pokemon in cell['wild_pokemons']:
                if self.catch_pokemon(pokemon) == PokemonCatchWorker.NO_POKEBALLS:
                    break
        if (self.config.mode == "all" or
                self.config.mode == "farm") and include_fort_on_path:
            if 'forts' in cell:
                # Only include those with a lat/long
                forts = [fort
                         for fort in cell['forts']
                         if 'latitude' in fort and 'type' in fort]
                gyms = [gym for gym in cell['forts'] if 'gym_points' in gym]

                # Sort all by distance from current pos- eventually this should
                # build graph & A* it
                forts.sort(key=lambda x: distance(self.position[
                           0], self.position[1], x['latitude'], x['longitude']))
                for fort in forts:
                    worker = MoveToFortWorker(fort, self)
                    worker.work()

                    worker = SeenFortWorker(fort, self)
                    hack_chain = worker.work()
                    if hack_chain > 10:
                        #print('need a rest')
                        break

    def _setup_logging(self):
        # log settings
        # log format
        logging.basicConfig(
            level=logging.DEBUG,
            format='%(asctime)s [%(module)10s] [%(levelname)5s] %(message)s')

        if self.config.debug:
            logging.getLogger("requests").setLevel(logging.DEBUG)
            logging.getLogger("pgoapi").setLevel(logging.DEBUG)
            logging.getLogger("rpc_api").setLevel(logging.DEBUG)
        else:
            logging.getLogger("requests").setLevel(logging.ERROR)
            logging.getLogger("pgoapi").setLevel(logging.ERROR)
            logging.getLogger("rpc_api").setLevel(logging.ERROR)

    def _setup_api(self):
        # instantiate pgoapi
        self.api = PGoApi()

        # provide player position on the earth
        self._set_starting_position()

        if not self.api.login(self.config.auth_service,
                              str(self.config.username),
                              str(self.config.password)):
            self.logger.error('Login Error, server busy', 'red')
            exit(0)

        # chain subrequests (methods) into one RPC call

        # get player profile call
        # ----------------------
        self.api.get_player()

        response_dict = self.api.call()
        currency_1 = "0"
        currency_2 = "0"

        player = response_dict['responses']['GET_PLAYER']['player_data']
        print response_dict

        # @@@ TODO: Convert this to d/m/Y H:M:S
        creation_date = datetime.datetime.fromtimestamp(
            player['creation_timestamp_ms'] / 1e3)

        pokecoins = '0'
        stardust = '0'
        balls_stock = self.pokeball_inventory()

        if 'amount' in player['currencies'][0]:
            pokecoins = player['currencies'][0]['amount']
        if 'amount' in player['currencies'][1]:
            stardust = player['currencies'][1]['amount']

        self.logger.info('[#] Username: {username}'.format(**player))
        self.logger.info('[#] Acccount Creation: {}'.format(creation_date))
        self.logger.info('[#] Bag Storage: {}/{}'.format(
            self.get_inventory_count('item'), player['max_item_storage']))
        self.logger.info('[#] Pokemon Storage: {}/{}'.format(
            self.get_inventory_count('pokemon'), player[
                'max_pokemon_storage']))
        self.logger.info('[#] Stardust: {}'.format(stardust))
        self.logger.info('[#] Pokecoins: {}'.format(pokecoins))
        self.logger.info('[#] PokeBalls: ' + str(balls_stock[1]))
        self.logger.info('[#] GreatBalls: ' + str(balls_stock[2]))
        self.logger.info('[#] UltraBalls: ' + str(balls_stock[3]))

        self.get_player_info()

        if self.config.initial_transfer:
            worker = InitialTransferWorker(self)
            worker.work()

        self.logger.info('[#]')
        self.update_inventory()

    def catch_pokemon(self, pokemon):
        worker = PokemonCatchWorker(pokemon, self)
        return_value = worker.work()

        if return_value == PokemonCatchWorker.BAG_FULL:
            worker = InitialTransferWorker(self)
            worker.work()

        return return_value

    def drop_item(self, item_id, count):
        self.api.recycle_inventory_item(item_id=item_id, count=count)
        inventory_req = self.api.call()

        # Example of good request response
        #{'responses': {'RECYCLE_INVENTORY_ITEM': {'result': 1, 'new_count': 46}}, 'status_code': 1, 'auth_ticket': {'expire_timestamp_ms': 1469306228058L, 'start': '/HycFyfrT4t2yB2Ij+yoi+on778aymMgxY6RQgvrGAfQlNzRuIjpcnDd5dAxmfoTqDQrbz1m2dGqAIhJ+eFapg==', 'end': 'f5NOZ95a843tgzprJo4W7Q=='}, 'request_id': 8145806132888207460L}
        return inventory_req

    def update_inventory(self):
        self.api.get_inventory()
        response = self.api.call()
        self.inventory = list()
        if 'responses' in response:
            if 'GET_INVENTORY' in response['responses']:
                if 'inventory_delta' in response['responses']['GET_INVENTORY']:
                    if 'inventory_items' in response['responses'][
                            'GET_INVENTORY']['inventory_delta']:
                        for item in response['responses']['GET_INVENTORY'][
                                'inventory_delta']['inventory_items']:
                            if not 'inventory_item_data' in item:
                                continue
                            if not 'item' in item['inventory_item_data']:
                                continue
                            if not 'item_id' in item['inventory_item_data'][
                                    'item']:
                                continue
                            if not 'count' in item['inventory_item_data'][
                                    'item']:
                                continue
                            self.inventory.append(item['inventory_item_data'][
                                'item'])

    def pokeball_inventory(self):
        self.api.get_player().get_inventory()

        inventory_req = self.api.call()
        inventory_dict = inventory_req['responses']['GET_INVENTORY'][
            'inventory_delta']['inventory_items']

        # get player balls stock
        # ----------------------
        balls_stock = {1: 0, 2: 0, 3: 0, 4: 0}

        for item in inventory_dict:
            try:
                # print(item['inventory_item_data']['item'])
                item_id = item['inventory_item_data']['item']['item_id']
                item_count = item['inventory_item_data']['item']['count']

                if item_id == Item.ITEM_POKE_BALL.value:
                    # print('Poke Ball count: ' + str(item_count))
                    balls_stock[1] = item_count
                if item_id == Item.ITEM_GREAT_BALL.value:
                    # print('Great Ball count: ' + str(item_count))
                    balls_stock[2] = item_count
                if item_id == Item.ITEM_ULTRA_BALL.value:
                    # print('Ultra Ball count: ' + str(item_count))
                    balls_stock[3] = item_count
            except:
                continue
        return balls_stock

    def item_inventory_count(self, id):
        self.api.get_player().get_inventory()

        inventory_req = self.api.call()
        inventory_dict = inventory_req['responses'][
            'GET_INVENTORY']['inventory_delta']['inventory_items']

        item_count = 0

        for item in inventory_dict:
            try:
                if item['inventory_item_data']['item']['item_id'] == int(id):
                    item_count = item[
                        'inventory_item_data']['item']['count']
            except:
                continue
        return item_count

    def _set_starting_position(self):

        if self.config.test:
            # TODO: Add unit tests
            return

        if self.config.location:
            try:
                location_str = str(self.config.location)
                location = (self._get_pos_by_name(location_str.replace(" ", "")))
                self.position = location
                self.api.set_position(*self.position)
                self.logger.info('')
                self.logger.info(u'[x] Address found: {}'.format(self.config.location.decode(
                    'utf-8')))
                self.logger.info('[x] Position in-game set as: {}'.format(self.position))
                self.logger.info('')
                return
            except:
                self.logger.info('[x] The location given using -l could not be parsed.')
                pass
        else:
            raise ValueError("No usable location")

    def _get_pos_by_name(self, location_name):
        # Check if the given location is already a coordinate.
        if ',' in location_name:
            possibleCoordinates = re.findall("[-]?\d{1,3}[.]\d{6,7}", location_name)
            if len(possibleCoordinates) == 2:
                # 2 matches, this must be a coordinate. We'll bypass the Google geocode so we keep the exact location.
                self.logger.info(
                    '[x] Coordinates found in passed in location, not geocoding.')
                return (float(possibleCoordinates[0]), float(possibleCoordinates[1]), float("0.0"))
            else:
                raise ValueError("Invalid GPS")
        else:
            raise ValueError("Invalid GPS")

    def _filter_ignored_pokemons(self, cell):
        process_ignore = False
        ignores = self.config.ignores
        if len(ignores) > 0:
            process_ignore = True

        if process_ignore:
            # remove any wild pokemon
            try:
                for p in cell['wild_pokemons'][:]:
                    pokemon_id = p['pokemon_data']['pokemon_id']
                    pokemon_name = filter(
                        lambda x: int(x.get('Number')) == pokemon_id,
                        self.pokemon_list)[0]['Name']

                    if pokemon_name in ignores:
                        cell['wild_pokemons'].remove(p)
            except KeyError:
                pass

            #
            # remove catchable pokemon
            try:
                for p in cell['catchable_pokemons'][:]:
                    pokemon_id = p['pokemon_id']
                    pokemon_name = filter(
                        lambda x: int(x.get('Number')) == pokemon_id,
                        self.pokemon_list)[0]['Name']

                    if pokemon_name in ignores:
                        cell['catchable_pokemons'].remove(p)
            except KeyError:
                pass

    def heartbeat(self):
        self.api.get_player()
        self.api.get_hatched_eggs()
        self.api.get_inventory()
        self.api.check_awarded_badges()
        self.api.call()

    def get_inventory_count(self, what):
        self.api.get_inventory()
        response_dict = self.api.call()
        if 'responses' in response_dict:
            if 'GET_INVENTORY' in response_dict['responses']:
                if 'inventory_delta' in response_dict['responses'][
                        'GET_INVENTORY']:
                    if 'inventory_items' in response_dict['responses'][
                            'GET_INVENTORY']['inventory_delta']:
                        pokecount = 0
                        itemcount = 1
                        for item in response_dict['responses'][
                                'GET_INVENTORY']['inventory_delta'][
                                    'inventory_items']:
                            #print('item {}'.format(item))
                            if 'inventory_item_data' in item:
                                if 'pokemon_data' in item[
                                        'inventory_item_data']:
                                    pokecount = pokecount + 1
                                if 'item' in item['inventory_item_data']:
                                    if 'count' in item['inventory_item_data'][
                                            'item']:
                                        itemcount = itemcount + \
                                            item['inventory_item_data'][
                                                'item']['count']
        if 'pokemon' in what:
            return pokecount
        if 'item' in what:
            return itemcount
        return '0'

    def get_player_info(self):
        self.api.get_inventory()
        response_dict = self.api.call()
        if 'responses' in response_dict:
            if 'GET_INVENTORY' in response_dict['responses']:
                if 'inventory_delta' in response_dict['responses'][
                        'GET_INVENTORY']:
                    if 'inventory_items' in response_dict['responses'][
                            'GET_INVENTORY']['inventory_delta']:
                        pokecount = 0
                        itemcount = 1
                        for item in response_dict['responses'][
                                'GET_INVENTORY']['inventory_delta'][
                                    'inventory_items']:
                            #print('item {}'.format(item))
                            if 'inventory_item_data' in item:
                                if 'player_stats' in item[
                                        'inventory_item_data']:
                                    playerdata = item['inventory_item_data'][
                                        'player_stats']

                                    nextlvlxp = (
                                        int(playerdata.get('next_level_xp', 0)) -
                                        int(playerdata.get('experience', 0)))

                                    if 'level' in playerdata:
                                        self.logger.info(
                                            '[#] -- Level: {level}'.format(
                                                **playerdata))

                                    if 'experience' in playerdata:
                                        self.logger.info(
                                            '[#] -- Experience: {experience}'.format(
                                                **playerdata))
                                        self.logger.info(
                                            '[#] -- Experience until next level: {}'.format(
                                                nextlvlxp))

                                    if 'pokemons_captured' in playerdata:
                                        self.logger.info(
                                            '[#] -- Pokemon Captured: {pokemons_captured}'.format(
                                                **playerdata))

                                    if 'poke_stop_visits' in playerdata:
                                        self.logger.info(
                                            '[#] -- Pokestops Visited: {poke_stop_visits}'.format(
                                                **playerdata))
コード例 #35
0
class PokemonGoBot(object):
    process_ignored_pokemon = False

    def __init__(self, config):
        self.config = config
        self.item_list = json.load(open('data/items.json'))
        self.pokemon_list = json.load(open('data/pokemon.json'))

    def start(self):
        self._setup_logging()
        self._setup_api()
        self._setup_ignored_pokemon()
        self.stepper = Stepper(self)
        random.seed()

    def take_step(self):
        self.stepper.take_step()

    def work_on_cell(self, map_cells, position, include_fort_on_path):
        self._remove_ignored_pokemon(map_cells)

        if (self.config.mode == "all" or self.config.mode == "poke"):
            self._work_on_catchable_pokemon(map_cells)

        if (self.config.mode == "all" or self.config.mode == "poke"):
            self._work_on_wild_pokemon(map_cells)

        if (self.config.mode == "all" or self.config.mode == "farm") and include_fort_on_path:
            self._work_on_forts(position, map_cells)

    def _work_on_forts(self, position, map_cells):
        forts = filtered_forts(position[0], position[1], sum([cell.get("forts", []) for cell in map_cells], []))
        if forts:
            worker = SeenFortWorker(forts[0], self)
            hack_chain = worker.work()

    def _remove_ignored_pokemon(self, map_cells):
        if self.process_ignored_pokemon:
            try:
                for cell in map_cells:
                    for p in cell['wild_pokemons'][:]:
                        pokemon_id = p['pokemon_data']['pokemon_id']
                        pokemon_name = filter(lambda x: int(x.get('Number')) == pokemon_id, self.pokemon_list)[0]['Name']

                        if pokemon_name in ignores:
                            cell['wild_pokemons'].remove(p)
            except KeyError:
                pass

            try:
                for call in map_cells:
                    for p in cell['catchable_pokemons'][:]:
                        pokemon_id = p['pokemon_id']
                        pokemon_name = filter(lambda x: int(x.get('Number')) == pokemon_id, self.pokemon_list)[0]['Name']

                        if pokemon_name in ignores:
                            cell['catchable_pokemons'].remove(p)
            except KeyError:
                pass

    def _work_on_catchable_pokemon(self, map_cells):
        for cell in map_cells:
            if 'catchable_pokemons' in cell and len(cell['catchable_pokemons']) > 0:
                logger.log('[#] Something rustles nearby!')
                # Sort all by distance from current pos- eventually this should
                # build graph & A* it
                cell['catchable_pokemons'].sort(
                    key=lambda x: distance(self.position[0], self.position[1], x['latitude'], x['longitude']))
                for pokemon in cell['catchable_pokemons']:
                    with open('web/catchable-%s.json' % (self.config.username), 'w') as outfile:
                        json.dump(pokemon, outfile)
                    worker = PokemonCatchWorker(pokemon, self)
                    if worker.work() == -1:
                        break
                    with open('web/catchable-%s.json' % (self.config.username), 'w') as outfile:
                        json.dump({}, outfile)

    def _work_on_wild_pokemon(self, map_cells):
        for cell in map_cells:
            if 'wild_pokemons' in cell and len(cell['wild_pokemons']) > 0:
                # Sort all by distance from current pos- eventually this should
                # build graph & A* it
                cell['wild_pokemons'].sort(
                    key=lambda x: distance(self.position[0], self.position[1], x['latitude'], x['longitude']))
                for pokemon in cell['wild_pokemons']:
                    worker = PokemonCatchWorker(pokemon, self)
                    if worker.work() == -1:
                        break

    def _setup_logging(self):
        self.log = logging.getLogger(__name__)
        # log settings
        # log format
        logging.basicConfig(
            level=logging.DEBUG,
            format='%(asctime)s [%(module)10s] [%(levelname)5s] %(message)s')

        if self.config.debug:
            logging.getLogger("requests").setLevel(logging.DEBUG)
            logging.getLogger("pgoapi").setLevel(logging.DEBUG)
            logging.getLogger("rpc_api").setLevel(logging.DEBUG)
        else:
            logging.getLogger("requests").setLevel(logging.ERROR)
            logging.getLogger("pgoapi").setLevel(logging.ERROR)
            logging.getLogger("rpc_api").setLevel(logging.ERROR)

    def _setup_api(self):
        # instantiate pgoapi
        self.api = PGoApi()
        # provide player position on the earth

        self._set_starting_position()

        if not self.api.login(self.config.auth_service,
                              str(self.config.username),
                              str(self.config.password)):
            logger.log('Login Error, server busy', 'red')
            exit(0)

        # chain subrequests (methods) into one RPC call

        # get player profile call
        # ----------------------
        self.api.get_player()

        response_dict = self.api.call()
        # print('Response dictionary: \n\r{}'.format(json.dumps(response_dict, indent=2)))
        currency_1 = "0"
        currency_2 = "0"

        player = response_dict['responses']['GET_PLAYER']['player_data']

        # @@@ TODO: Convert this to d/m/Y H:M:S
        creation_date = datetime.datetime.fromtimestamp(
            player['creation_timestamp_ms'] / 1e3)

        pokecoins = '0'
        stardust = '0'
        balls_stock = self.pokeball_inventory()

        if 'amount' in player['currencies'][0]:
            pokecoins = player['currencies'][0]['amount']
        if 'amount' in player['currencies'][1]:
            stardust = player['currencies'][1]['amount']

        logger.log('[#]')
        logger.log('[#] Username: {username}'.format(**player))
        logger.log('[#] Acccount Creation: {}'.format(creation_date))
        logger.log('[#] Bag Storage: {}/{}'.format(
            self.get_inventory_count('item'), player['max_item_storage']))
        logger.log('[#] Pokemon Storage: {}/{}'.format(
            self.get_inventory_count('pokemon'), player[
                'max_pokemon_storage']))
        logger.log('[#] Stardust: {}'.format(stardust))
        logger.log('[#] Pokecoins: {}'.format(pokecoins))
        logger.log('[#] PokeBalls: {}'.format(balls_stock[1]))
        logger.log('[#] GreatBalls: {}'.format(balls_stock[2]))
        logger.log('[#] UltraBalls: {}'.format(balls_stock[3]))

        # Testing
        # self.drop_item(Item.ITEM_POTION.value,1)
        # exit(0)
        self.get_player_info()

        if self.config.initial_transfer:
            self.initial_transfer()

        logger.log('[#]')
        self.update_inventory()

    def _setup_ignored_pokemon(self):
        try:
            with open("./data/catch-ignore.yml", 'r') as y:
                ignores = yaml.load(y)['ignore']
                if len(ignores) > 0:
                    self.process_ignored_pokemon = True
        except Exception, e:
            pass
コード例 #36
0
ファイル: bot.py プロジェクト: NewyorkDev/PokemonGo-Bot
class PokemonGoBot(object):

    def __init__(self, config):
        self.config = config
        self.pokemon_list=json.load(open('pokemon.json'))
        self.item_list=json.load(open('items.json'))

    def start(self):
        self._setup_logging()
        self._setup_api()
        self.stepper = Stepper(self)

    def take_step(self):
        self.stepper.take_step()

    def work_on_cell(self, cell, position):
        if 'catchable_pokemons' in cell:
            print 'Something rustles nearby!'
            for pokemon in cell['catchable_pokemons']:
                worker = PokemonCatchWorker(pokemon, self)
                worker.work()
        if 'wild_pokemons' in cell:
            for pokemon in cell['wild_pokemons']:
                worker = PokemonCatchWorker(pokemon, self)
                worker.work()
        if self.config.spinstop:
            if 'forts' in cell:
                # Only include those with a lat/long
                forts = [fort for fort in cell['forts'] if 'latitude' in fort and 'type' in fort]
                # Sort all by distance from current pos- eventually this should build graph & A* it
                forts.sort(key=lambda x: SeenFortWorker.geocalc(self.position[0], self.position[1], fort['latitude'], fort['longitude']))
                for fort in cell['forts']:
                    worker = SeenFortWorker(fort, self)
                    hack_chain = worker.work()
                    if hack_chain > 10:
                        print('need a rest')
                        break

    def _setup_logging(self):
        self.log = logging.getLogger(__name__)
        # log settings
        # log format
        logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(module)10s] [%(levelname)5s] %(message)s')
        # log level for http request class
        logging.getLogger("requests").setLevel(logging.WARNING)
        # log level for main pgoapi class
        logging.getLogger("pgoapi").setLevel(logging.INFO)
        # log level for internal pgoapi class
        logging.getLogger("rpc_api").setLevel(logging.INFO)

    def _setup_api(self):
        # instantiate pgoapi
        self.api = PGoApi()
        # provide player position on the earth

        self._set_starting_position()

        if not self.api.login(self.config.auth_service, self.config.username, self.config.password):
            return

        # chain subrequests (methods) into one RPC call

        # get player profile call
        # ----------------------
        self.api.get_player()

        response_dict = self.api.call()
        #print('Response dictionary: \n\r{}'.format(json.dumps(response_dict, indent=2)))
        currency_1="0"
        currency_2="0"
        try:
            if 'amount' in response_dict['responses']['GET_PLAYER']['profile']['currency'][0]:
                currency_1=response_dict['responses']['GET_PLAYER']['profile']['currency'][0]['amount']
            if 'amount' in response_dict['responses']['GET_PLAYER']['profile']['currency'][1]:
                currency_2=response_dict['responses']['GET_PLAYER']['profile']['currency'][1]['amount']
            print 'Profile:'
            print '    Username: '******'responses']['GET_PLAYER']['profile']['username'])
            print '    Bag size: ' + str(response_dict['responses']['GET_PLAYER']['profile']['item_storage'])
            print '    Pokemon Storage Size: ' + str(response_dict['responses']['GET_PLAYER']['profile']['poke_storage'])
            print '    Account Creation: ' + str(response_dict['responses']['GET_PLAYER']['profile']['creation_time'])
            print '    Currency: '
            print '        ' + str(response_dict['responses']['GET_PLAYER']['profile']['currency'][0]['type']) + ': ' + str(currency_1)
            print '        ' + str(response_dict['responses']['GET_PLAYER']['profile']['currency'][1]['type']) + ': ' + str(currency_2)
        except:
            print('Exception during print player profile')
        self.update_inventory();

    def update_inventory(self):
        self.api.get_inventory()
        response = self.api.call()
        self.inventory = list()
        if 'responses' in response:
            if 'GET_INVENTORY' in response['responses']:
                if 'inventory_delta' in response['responses']['GET_INVENTORY']:
                    if 'inventory_items' in response['responses']['GET_INVENTORY']['inventory_delta']:
                        for item in response['responses']['GET_INVENTORY']['inventory_delta']['inventory_items']:
                            if not 'inventory_item_data' in item:
                                continue
                            if not 'item' in item['inventory_item_data']:
                                continue
                            if not 'item' in item['inventory_item_data']['item']:
                                continue
                            if not 'count' in item['inventory_item_data']['item']:
                                continue
                            self.inventory.append(item['inventory_item_data']['item'])

    def _set_starting_position(self):
        self.position = self._get_pos_by_name(self.config.location)
        self.api.set_position(*self.position)
        print(self.position)
        if self.config.test:
            return

    def _get_pos_by_name(self, location_name):
        geolocator = GoogleV3(api_key=self.config.gmapkey)
        loc = geolocator.geocode(location_name)

        self.log.info('Your given location: %s', loc.address.encode('utf-8'))
        self.log.info('lat/long/alt: %s %s %s', loc.latitude, loc.longitude, loc.altitude)

        return (loc.latitude, loc.longitude, loc.altitude)
コード例 #37
0
ファイル: __init__.py プロジェクト: ctfhacker/PokemonGo-Bot
class PokemonGoBot(object):
    def __init__(self, config):
        self.config = config
        self.pokemon_list = json.load(open('data/pokemon.json'))
        self.item_list = json.load(open('data/items.json'))

    def start(self):
        self._setup_logging()
        self._setup_api()
        self.stepper = Stepper(self)
        random.seed()

    def take_step(self):
        self.stepper.take_step()

    def work_on_cell(self, cell, position, include_fort_on_path):
        if self.config.evolve_all:
            # Run evolve all once. Flip the bit.
            print('[#] Attempting to evolve all pokemons ...')
            worker = EvolveAllWorker(self)
            worker.work()
            self.config.evolve_all = []

        self._filter_ignored_pokemons(cell)

        if (self.config.mode == "all" or self.config.mode ==
                "poke") and 'catchable_pokemons' in cell and len(cell[
                    'catchable_pokemons']) > 0:
            logger.log('[#] Something rustles nearby!')
            # Sort all by distance from current pos- eventually this should
            # build graph & A* it
            cell['catchable_pokemons'].sort(
                key=
                lambda x: distance(self.position[0], self.position[1], x['latitude'], x['longitude']))

            user_web_catchable = 'web/catchable-%s.json' % (self.config.username)
            for pokemon in cell['catchable_pokemons']:
                with open(user_web_catchable, 'w') as outfile:
                    json.dump(pokemon, outfile)

                if self.catch_pokemon(pokemon) == PokemonCatchWorker.NO_POKEBALLS:
                    break
                with open(user_web_catchable, 'w') as outfile:
                    json.dump({}, outfile)

        if (self.config.mode == "all" or self.config.mode == "poke"
            ) and 'wild_pokemons' in cell and len(cell['wild_pokemons']) > 0:
            # Sort all by distance from current pos- eventually this should
            # build graph & A* it
            cell['wild_pokemons'].sort(
                key=
                lambda x: distance(self.position[0], self.position[1], x['latitude'], x['longitude']))
            for pokemon in cell['wild_pokemons']:
                if self.catch_pokemon(pokemon) == PokemonCatchWorker.NO_POKEBALLS:
                    break
        if (self.config.mode == "all" or
                self.config.mode == "farm") and include_fort_on_path:
            if 'forts' in cell:
                # Only include those with a lat/long
                forts = [fort
                         for fort in cell['forts']
                         if 'latitude' in fort and 'type' in fort]
                gyms = [gym for gym in cell['forts'] if 'gym_points' in gym]

                # Sort all by distance from current pos- eventually this should
                # build graph & A* it
                forts.sort(key=lambda x: distance(self.position[
                           0], self.position[1], x['latitude'], x['longitude']))
                for fort in forts:
                    worker = MoveToFortWorker(fort, self)
                    worker.work()

                    worker = SeenFortWorker(fort, self)
                    hack_chain = worker.work()
                    if hack_chain > 10:
                        #print('need a rest')
                        break

    def _setup_logging(self):
        self.log = logging.getLogger(__name__)
        # log settings
        # log format
        logging.basicConfig(
            level=logging.DEBUG,
            format='%(asctime)s [%(module)10s] [%(levelname)5s] %(message)s')

        if self.config.debug:
            logging.getLogger("requests").setLevel(logging.DEBUG)
            logging.getLogger("pgoapi").setLevel(logging.DEBUG)
            logging.getLogger("rpc_api").setLevel(logging.DEBUG)
        else:
            logging.getLogger("requests").setLevel(logging.ERROR)
            logging.getLogger("pgoapi").setLevel(logging.ERROR)
            logging.getLogger("rpc_api").setLevel(logging.ERROR)

    def _setup_api(self):
        # instantiate pgoapi
        self.api = PGoApi()

        # check if the release_config file exists
        try:
            with open('release_config.json') as file:
                pass
        except:
            # the file does not exist, warn the user and exit.
            logger.log('[#] IMPORTANT: Rename and configure release_config.json.example for your Pokemon release logic first!', 'red')
            exit(0)

        # provide player position on the earth
        self._set_starting_position()

        if not self.api.login(self.config.auth_service,
                              str(self.config.username),
                              str(self.config.password)):
            logger.log('Login Error, server busy', 'red')
            exit(0)

        # chain subrequests (methods) into one RPC call

        # get player profile call
        # ----------------------
        self.api.get_player()

        response_dict = self.api.call()
        #print('Response dictionary: \n\r{}'.format(json.dumps(response_dict, indent=2)))
        currency_1 = "0"
        currency_2 = "0"

        player = response_dict['responses']['GET_PLAYER']['player_data']

        # @@@ TODO: Convert this to d/m/Y H:M:S
        creation_date = datetime.datetime.fromtimestamp(
            player['creation_timestamp_ms'] / 1e3)

        pokecoins = '0'
        stardust = '0'
        balls_stock = self.pokeball_inventory()

        if 'amount' in player['currencies'][0]:
            pokecoins = player['currencies'][0]['amount']
        if 'amount' in player['currencies'][1]:
            stardust = player['currencies'][1]['amount']

        logger.log('[#] Username: {username}'.format(**player))
        logger.log('[#] Acccount Creation: {}'.format(creation_date))
        logger.log('[#] Bag Storage: {}/{}'.format(
            self.get_inventory_count('item'), player['max_item_storage']))
        logger.log('[#] Pokemon Storage: {}/{}'.format(
            self.get_inventory_count('pokemon'), player[
                'max_pokemon_storage']))
        logger.log('[#] Stardust: {}'.format(stardust))
        logger.log('[#] Pokecoins: {}'.format(pokecoins))
        logger.log('[#] PokeBalls: ' + str(balls_stock[1]))
        logger.log('[#] GreatBalls: ' + str(balls_stock[2]))
        logger.log('[#] UltraBalls: ' + str(balls_stock[3]))

        self.get_player_info()

        if self.config.initial_transfer:
            worker = InitialTransferWorker(self)
            worker.work()

        logger.log('[#]')
        self.update_inventory()

    def catch_pokemon(self, pokemon):
        worker = PokemonCatchWorker(pokemon, self)
        return_value = worker.work()

        if return_value == PokemonCatchWorker.BAG_FULL:
            worker = InitialTransferWorker(self)
            worker.work()

        return return_value

    def drop_item(self, item_id, count):
        self.api.recycle_inventory_item(item_id=item_id, count=count)
        inventory_req = self.api.call()

        # Example of good request response
        #{'responses': {'RECYCLE_INVENTORY_ITEM': {'result': 1, 'new_count': 46}}, 'status_code': 1, 'auth_ticket': {'expire_timestamp_ms': 1469306228058L, 'start': '/HycFyfrT4t2yB2Ij+yoi+on778aymMgxY6RQgvrGAfQlNzRuIjpcnDd5dAxmfoTqDQrbz1m2dGqAIhJ+eFapg==', 'end': 'f5NOZ95a843tgzprJo4W7Q=='}, 'request_id': 8145806132888207460L}
        return inventory_req

    def update_inventory(self):
        self.api.get_inventory()
        response = self.api.call()
        self.inventory = list()
        if 'responses' in response:
            if 'GET_INVENTORY' in response['responses']:
                if 'inventory_delta' in response['responses']['GET_INVENTORY']:
                    if 'inventory_items' in response['responses'][
                            'GET_INVENTORY']['inventory_delta']:
                        for item in response['responses']['GET_INVENTORY'][
                                'inventory_delta']['inventory_items']:
                            if not 'inventory_item_data' in item:
                                continue
                            if not 'item' in item['inventory_item_data']:
                                continue
                            if not 'item_id' in item['inventory_item_data'][
                                    'item']:
                                continue
                            if not 'count' in item['inventory_item_data'][
                                    'item']:
                                continue
                            self.inventory.append(item['inventory_item_data'][
                                'item'])

    def pokeball_inventory(self):
        self.api.get_player().get_inventory()

        inventory_req = self.api.call()
        try:
            inventory_dict = inventory_req['responses']['GET_INVENTORY'][
                'inventory_delta']['inventory_items']
        except KeyError as e:
            print(str(e))
            balls_stock = {1: 0, 2: 0, 3: 0, 4: 0}
            return balls_stock

        user_web_inventory = 'web/inventory-%s.json' % (self.config.username)
        with open(user_web_inventory, 'w') as outfile:
            json.dump(inventory_dict, outfile)

        # get player balls stock
        # ----------------------
        balls_stock = {1: 0, 2: 0, 3: 0, 4: 0}

        for item in inventory_dict:
            try:
                # print(item['inventory_item_data']['item'])
                item_id = item['inventory_item_data']['item']['item_id']
                item_count = item['inventory_item_data']['item']['count']

                if item_id == Item.ITEM_POKE_BALL.value:
                    # print('Poke Ball count: ' + str(item_count))
                    balls_stock[1] = item_count
                if item_id == Item.ITEM_GREAT_BALL.value:
                    # print('Great Ball count: ' + str(item_count))
                    balls_stock[2] = item_count
                if item_id == Item.ITEM_ULTRA_BALL.value:
                    # print('Ultra Ball count: ' + str(item_count))
                    balls_stock[3] = item_count
            except:
                continue
        return balls_stock

    def item_inventory_count(self, id):
        self.api.get_player().get_inventory()

        inventory_req = self.api.call()
        try:
            inventory_dict = inventory_req['responses'][
                'GET_INVENTORY']['inventory_delta']['inventory_items']
        except KeyError as e:
            print(str(e))
            return 0

        item_count = 0

        for item in inventory_dict:
            try:
                if item['inventory_item_data']['item']['item_id'] == int(id):
                    item_count = item[
                        'inventory_item_data']['item']['count']
            except:
                continue
        return item_count

    def _set_starting_position(self):

        if self.config.test:
            # TODO: Add unit tests
            return

        if self.config.location:
            try:
                location_str = str(self.config.location)
                location = (self._get_pos_by_name(location_str.replace(" ", "")))
                self.position = location
                self.api.set_position(*self.position)
                logger.log('')
                logger.log(u'[x] Address found: {}'.format(self.config.location.decode(
                    'utf-8')))
                logger.log('[x] Position in-game set as: {}'.format(self.position))
                logger.log('')
                return
            except:
                logger.log('[x] The location given using -l could not be parsed. Checking for a cached location.')
                pass

        if self.config.location_cache and not self.config.location:
            try:
                #
                # save location flag used to pull the last known location from
                # the location.json
                with open('data/last-location-%s.json' %
                          (self.config.username)) as f:
                    location_json = json.load(f)

                    self.position = (location_json['lat'],
                                     location_json['lng'], 0.0)
                    self.api.set_position(*self.position)

                    logger.log('')
                    logger.log(
                        '[x] Last location flag used. Overriding passed in location')
                    logger.log(
                        '[x] Last in-game location was set as: {}'.format(
                            self.position))
                    logger.log('')

                    return
            except:
                if not self.config.location:
                    sys.exit(
                        "No cached Location. Please specify initial location.")
                else:
                    pass

    def _get_pos_by_name(self, location_name):
        # Check if the given location is already a coordinate.
        if ',' in location_name:
            possibleCoordinates = re.findall("[-]?\d{1,3}[.]\d{6,7}", location_name)
            if len(possibleCoordinates) == 2:
                # 2 matches, this must be a coordinate. We'll bypass the Google geocode so we keep the exact location.
                logger.log(
                    '[x] Coordinates found in passed in location, not geocoding.')
                return (float(possibleCoordinates[0]), float(possibleCoordinates[1]), float("0.0"))

        geolocator = GoogleV3(api_key=self.config.gmapkey)
        loc = geolocator.geocode(location_name, timeout=10)

        #self.log.info('Your given location: %s', loc.address.encode('utf-8'))
        #self.log.info('lat/long/alt: %s %s %s', loc.latitude, loc.longitude, loc.altitude)

        return (loc.latitude, loc.longitude, loc.altitude)

    def _filter_ignored_pokemons(self, cell):
        process_ignore = False
        try:
            with open("./data/catch-ignore.yml", 'r') as y:
                ignores = yaml.load(y)['ignore']
                if len(ignores) > 0:
                    process_ignore = True
        except Exception, e:
            pass

        if process_ignore:
            #
            # remove any wild pokemon
            try:
                for p in cell['wild_pokemons'][:]:
                    pokemon_id = p['pokemon_data']['pokemon_id']
                    pokemon_name = filter(
                        lambda x: int(x.get('Number')) == pokemon_id,
                        self.pokemon_list)[0]['Name']

                    if pokemon_name in ignores:
                        cell['wild_pokemons'].remove(p)
            except KeyError:
                pass

            #
            # remove catchable pokemon
            try:
                for p in cell['catchable_pokemons'][:]:
                    pokemon_id = p['pokemon_id']
                    pokemon_name = filter(
                        lambda x: int(x.get('Number')) == pokemon_id,
                        self.pokemon_list)[0]['Name']

                    if pokemon_name in ignores:
                        cell['catchable_pokemons'].remove(p)
            except KeyError:
                pass
コード例 #38
0
ファイル: __init__.py プロジェクト: ctfhacker/PokemonGo-Bot
 def start(self):
     self._setup_logging()
     self._setup_api()
     self.stepper = Stepper(self)
     random.seed()
コード例 #39
0
ファイル: bot.py プロジェクト: yan7109/PokemonGo-Bot
class PokemonGoBot(object):

    def __init__(self, config):
        self.config = config
        self.pokemon_list=json.load(open('pokemon.json'))
        self.item_list=json.load(open('items.json'))

    def start(self):
        self._setup_logging()
        self._setup_api()
        self.stepper = Stepper(self)
        random.seed()

    def take_step(self):
        self.stepper.take_step()

    def work_on_cell(self, cell, position):
        if 'catchable_pokemons' in cell:
            print '[#] Something rustles nearby!'
            for pokemon in cell['catchable_pokemons']:
                worker = PokemonCatchWorker(pokemon, self)
                worker.work()
        if 'wild_pokemons' in cell:
            for pokemon in cell['wild_pokemons']:
                worker = PokemonCatchWorker(pokemon, self)
                worker.work()
        if self.config.spinstop:
            if 'forts' in cell:
                # Only include those with a lat/long
                forts = [fort for fort in cell['forts'] if 'latitude' in fort and 'type' in fort]
                # Sort all by distance from current pos- eventually this should build graph & A* it
                forts.sort(key=lambda x: SeenFortWorker.geocalc(self.position[0], self.position[1], fort['latitude'], fort['longitude']))
                for fort in cell['forts']:
                    worker = SeenFortWorker(fort, self)
                    hack_chain = worker.work()
                    if hack_chain > 10:
                        print('need a rest')
                        break

    def _setup_logging(self):
        self.log = logging.getLogger(__name__)
        # log settings
        # log format
        logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(module)10s] [%(levelname)5s] %(message)s')
        # log level for http request class
        logging.getLogger("requests").setLevel(logging.WARNING)
        # log level for main pgoapi class
        logging.getLogger("pgoapi").setLevel(logging.INFO)
        # log level for internal pgoapi class
        logging.getLogger("rpc_api").setLevel(logging.INFO)

    def _setup_api(self):
        # instantiate pgoapi
        self.api = PGoApi()
        # provide player position on the earth

        self._set_starting_position()

        if not self.api.login(self.config.auth_service, self.config.username, self.config.password):
            return

        # chain subrequests (methods) into one RPC call

        # get player profile call
        # ----------------------
        self.api.get_player()

        response_dict = self.api.call()
        #print('Response dictionary: \n\r{}'.format(json.dumps(response_dict, indent=2)))
        currency_1="0"
        currency_2="0"

        player = response_dict['responses']['GET_PLAYER']['profile']

        ### @@@ TODO: Convert this to d/m/Y H:M:S
        creation_date = datetime.datetime.fromtimestamp(player['creation_time'] / 1e3)
        
        pokecoins = '0'
        stardust = '0'

        if 'amount' in player['currency'][0]:
            pokecoins = player['currency'][0]['amount']
        if 'amount' in player['currency'][1]:
            stardust = player['currency'][1]['amount']

        try:
            print('[#]')
            print('[#] Username: '******'username']))
            print('[#] Acccount Creation: ' + str(creation_date))
            print('[#] Bag Storage: ' + str(self.getInventoryCount('item')) + '/' + str(player['item_storage']))
            print('[#] Pokemon Storage: ' + str(self.getInventoryCount('pokemon')) + '/' + str(player['poke_storage']))
            print('[#] Stardust: ' + str(stardust))
            print('[#] Pokecoins: ' + str(pokecoins))
            self.getPlayerInfo()
            print('[#]')
        except:
             print('Exception during print player profile')
        self.update_inventory();

    def update_inventory(self):
        self.api.get_inventory()
        response = self.api.call()
        self.inventory = list()
        if 'responses' in response:
            if 'GET_INVENTORY' in response['responses']:
                if 'inventory_delta' in response['responses']['GET_INVENTORY']:
                    if 'inventory_items' in response['responses']['GET_INVENTORY']['inventory_delta']:
                        for item in response['responses']['GET_INVENTORY']['inventory_delta']['inventory_items']:
                            if not 'inventory_item_data' in item:
                                continue
                            if not 'item' in item['inventory_item_data']:
                                continue
                            if not 'item' in item['inventory_item_data']['item']:
                                continue
                            if not 'count' in item['inventory_item_data']['item']:
                                continue
                            self.inventory.append(item['inventory_item_data']['item'])

    def _set_starting_position(self):
        self.position = self._get_pos_by_name(self.config.location)
        self.api.set_position(*self.position)

        print('[x] Address found: ' + self.config.location)
        print('[x] Position in-game set as: ' + str(self.position))

        if self.config.test:
            return

    def _get_pos_by_name(self, location_name):
        geolocator = GoogleV3(api_key=self.config.gmapkey)
        loc = geolocator.geocode(location_name)

        print

        #self.log.info('Your given location: %s', loc.address.encode('utf-8'))
        #self.log.info('lat/long/alt: %s %s %s', loc.latitude, loc.longitude, loc.altitude)

        return (loc.latitude, loc.longitude, loc.altitude)


    ###########################################    
    ## @eggins pretty print functions
    ###########################################

    ## - Get count of inventory items and return the output for each
    def getInventoryCount(self, what):
        # Get contents of inventory
        self.api.get_inventory()
        response_dict = self.api.call()
        if 'responses' in response_dict:
            if 'GET_INVENTORY' in response_dict['responses']:
                if 'inventory_delta' in response_dict['responses']['GET_INVENTORY']:
                    if 'inventory_items' in response_dict['responses']['GET_INVENTORY']['inventory_delta']:
                        pokecount = 0
                        itemcount = 1
                        for item in response_dict['responses']['GET_INVENTORY']['inventory_delta']['inventory_items']:
                            #print('item {}'.format(item))
                            if 'inventory_item_data' in item:
                                if 'pokemon' in item['inventory_item_data']:
                                    pokecount = pokecount + 1
                                if 'item' in item['inventory_item_data']:
                                    if 'count' in item['inventory_item_data']['item']:
                                        itemcount = itemcount + item['inventory_item_data']['item']['count']
        if 'pokemon' in what:
            return pokecount
        if 'item' in what:
            return itemcount
        return '0'

    ## - Get more player information
    def getPlayerInfo(self):
        # Get contents of inventory
        self.api.get_inventory()
        response_dict = self.api.call()
        if 'responses' in response_dict:
            if 'GET_INVENTORY' in response_dict['responses']:
                if 'inventory_delta' in response_dict['responses']['GET_INVENTORY']:
                    if 'inventory_items' in response_dict['responses']['GET_INVENTORY']['inventory_delta']:
                        pokecount = 0
                        itemcount = 1
                        for item in response_dict['responses']['GET_INVENTORY']['inventory_delta']['inventory_items']:
                            #print('item {}'.format(item))
                            if 'inventory_item_data' in item:
                                if 'player_stats' in item['inventory_item_data']:
                                    playerdata = item['inventory_item_data']['player_stats']

                                    nextlvlxp = (int(playerdata['next_level_xp']) - int(playerdata['experience']))

                                    if 'level' in playerdata:
                                        print('[#] -- Level: ' + str(playerdata['level']))

                                    if 'experience' in playerdata:
                                        print('[#] -- Experience: ' + str(playerdata['experience']))
                                        print('[#] -- Experience until next level: ' + str(nextlvlxp))

                                    if 'pokemons_captured' in playerdata:
                                        print('[#] -- Pokemon Captured: ' + str(playerdata['pokemons_captured']))

                                    if 'poke_stop_visits' in playerdata:
                                        print('[#] -- Pokestops Visited: ' + str(playerdata['poke_stop_visits']))
コード例 #40
0
from numpy.random import randint, exponential
from numpy import arange, concatenate
import numpy as np
from pyglet.window import key

try:
    from toolbox.toolbox.IO.nidaq import DigitalInput, DigitalOutput, AnalogInput, AnalogOutput
    have_nidaq = True
except:  # Exception, e:
    print("could not import iodaq.")
    have_nidaq = False

sys.path.append('C:\github\syringe_pump')
from stepper import Stepper
import time
s = Stepper(mode='arduino', port='COM3', syringe='3mL')

MOUSE_ID = 'm1'
REWARD_VOLUME = 10  #in µL
REWARD_WINDOW = 1.0  #in seconds

try:
    opts, args = getopt.getopt(sys.argv, "hi:o:",
                               ["mouse_id=", "reward_volume="])
    print(args)
    MOUSE_ID = args[1]
    REWARD_VOLUME = int(args[2])
    REWARD_WINDOW = float(args[3])
    print(MOUSE_ID)
    print(REWARD_VOLUME)
    print(REWARD_WINDOW)
コード例 #41
0
ファイル: bot.py プロジェクト: TSM-EVO/PokemonGo-Bot
class PokemonGoBot(object):

    def __init__(self, config):
        self.config = config
        self.pokemon_list=json.load(open('pokemon.json'))
        self.item_list=json.load(open('items.json'))

    def start(self):
        self._setup_logging()
        self._setup_api()
        self.stepper = Stepper(self)

    def take_step(self):
        self.stepper.set_position()
        self.stepper.get_cells()
        self.catch_pokemon()

        if self.config.spinstop:
            self.goto_pokestop()
        else:
            self.stepper.step()

    def catch_pokemon(self):
        self.stepper.get_cells()
        surrounding_pokemon = ['catchable_pokemons', 'wild_pokemons']
        print "seaching for pokemon"
        for pokemon_type in surrounding_pokemon:
            for cell in self.stepper.cells:
                if pokemon_type in cell:
                    for pokemon in cell[pokemon_type]:
                       worker = PokemonCatchWorker(pokemon, self)
                       worker.work()

    def goto_pokestop(self):
        for cell in self.stepper.cells:
            if 'forts' in cell:
                for fort in cell['forts']:
                    if 'type' in fort:
                        worker = SeenFortWorker(cell, fort, self)
                        hack_chain = worker.work()
                        if hack_chain > 10:
                            print('need a rest')
                            break

    def _setup_logging(self):
        self.log = logging.getLogger(__name__)
        logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(module)10s] [%(levelname)5s] %(message)s')
        logging.getLogger("requests").setLevel(logging.WARNING)
        logging.getLogger("pgoapi").setLevel(logging.INFO)
        logging.getLogger("rpc_api").setLevel(logging.INFO)

    def _setup_api(self):
        self.api = PGoApi()
        self._set_starting_position()

        if not self.api.login(self.config.auth_service, self.config.username, self.config.password):
            return

        # chain subrequests (methods) into one RPC call

        # get player profile call
        # ----------------------
        self.api.get_player()

        response_dict = self.api.call()
        #print('Response dictionary: \n\r{}'.format(json.dumps(response_dict, indent=2)))
        currency_1="0"
        currency_2="0"
        try:
            if 'amount' in response_dict['responses']['GET_PLAYER']['profile']['currency'][0]:
                currency_1=response_dict['responses']['GET_PLAYER']['profile']['currency'][0]['amount']
            if 'amount' in response_dict['responses']['GET_PLAYER']['profile']['currency'][1]:
                currency_2=response_dict['responses']['GET_PLAYER']['profile']['currency'][1]['amount']
            print 'Profile:'
            print '    Username: '******'responses']['GET_PLAYER']['profile']['username'])
            print '    Bag size: ' + str(response_dict['responses']['GET_PLAYER']['profile']['item_storage'])
            print '    Pokemon Storage Size: ' + str(response_dict['responses']['GET_PLAYER']['profile']['poke_storage'])
            print '    Account Creation: ' + str(response_dict['responses']['GET_PLAYER']['profile']['creation_time'])
            print '    Currency: '
            print '        ' + str(response_dict['responses']['GET_PLAYER']['profile']['currency'][0]['type']) + ': ' + str(currency_1)
            print '        ' + str(response_dict['responses']['GET_PLAYER']['profile']['currency'][1]['type']) + ': ' + str(currency_2)
        except:
            print('Exception during print player profile')

    def _set_starting_position(self):
        self.position = self._get_pos_by_name(self.config.location)
        self.api.set_position(*self.position)
        print(self.position)
        if self.config.test:
            return

    def _get_pos_by_name(self, location_name):
        geolocator = GoogleV3(api_key=self.config.gmapkey)
        loc = geolocator.geocode(location_name)

        self.log.info('Your given location: %s', loc.address.encode('utf-8'))
        self.log.info('lat/long/alt: %s %s %s', loc.latitude, loc.longitude, loc.altitude)

        return (loc.latitude, loc.longitude, loc.altitude)