Exemple #1
0
    def __init__( self, robotName, skinImgs, screen, initPos, initDir ):
        """
            'robotName' - String com um máximo de 15 caracteres que indica o nome do robot.            
            'skinImgs' - Lista com as imagens para o corpo, arma e radar do robot. [ bodyImg, gunImg, radarImg ]
            screen - objecto do tipo 'pygame.display' onde o robot irá ficar.
            'initPos' - Tupla com o x e y iniciais
            'initDir' - Direcção inicial do robot
        """
        self._name = robotName
        # Imagem base que não vai ser alterada
        self._baseBodyImg = skinImgs[ 0 ]
        self.screen = screen
        
        # Imagem que vai sofrer as alterações para depois se dezenhada na Surface.
        self._bodyImg = None
        # Vai conter sempre o rectangulo actual da imagem
        self._bodyRect = self._baseBodyImg.get_rect()

        Gun.__init__( self, skinImgs[ 1 ] )
        Radar.__init__( self, skinImgs[ 2 ] )
        
        # Inicializa a posição do robot com a sua posição inicial
        x, y = initPos
        self.update( x, y, initDir, initDir, initDir )
        
        self.angle = 0
Exemple #2
0
    def __init__(self, name, x, y, radar_length, angle=-90, length=16):
        #set x,y and orientation posistion
        self.x = x
        self.y = y
        self.orientation = math.radians(-90)

        #set steering and acceleration/speed values
        self.steering_angle = 0.0
        self.previous_steering_angle = 0.0
        self.max_steering_angle = math.radians(30)
        self.acceleration = 0.0
        self.max_acceleration = 5.0
        self.speed = 0.0
        self.max_speed = 10

        #build car body based on the lenght
        self.car_length = 50
        self.car_width = 30
        self.wheel_length = 10
        self.wheel_width = 5

        #set params used for score calculation
        self.time = 200
        self.time_alive = 200
        self.checkpoint_passed = 2
        self.is_alive = True

        self.radar = Radar(self.x, self.y, 130,
                           (180, -90, -40, -15, 0, 15, 40, 90),
                           math.degrees(self.steering_angle))
Exemple #3
0
def main():
    config = Configuration("config.ini")
    logging.basicConfig(level=config.logging_level)
    logger = logging.getLogger('SpeedTrap')
    logger.info("SpeedTrap Starting")
    logger.info("Loading configuration file")
    if config.clear_local_on_start:
        LocalTools.clean_local(config)
    log_speed = LogSpeed(config)

    radar = Radar(config)
    execute_loop = True
    while execute_loop:
        try:
            current_report = radar.read_serial_buffer()
            if (len(current_report) > 0):
                try:
                    current_report_json = json.loads(current_report)
                    current_speed = abs(float(current_report_json['speed']))
                    logger.debug("Current speed is %s", current_speed)
                    log_speed.log_speed(current_speed)
                except:
                    pass
            else:
                log_speed.log_speed(0)
        except KeyboardInterrupt:
            execute_loop = False
    logger.info("SpeedTrap Terminating")
    while threading.active_count() > 1:
        logger.info('Waiting for %s threads to terminate.',
                    threading.active_count() - 1)
        time.sleep(1)
Exemple #4
0
class Main:
    def main(self):
        self.radar = Radar()
        self.radar.draw_radar()

        self.radar.display.getMouse()
        self.radar.display.close()
 def __init__(self, token):
     self.TOKEN = token
     locale.setlocale(locale.LC_ALL, '')
     self.days = [
         'todos os dias',
         'Segunda-Feira',
         'Terça-Feira',
         'Quarta-Feira',
         'Quinta-Feira',
         'Sexta-Feira',
         'Sábado',
         'Domingo',
     ]
     self.reg = [
         r'^\d*$',  # user_id
         r'^(\d\d[/]){2}\d{4}$',  # date
         r'^[1-9]+\d*$',  # blocks
         r'^\d+([,]\d+)?$',  # perc, capital
         r'^([a-zA-Z]{4}\d{1,2}|B3SA3)(, ?([a-zA-Z]{4}\d{1,2}|B3SA3))*?$',  # tickers
         r'^([0-1]\d|2[0-3]):[0-5]\d$',  # hour
     ]
     self.modes = ['SD', 'SW', 'MD', 'MW']
     self.sm_dw = {
         self.modes[0]: 'Small Caps/Diário',
         self.modes[1]: 'Small Caps/Semanal',
         self.modes[2]: 'Mid Large Caps/Diário',
         self.modes[3]: 'Mid Large Caps/Semanal',
     }
     self.rd = Radar()
Exemple #6
0
	def start(self):
			# start sec_div10 count
		self.sec_div10 = [-1]
		self.add_second()
			# create temporary list
		self.temporary_list = []
			# create enemy list
		self.enemy_list = []
			# create sub
		x_center = self.width//2
		y_center = self.height//2
		# Sub(x,y, color, size, lifes, atack_time, sec_div10, temporary_list, enemy_list)
		self.sub = Sub(
			x_center,
			y_center,
			self.color,
			self.size,
			self.lifes,
			self.atack_time,
			self.sec_div10,
			self.temporary_list,
			self.enemy_list)
			# create radar dots
		qtd = self.n_dots
		width = self.width / qtd
		height = self.height / qtd
		self.dot_list = []
		for i in range(qtd):
			for j in range(qtd):
				# Dot(x, y, color, size, time_fade, start_fadein)
				self.dot_list.append(Dot(
									width*j+width//2,
									height*i+height//2,
									self.color,
									0,
									self.time_fadeout, False))
			# create radar
		# Radar(sub, range, add_angle, dot_list, enemy_list)
		self.radar = Radar(
						self.sub,
						self.range_radar,
						360/self.time_radar,
						self.dot_list,
						self.enemy_list)
			# start enemies spawn countdown
		pygame.time.set_timer(pygame.USEREVENT+1, 5000)		# normal enemies
		pygame.time.set_timer(pygame.USEREVENT+2, 30000)	# boss
Exemple #7
0
def callback(data):
    """This callback function reacts to messages from CAN-bus bridge using rosserial"""
    #printing info about packet that has just arrived
    logfunction(data.id, data.timestamp, data.lenght, data.value, 0)

    #call appropriate instace depending on IDs
    if data.id == 20:
        Radar.sendpacket(RADARHCSR04, data.value)

    elif data.id == 21:
        Humidity.sendpacket(DHT11_HUM, data.value)

    elif data.id == 18:
        Temperature.sendpacket(DHT11, data.value)

    elif data.id == 19:
        Humidity.sendpacket(DHT11_HUM, data.value)
Exemple #8
0
def main():
    print("#auto drive start#")
    start_game()
    radar = Radar(HIT_X, HIT_Y)
    player = PlayerCharacter(radar)
    reactor.callWhenRunning(player.start)
    reactor.callWhenRunning(radar.start)
    reactor.run()
Exemple #9
0
def main():
    start_game()
    radar = Radar((HIT_X, HIT_Y))
    player = PlayerCharacter(radar)

    reactor.callWhenRunning(player.start)
    reactor.callWhenRunning(radar.start)
    reactor.run()
Exemple #10
0
def data(coords):
    niantic = Niantic()
    try:
        niantic.connect()
    except Exception as e:
        logger.error('%s: failed to connect: %s' % (coords, e))
        return ('Failed to connect', 500)
    radar = Radar(niantic)
    location = __parse_location(coords)
    if not location:
        return ('Invalid coordinates: %s' % coords, 400)
    try:
        data = radar.locate(location)
    except Exception as e:
        logger.error('%s: failed to locate: %s' % (coords, e))
        return ('Failed to locate', 500)
    return jsonify(pokemons=data.pokemons,
                   gyms=data.gyms,
                   pokestops=data.pokestops)
Exemple #11
0
    def __init__(self, surface):
        self.surface = surface
        self.x_pos = BORDER_SIZE
        self.y_pos = round(const.WIN_HEIGHT*2/3)
        self.width = const.WIN_LENGTH - 2*BORDER_SIZE
        self.height = round(const.WIN_HEIGHT/3 - BORDER_SIZE)

        radar_radius = round(self.height/2) - 20
        self.radar = Radar(self.x_pos + 5 + self.width - radar_radius - 10, \
            self.y_pos + round(self.height/2) + 2, radar_radius)

        self.sensors = Sensors(self.x_pos + 5, self.y_pos + 2)

        self.laser_button_n = DashButton((self.x_pos + 510, self.y_pos + 30, 70, 70))
        self.laser_button_s = DashButton((self.x_pos + 510, self.y_pos + 110, 70, 70))
        self.repair_switch = DashButton((self.x_pos + 350, self.y_pos + 70, 150, 100))
        self.laser_n_disabled = False
        self.laser_s_disabled = False
        self.repair_disabled = False
        self.cactus_button = DashButton((BORDER_SIZE, const.WIN_HEIGHT - BORDER_SIZE - 80, 55, 80))
Exemple #12
0
    def get_effective_measurement(self, t):

        # individual measures in array
        zs = np.array(
            [sensor.measure(self.target, t) for sensor in self.radars])

        # convert to cartesian
        cart_zs = np.array(
            [Radar.cartesian_measurement(measurement) for measurement in zs])

        # add the radar's position
        cart_zs = np.array([
            cart_zs[i] + self.radars[i].location[:2]
            for i in range(len(self.radars))
        ])

        # inverted individual covs (R_k^{-1})
        Rs = [
            np.linalg.inv(
                Radar.cartesian_error_covariance(zs[i],
                                                 self.radars[i].sigma_range,
                                                 self.radars[i].sigma_azimuth))
            for i in range(len(self.radars))
        ]

        # effective cov
        Rk = np.linalg.inv(np.sum(Rs, axis=0))

        # values for the sum to obtain z_k
        zk_sum_values = np.array(
            [np.matmul(Rs[i], cart_zs[i]) for i in range(len(self.radars))])

        # effective measurement
        zk = np.matmul(Rk, np.sum(zk_sum_values, axis=0))

        return zk, Rk
Exemple #13
0
 def __init__(self, location):
     self.name = "MazeRobotPieSlice"
     self.default_speed = 25.0
     self.default_turn_speed = 9.0
     self.actualRange = 40.0
     self.default_robot_size = 5.5 # radius of robot
     self.default_sensor_density = 5
     self.velocity = 0.0
     self.heading = math.pi/2
     self.location = location
     self.old_location = location
     self.time_step = 0.099
     self.heading_noise = 0.0
     self.rangefinders = []
     self.radars = []
     for i in range(0,5):
         between_angle = math.pi/4.0
         final_angle = math.pi/2-(between_angle*i)
         self.rangefinders.append(RangeFinder(final_angle, self.actualRange))
     for i in range(0,4):
         between_angle = math.pi/2.0
         start_angle = math.pi/4-(between_angle*i)
         self.radars.append(Radar(start_angle, start_angle + between_angle))
Exemple #14
0
def main():

    # Intervalo de tiempo en el que vamos a medir
    tiempo_inicial = datetime.datetime(2016, 3, 5, 1)
    tiempo_final = datetime.datetime(2016, 3, 5, 10)
    import math
    # parametros del generador de senales
    amplitud = 0.2
    fase = 1
    frecuencia = 20 * math.pi

    #Construir un nuevo genrador de senales

    Gen = Generador(amplitud, fase, frecuencia)

    #Construir un detector

    detector = Detector()

    #construir un nuevo radar

    radar = Radar(Gen, detector)

    # parametros para un blanco

    amplitud_de_frecuencia_del_blanco = amplitud + 100
    tiempo_inicial_b = datetime.datetime(2016, 3, 5, 2)
    tiempo_final_b = datetime.datetime(2016, 3, 5, 6)

    # Construir un nuevo blanco

    blanco = Blanco(amplitud_de_frecuencia_del_blanco, tiempo_inicial_b,
                    tiempo_final_b)

    lista_blancos = [blanco]

    #Construir un medio

    medio = Medio(lista_blancos)

    #Hago funcionar el radar

    radar.detectar(medio, tiempo_inicial, tiempo_final)
    radar.graficar(medio, tiempo_inicial, tiempo_final)
Exemple #15
0
#title
title = myfont.render("PiAware Radar", 1, GREEN)
screen.blit(title, TITLEPOS)
sac = myfont.render("stuffaboutcode.com", 1, GREEN)
screen.blit(sac, (TITLEPOS[0], TITLEPOS[1] + LINESPACE))

#flight data timer
flight_data_timer = None

#get the home position
home_x, home_y = lat_lon_to_x_y(args.lat, args.lon)

#startup the radar
radar = Radar(screen,
              RADARRECT,
              radar_pos=(home_x, home_y),
              scale=scale,
              back_col=BLACK,
              radar_col=GREEN)
radar.start()

#get the flight data
myflights = FlightData(data_url=piaware_url)

done = False
next_refresh = pygame.time.get_ticks()
while not done:

    #should the flights be refreshed
    if pygame.time.get_ticks() > next_refresh:

        #keep a track of the last aircraft we saw
Exemple #16
0
def exercise_4():

    colors = ['b', 'g', 'm', 'c', 'y']
    car = target

    time = np.linspace(0, car.location[0] / car.v, 900)

    trajectory = np.array([car.position(t) for t in time])

    # 4.2 Measurements transformation

    fig = plt.figure()

    for i, radar in enumerate(radars, start=1):
        measurements = [radar.measure(car, t) for t in time]
        trans_measures = np.array([
            Radar.cartesian_measurement(m) + radar.location[:2]
            for m in measurements
        ])
        plt.plot(trans_measures[:, 0],
                 trans_measures[:, 1],
                 c=colors[(i % 5) - 1],
                 label='Radar %s Measurements' % i)

    plt.plot(trajectory[:, 0],
             trajectory[:, 1],
             c='r',
             label='Real trajectory')
    plt.title('Trajectory and Radars Measurements')
    plt.legend()
    plt.xlabel('X-axis (m)')
    plt.ylabel('Y-axis (m)')
    plt.show()

    # 4.3 Kalman Filter

    time_limit = car.location[0] / car.v
    kalman = KalmanFilter(radars, car, delta_t=2)
    kalman.filter(time_limit)

    fig = plt.figure()
    plt.plot(trajectory[:, 0],
             trajectory[:, 1],
             c='r',
             label='Target Trajectory')
    plt.plot(kalman.track[:, 0], kalman.track[:, 1], c='g', label='Track')
    plt.xlabel('X-axis (m)')
    plt.ylabel('Y-axis (m)')
    plt.title('Real Trajectory vs Track using Kalman Filter')
    plt.legend(loc='upper right')
    plt.xlim(-1000, 12000)
    plt.ylim(-2000, 2000)
    # plt.show()

    kalman.d_retro(time_limit)
    #
    fig = plt.figure()
    plt.plot(trajectory[:, 0],
             trajectory[:, 1],
             c='r',
             label='Target Trajectory')
    plt.plot(kalman.no_filtered_track[:, 0],
             kalman.no_filtered_track[:, 1],
             c='y',
             label='Predicted Track')
    plt.plot(kalman.track[:, 0],
             kalman.track[:, 1],
             c='g',
             label='Filtered Track')
    plt.plot(kalman.retro_track[:, 0],
             kalman.retro_track[:, 1],
             c='b',
             label='Track with retrodiction')
    plt.xlabel('X-axis (m)')
    plt.ylabel('Y-axis (m)')
    plt.title(
        'Real Trajectory vs Track using Kalman Filter vs Track using retrodiction'
    )
    plt.legend(loc='upper right')
    plt.xlim(-1000, 12000)
    plt.ylim(-2000, 2000)
    plt.show()

    # error calculation:
    err = np.sum(
        np.sqrt(
            np.sum((trajectory[:, 0] - kalman.retro_track[:, 0])**2 +
                   (trajectory[:, 1] - kalman.retro_track[:, 1])**2)))
    print('Error of the track when applying retrodiction: ')
    print(err)

    # error calculation:
    err = np.sum(
        np.sqrt(
            np.sum((trajectory[:, 0] - kalman.track[:, 0])**2 +
                   (trajectory[:, 1] - kalman.track[:, 1])**2)))
    print('Error of the track without retrodiction: ')
    print(err)
Exemple #17
0
 def __init__(self):
     self._camera = Camera()
     self._radars = [Radar('test', 18, 24)]
     self._agent = Agent()
Exemple #18
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-c",
                        "--config",
                        dest="filename",
                        help="load configuration file",
                        required=True)
    config_filename = parser.parse_args().filename
    config = Configuration(config_filename)
    logging.basicConfig(filename=config.logging_path,
                        level=config.logging_level)
    logger = logging.getLogger('SpeedTrap')
    logger.info("SpeedTrap Starting")
    logger.info("Configuration file successfully loaded")
    logger.debug("%s", config)
    if config.clear_local_on_start:
        LocalTools.clean_local(config)
    # log_speed = LogSpeed(config)
    execute_loop = True
    radar = Radar(config)

    # Create pipes for inter-process communication
    video_queue = Queue()  # Video Ring Buffer

    logger.debug("Starting video capture Process")
    capture_video = CaptureVideo(config)
    capture_parent, capture_child = Pipe()
    capture_speed_parent, capture_speed_child = Pipe()
    capture_process = Process(target=capture_video.capture,
                              args=(capture_child, capture_speed_child,
                                    video_queue))
    capture_process.start()
    logger.info("Video capture Process started")

    logger.debug("Starting video record Process")
    record_video = RecordVideo(config)
    record_parent, record_child = Pipe()
    record_process = Process(target=record_video.record,
                             args=(record_child, video_queue))
    record_process.start()
    logger.info("Video record Process started")

    logger.debug("Starting scribe Process")
    data_recorder = Scribe(config)
    data_parent, data_child = Pipe()
    data_process = Process(target=data_recorder.capture, args=(data_child, ))
    data_process.start()
    logger.info("Scribe Process started")

    # Tracking if we are currently recording so we don't accidentally create a race condition
    recording = False
    speed = 0
    logger.debug("Starting radar polling loop")
    while execute_loop:
        try:
            if record_parent.poll():
                record_result = record_parent.recv()
                logger.debug("Message received on record_parent Pipe()")
                if type(record_result) is SpeedRecord:
                    logger.debug("Received message is a SpeedRecord")
                    logger.debug("Sending message on data_parent Pipe()")
                    data_parent.send(record_result)  # Log Data
                    # Change the behavior of the capture process back to its default.
                    recording = False
                    capture_parent.send(0)
            current_report = radar.read_serial_buffer()
            if len(current_report) > 0:
                try:
                    current_report_json = json.loads(current_report)
                    speed = abs(float(current_report_json['speed']))
                except:
                    pass
            else:
                speed = 0
            logger.debug("Current speed is %s", speed)
            logger.debug(
                "Sending message of %s to capture_speed_parent Pipe()", speed)
            capture_speed_parent.send(speed)
            if speed > config.record_threshold and recording is False:
                recording = True
                # Change the behavior of the video capture and recording process to record mode
                logger.debug("Sending message of 1 to capture_parent Pipe()")
                capture_parent.send(1)
                logger.debug("Sending message of 1 to record_parent Pipe()")
                record_parent.send(1)
        except KeyboardInterrupt:
            execute_loop = False
    logger.info("SpeedTrap Terminating")
Exemple #19
0
	drone_ready        = 2;	# Drone on his spot and operational
	drone_flying       = 3;	# Drone in mission flying through the target
	drone_back         = 4;	# Drone back of a mission ready for inspection
	drone_destroyed    = 5;	# Drone destroyed during a mission
	drone_detected     = 6;	# Drone ennemi dedetected
	
	p                  = 30
	
	utils              = Utils(thread_list);
	
	Win                = Window(utils, thread_list);

	utils.canvas       = Win.get_canvas();
	utils.label_list   = Win.get_label_list();
	utils.win          = Win;
	
	radar = Radar(utils, thread_list, Win.get_canvas(), Win.get_label_list(), Win.get_repare_b());
	thread_list.append(radar);
	print ("---- Drones 1 to "+str(g.NUMBER_DRONE)+" initialization ----");
	for i in range(g.NUMBER_DRONE):
		print ("Drone : "+ str(i+1));
		X = ((Win.get_width_zone() - g.NUMBER_DRONE * p) / 2 + p * i + p/2) * g.DIMENSION_COEFFICIENT;
		Y = Win.get_origine_Y() - 20 * g.DIMENSION_COEFFICIENT;
		Z = 0;
		drone = Drone(utils, Win.get_canvas(), i, X, Y, Z, thread_list, Win.get_label_list()[i]);
		thread_list.append(drone);


	radar.start();
	
	Win.get_window().mainloop();
Exemple #20
0
class Py1bitSub:
	def __init__(self, width, height, title):
		self.width = width
		self.height = height
		self.win = pygame.display.set_mode((width, height))
		pygame.display.set_caption(title)
		icon = pygame.image.load("icon.png")
		pygame.display.set_icon(icon)

		self.clock = pygame.time.Clock()
		self.running = True
		self.game_running = True
		self.display_end_screen = True
		self.FPS = 60
		self.background = (0, 0, 0)
		self.difficulty = 0

		self.time_radar = self.FPS * 4 	# seconds to complete a cicle
		self.range_radar = 250
		self.time_fadeout = 200
		self.n_dots = 25				# this will be squared

		self.atack_time = 5 	# seconds to sub atack
		self.color = (50, 175, 40)	# green
		self.size = 7
		self.lifes = 5

	def add_second(self):
		self.sec_div10[0] += 1
		self.difficulty = int( (self.sec_div10[0]/10)//60 )
		pygame.time.set_timer(pygame.NUMEVENTS-1, 100)		# wait 1/10 sec

	def start(self):
			# start sec_div10 count
		self.sec_div10 = [-1]
		self.add_second()
			# create temporary list
		self.temporary_list = []
			# create enemy list
		self.enemy_list = []
			# create sub
		x_center = self.width//2
		y_center = self.height//2
		# Sub(x,y, color, size, lifes, atack_time, sec_div10, temporary_list, enemy_list)
		self.sub = Sub(
			x_center,
			y_center,
			self.color,
			self.size,
			self.lifes,
			self.atack_time,
			self.sec_div10,
			self.temporary_list,
			self.enemy_list)
			# create radar dots
		qtd = self.n_dots
		width = self.width / qtd
		height = self.height / qtd
		self.dot_list = []
		for i in range(qtd):
			for j in range(qtd):
				# Dot(x, y, color, size, time_fade, start_fadein)
				self.dot_list.append(Dot(
									width*j+width//2,
									height*i+height//2,
									self.color,
									0,
									self.time_fadeout, False))
			# create radar
		# Radar(sub, range, add_angle, dot_list, enemy_list)
		self.radar = Radar(
						self.sub,
						self.range_radar,
						360/self.time_radar,
						self.dot_list,
						self.enemy_list)
			# start enemies spawn countdown
		pygame.time.set_timer(pygame.USEREVENT+1, 5000)		# normal enemies
		pygame.time.set_timer(pygame.USEREVENT+2, 30000)	# boss

	def create_enemy(self):
		# create enemy
		type = randint(1,3)	# type of enemies
		qtd = randint(1,3)	# number of enemies
		for _ in range(qtd):
			# random pos in x axis
			if randint(0,1) == 0:
				x = randint(0,self.width)
				y = 0 if randint(0,1) == 0 else self.height	#
			# random pos in y axis
			else:
				x = 0 if randint(0,1) == 0 else self.width	#
				y = randint(0,self.height)
			# Enemy(x,y, type, color, size, time_fade, sec_div10, temporary_list, sub)
			self.enemy_list.append(Enemy(
									x,
									y,
									type,
									self.color,
									self.size,
									self.time_fadeout,
									self.sec_div10,
									self.temporary_list,
									self.sub))
		# call in another 6 to 9 sec
		time = randint(6,9) - self.difficulty
		if time < 0: time = 0
		pygame.time.set_timer(pygame.USEREVENT+1, time*1000)

	def create_boss(self):
		# create boss
		# random pos in x axis
		if randint(0,1) == 0:
			x = randint(0,self.width)
			y = 0 if randint(0,1) == 0 else self.height	#
		# random pos in y axis
		else:
			x = 0 if randint(0,1) == 0 else self.width	#
			y = randint(0,self.height)
		# Enemy(x,y, type, color, size, time_fade, sec_div10, temporary_list, sub)
		self.enemy_list.append(Enemy(
								x,
								y,
								0,
								self.color,
								self.size,
								self.time_fadeout,
								self.sec_div10,
								self.temporary_list,
								self.sub))
		# call in another 30 to 45 sec
		time = randint(30,45) - self.difficulty*3
		if time < 0: time =0
		pygame.time.set_timer(pygame.USEREVENT+2, time*1000)


	def stats(self, window):
		font = pygame.font.SysFont("calibri", 20)
		porcentage = self.sub.atack_ready_porcent()
		srt_porcentage = "#"*(self.atack_time-porcentage) + "_"*porcentage
		text = "bomb: ["+srt_porcentage+"]"
		text += " lifes:"+str(self.sub.lifes)
		text += " difficulty:"+str(self.difficulty)
		text += " sec:"+str(self.sec_div10[0]/10)
		textbox = font.render(text, True, self.color)
		x = 15
		y = self.height - textbox.get_height() - 15
		window.blit(textbox, (x,y))

	def input(self, keys):
		margin = 15
		# Player Controls
		if keys[pygame.K_a] or keys[pygame.K_LEFT]:
			if self.sub.x > 0 + margin:
				self.sub.accelerate(-1,0)
		if keys[pygame.K_d] or keys[pygame.K_RIGHT]:
			if self.sub.x < self.width - margin:
				self.sub.accelerate(1,0)
		if keys[pygame.K_w] or keys[pygame.K_UP]:
			if self.sub.y > 0 + margin:
				self.sub.accelerate(0,-1)
		if keys[pygame.K_s] or keys[pygame.K_DOWN]:
			if self.sub.y < self.height - margin:
				self.sub.accelerate(0,1)
		if keys[pygame.K_SPACE]:
			self.sub.atack()
		if keys[pygame.K_ESCAPE]:
			self.game_running = False

	def logic(self):
		for dot in self.dot_list:			# radar dots
			dot.update()
		self.sub.update()					# player
		for enemy in self.enemy_list:		# enemies
			enemy.update()
		if not self.sub.is_alive():		# player died
			self.game_running = False
		self.radar.update()					# radar
		for _ in range(len(self.temporary_list)):
			temp = self.temporary_list.pop()
			if temp[0] > 0:
				temp[1].update()
				self.temporary_list.append( (temp[0]-1, temp[1]) )


	def render(self, window):
		window.fill(self.background)		# background
		for dot in self.dot_list:			# radar dots
			dot.render(window)
		for temp in self.temporary_list:	# explosions
			temp[1].render(window)
		for enemy in self.enemy_list:		# enemies
			enemy.render(window)
		self.sub.render(window)				# player
		self.stats(window)					# stats
		pygame.display.update()				# update screen


	def settings(self):
		entry = ""
		while entry != "/quit":
			print("type: /quit to save and leave settings")
			print("/n_dots to change number of dots in radar")
			print("/lifes to change your number of lifes")
			print("/radar_time to change the number of seconds to complete a turn")
			print("/radar_range to change the range to see enemies")
			entry = input()
			if entry == "/n_dots":
				print("current number: "+str(self.n_dots))
				print("enter the number of dots (this number will be squared)")
				self.n_dots = int(input())
			elif entry == "/lifes":
				print("current number: "+str(self.lifes))
				print("enter the number of lifes")
				self.lifes = int(input())
			elif entry == "/radar_time":
				print("current number: "+str(self.time_radar/self.FPS))
				print("enter the number of lifes")
				self.time_radar = self.FPS * int(input())
			elif entry == "/radar_range":
				print("current number: "+str(self.range_radar))
				print("enter the number of lifes")
				self.range_radar = int(input())
		print("settings have been saved, you can go back to the game")


	def wait_to_start(self):
		font = pygame.font.SysFont("calibri", 40)
		text = font.render("Press G to start", True, self.color)
		x = self.width//2 - text.get_width()//2
		y = self.height//4 - text.get_height()//2
		self.win.blit(text, (x,y))

		font = pygame.font.SysFont("calibri", 30)
		text = font.render("use wasd to move", True, self.color)
		x = self.width//2 - text.get_width()//2
		y = self.height//2 - text.get_height()//2
		self.win.blit(text, (x,y))

		text = font.render("space to atack", True, self.color)
		x = self.width//2 - text.get_width()//2
		y = self.height//2 + text.get_height()//2
		self.win.blit(text, (x,y))

		font = pygame.font.SysFont("calibri", 17)
		text = font.render("press C to open game settings on terminal", True, self.color)
		x = self.width//2 - text.get_width()//2
		y = self.height - text.get_height()*5
		self.win.blit(text, (x,y))

		text = font.render("made by Paulo BF Almeida", True, self.color)
		x = self.width//2 - text.get_width()//2
		y = self.height - text.get_height()*2
		self.win.blit(text, (x,y))

		pygame.display.update()

		while True:							# wait to player press 'g'
			event = pygame.event.wait()
			if event.type == pygame.QUIT:	# kill screen
				self.game_running = False
				self.running = False
				self.display_end_screen = False
				break
			if event.type == pygame.KEYDOWN:
				if event.key == pygame.K_g:	# start game
					break
				if event.key == pygame.K_c:	# start game
					self.settings()


	def end_screen(self):
		font = pygame.font.SysFont("calibri", 30)
		text = font.render("press G to start a new game", True, self.color)
		x = self.width//2 - text.get_width()//2
		y = self.height//4 - text.get_height()//2
		self.win.blit(text, (x,y))

		text = font.render("You died", True, self.color)
		x = self.width//2 - text.get_width()//2
		y = self.height//2 - text.get_height()//2
		self.win.blit(text, (x,y))

		points = self.sub.generate_points(self.difficulty, self.lifes)
		text = font.render("points:"+str(points), True, self.color)
		x = self.width//2 - text.get_width()//2
		y = self.height//2 + text.get_height()//2
		self.win.blit(text, (x,y))

		pygame.display.update()

		while True:							# wait to player press 'g'
			event = pygame.event.wait()
			if event.type == pygame.QUIT:	# kill screen
				self.running = False
				self.game_running = False
				self.display_end_screen = False
				break
			if event.type == pygame.KEYDOWN:
				if event.key == pygame.K_g:	# start game
					self.game_running = True
					break
Exemple #21
0
class Dashboard:
    def __init__(self, surface):
        self.surface = surface
        self.x_pos = BORDER_SIZE
        self.y_pos = round(const.WIN_HEIGHT*2/3)
        self.width = const.WIN_LENGTH - 2*BORDER_SIZE
        self.height = round(const.WIN_HEIGHT/3 - BORDER_SIZE)

        radar_radius = round(self.height/2) - 20
        self.radar = Radar(self.x_pos + 5 + self.width - radar_radius - 10, \
            self.y_pos + round(self.height/2) + 2, radar_radius)

        self.sensors = Sensors(self.x_pos + 5, self.y_pos + 2)

        self.laser_button_n = DashButton((self.x_pos + 510, self.y_pos + 30, 70, 70))
        self.laser_button_s = DashButton((self.x_pos + 510, self.y_pos + 110, 70, 70))
        self.repair_switch = DashButton((self.x_pos + 350, self.y_pos + 70, 150, 100))
        self.laser_n_disabled = False
        self.laser_s_disabled = False
        self.repair_disabled = False
        self.cactus_button = DashButton((BORDER_SIZE, const.WIN_HEIGHT - BORDER_SIZE - 80, 55, 80))

    def take_damage(self, damage=1):
        """Decreases the Hull bar by the amount given, or 1 if none is given.

        Args:
            damage (int, optional): Damage dealt. Defaults to 1.
        """
        self.sensors.hull_bar.change_value(damage*-1)
        if damage is not 0:
            SOUNDS['damage'].play()

    def lose_water(self, water_loss=1):
        """Decreases the Water bar by the amount given, or 1 if none is given.

        Args:
            water_loss (int, optional): Water spent. Defaults to 1.
        """
        self.sensors.water_bar.change_value(water_loss*-1)
        if water_loss is not 0:
            SOUNDS['sprinkler'].play()

    def get_health(self):
        """Getter that returns the health of the hull.
        """
        return self.sensors.hull_bar.value

    def get_water(self):
        """Getter that returns the water left in the tank.
        """
        return self.sensors.water_bar.value

    def draw(self, sprinklers, lightyears, level, is_repairing=False):
        # Many values here are magic numbers. This layout will be pretty messed up if
        # we change WIN_LENGTH or WIN_HEIGHT
        self.radar.draw(self.surface)
        if not (self.sensors.disabled or self.sensors.broken):
            self.sensors.draw(self.surface)
        number_text = const.DIGITAL_FONT.render(str(lightyears), True, const.YELLOW)
        pygame.draw.rect(self.surface, const.BLACK, (self.x_pos + 75, self.y_pos + 115, \
            number_text.get_width() + 20, number_text.get_height() + 10))
        self.surface.blit(number_text, (self.x_pos + 85, self.y_pos + 125))

        if level <= 2:
            self.surface.blit(IMAGES['dashboard_sans_lever'], (self.x_pos-10, self.y_pos))
        elif level == 3:
            self.surface.blit(IMAGES['dashboard'], (self.x_pos-10, self.y_pos))
        if self.sensors.disabled or self.sensors.broken:
            self.sensors.draw(self.surface)

        hull_text = const.DEFAULT_FONT_SM.render("Hull", True, const.BLACK)
        self.surface.blit(hull_text, (self.x_pos + 68 - hull_text.get_width(), self.y_pos + 10))
        water_text = const.DEFAULT_FONT_SM.render("Water", True, const.BLACK)
        self.surface.blit(water_text, (self.x_pos + 68 - water_text.get_width(), self.y_pos + 20 + BAR_WIDTH))
        radar_text = const.DEFAULT_FONT_SM.render('Radar', True, const.BLACK)
        self.surface.blit(radar_text, (self.x_pos + 600, self.y_pos + BORDER_SIZE))

        cactus = pygame.transform.scale(IMAGES['cactus'], (55, 80))
        self.surface.blit(cactus, (BORDER_SIZE, \
            const.WIN_HEIGHT - BORDER_SIZE - cactus.get_height()))

        # available sprinklers
        sprinkler_text = const.DEFAULT_FONT_SM.render('Sprinklers Available', True, const.BLACK)
        self.surface.blit(sprinkler_text, (self.x_pos + 300, self.y_pos + BORDER_SIZE))
        for i in range(sprinklers):
            self.surface.blit(IMAGES['sprinkler'], (self.x_pos + 300 + i*50, \
                self.y_pos + BORDER_SIZE + sprinkler_text.get_height()))

        # lightyears to destination
        lightyear_text = const.DEFAULT_FONT_SM.render('Lightyears to', True, const.BLACK)
        spaceport_text = const.DEFAULT_FONT_SM.render('Next Spaceport', True, const.BLACK)
        self.surface.blit(lightyear_text, (self.x_pos + 130, self.y_pos + 120))
        self.surface.blit(spaceport_text, (self.x_pos + 130, self.y_pos + 120 + lightyear_text.get_height()))

        # lasers
        laser_text = const.DEFAULT_FONT_SM.render('Lasers', True, const.BLACK)
        self.surface.blit(laser_text, (self.x_pos + 515, self.y_pos + BORDER_SIZE))

        if self.laser_n_disabled:
            pygame.draw.rect(self.surface, (50, 50, 50), (self.x_pos + 510, self.y_pos + 38, 70, 70))
            fire_text = const.TITLE_FONT_SM.render("FIRE", True, (255, 127, 0))
            self.surface.blit(fire_text, (self.x_pos + 510 + (70 - fire_text.get_width())/2, self.y_pos + 53))

        if self.laser_s_disabled:
            pygame.draw.rect(self.surface, (50, 50, 50), (self.x_pos + 510, self.y_pos + 118, 70, 70))
            fire_text = const.TITLE_FONT_SM.render("FIRE", True, (255, 127, 0))
            self.surface.blit(fire_text, (self.x_pos + 510 + (70 - fire_text.get_width())/2, self.y_pos + 133))

        # repair button
        if level >= 3:
            repair_text = const.DEFAULT_FONT_SM.render('Repair Mode', True, const.BLACK)
            self.surface.blit(repair_text, (self.x_pos + 330, self.y_pos + 90))
            off_on_text = const.DEFAULT_FONT_SM.render('On            Off', True, const.BLACK)
            if not self.repair_disabled:
                self.surface.blit(off_on_text, (self.x_pos + 335, self.y_pos + 90 + repair_text.get_height()))
                if not is_repairing:
                    self.surface.blit(IMAGES['lever'], (self.x_pos + 320, self.y_pos + 133))
            else:
                pygame.draw.rect(self.surface, (50, 50, 50), (self.x_pos + 315, self.y_pos + 133, 135, 45))
                fire_text = const.TITLE_FONT_SM.render("ON FIRE", True, (255, 127, 0))
                self.surface.blit(fire_text, (self.x_pos + 315 + (135 - fire_text.get_width())/2, self.y_pos + 143))
Exemple #22
0
        self.textSurf = self.font.render("UAL121", 1, (86, 176, 91))
        self.surf.blit(self.textSurf, (9, 0))
        self.rect = self.surf.get_rect()
        self.x = 600 / radar.scale
        self.y = 300 / radar.scale
        self.heading = 60
        self.speed = 250

    def update(self, elapsed):
        self.h = ((self.speed * px_per_nm) / 3600 * (elapsed / 1000)) * 60
        self.x += (sin(radians(self.heading)) * self.h) / radar.scale
        self.y -= (cos(radians(self.heading)) * self.h) / radar.scale


asdex = Asdex(airport_data, screen_height, screen_width)
radar = Radar(airport_data, screen_height, screen_width)
aircraft = Aircraft()
elapsed = 1
sweep = 0
running = True
scene = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                scene = not scene

    if not scene:
        screen.blit(radar.surface, (0, 0))
Exemple #23
0
from car import Car
from radar import Radar

target = Car(v=20 * 1000 / 3600,
             a_x=10000.0,
             a_y=1000.0,
             a_z=1000.0)

radars = [
        Radar(x=0.0, y=100000.0, z=10000.0, sigma_range=10.0, sigma_azimuth=0.1),
        Radar(x=100000.0, y=0.0, z=10000.0, sigma_range=10.0, sigma_azimuth=0.1),
        # Radar(x=100000.0, y=100000.0, z=10000.0, sigma_range=10.0, sigma_azimuth=0.1),
        # Radar(x=0.0, y=-100000.0, z=10000.0, sigma_range=10.0, sigma_azimuth=0.1),
    ]
screen.blit(scale_text, (SCALETEXTRECT[0], SCALETEXTRECT[1]))

#title 
title = myfont.render("PiAware Radar", 1, GREEN)
screen.blit(title, TITLEPOS)
sac = myfont.render("stuffaboutcode.com", 1, GREEN)
screen.blit(sac, (TITLEPOS[0], TITLEPOS[1] + LINESPACE))

#flight data timer
flight_data_timer = None

#get the home position
home_x, home_y = lat_lon_to_x_y(args.lat, args.lon)

#startup the radar
radar = Radar(screen, RADARRECT, radar_pos = (home_x, home_y), scale = scale, back_col = BLACK, radar_col = GREEN)
radar.start()

#get the flight data
myflights = FlightData(data_url = piaware_url)

done = False
next_refresh = pygame.time.get_ticks()
while not done:
    
    #should the flights be refreshed
    if pygame.time.get_ticks() > next_refresh:

        #keep a track of the last aircraft we saw
        lastaircraftseen = deepcopy(myflights.aircraft)
        
Exemple #25
0
class Car:
    def __init__(self, name, x, y, radar_length, angle=-90, length=16):
        #set x,y and orientation posistion
        self.x = x
        self.y = y
        self.orientation = math.radians(-90)

        #set steering and acceleration/speed values
        self.steering_angle = 0.0
        self.previous_steering_angle = 0.0
        self.max_steering_angle = math.radians(30)
        self.acceleration = 0.0
        self.max_acceleration = 5.0
        self.speed = 0.0
        self.max_speed = 10

        #build car body based on the lenght
        self.car_length = 50
        self.car_width = 30
        self.wheel_length = 10
        self.wheel_width = 5

        #set params used for score calculation
        self.time = 200
        self.time_alive = 200
        self.checkpoint_passed = 2
        self.is_alive = True

        self.radar = Radar(self.x, self.y, 130,
                           (180, -90, -40, -15, 0, 15, 40, 90),
                           math.degrees(self.steering_angle))

    #When passing a checkpoint of the racetrack, reward the car with a bonus
    #First one to pass will get the max bonus, second one will recieve 500 points less
    def check_passed(self, racetrack):
        score = 0
        check1 = racetrack.checkpoints[self.checkpoint_passed]
        check2 = racetrack.checkpoints[self.checkpoint_passed + 1]
        p1 = [self.x - self.car_length / 4, self.y - self.car_width / 2]
        p2 = [self.x + (0.75 * self.car_length), self.y - self.car_width / 2]
        p3 = [self.x + (0.75 * self.car_length), self.y + self.car_width / 2]
        p4 = [self.x - self.car_length / 4, self.y + self.car_width / 2]

        corners = (p1, p2, p3, p4)

        c_x = self.x
        c_y = self.y
        delta_angle = self.orientation
        rotated_corners = []

        for p in corners:
            temp = []
            length = math.sqrt((p[0] - c_x)**2 + (c_y - p[1])**2)
            angle = math.atan2(c_y - p[1], p[0] - c_x)
            angle += delta_angle
            temp.append(c_x + length * math.cos(angle))
            temp.append(c_y - length * math.sin(angle))
            rotated_corners.append(temp)

        line1 = LineString((rotated_corners[0], rotated_corners[1],
                            rotated_corners[2], rotated_corners[3]))
        line2 = LineString([check1, check2])
        intersection1 = (line1.intersection(line2))

        if (isinstance(intersection1, shapely.geometry.multipoint.MultiPoint)):
            intersection1 = intersection1[len(intersection1) - 1]

        if (len(intersection1.coords) == 1):
            self.checkpoint_passed = self.checkpoint_passed + 2
            score = self.time_alive + 1000
            self.time_alive = self.time
        return score

    #Being alive is good, small reward
    def update_score(self):

        return 10
        a = math.degrees(self.steering_angle)
        b = math.degrees(self.previous_steering_angle)

        if (a > b):
            return -(100 - (a - b))
        else:
            return -(100 - (b - a))

    def distanceNextCheckpoint(self, racetrack):
        check = racetrack.checkpoints[self.checkpoint_passed]
        line = LineString(check)

        x = self.position.x
        y = self.position.y
        np = nearest_points(line, Point(x, y))[0]
        return calculate_distance(np.x, np.y, x, y)

    #update the car pos and angle
    def update(self, dt):
        #dunno yet
        #self.speed += (self.acceleration * dt, 0)
        #self.speed = max(-self.speed, min(self.speed, self.speed))

        theta = self.orientation  # initial orientation
        alpha = self.steering_angle  # steering angle
        dist = self.speed  # distance to be moved
        length = self.car_length  # length of the robot
        if abs(alpha) > self.max_steering_angle:
            raise ValueError('Exceeding max steering angle')

        # in local coordinates of robot
        beta = (dist / length) * math.tan(alpha)  # turning angle

        _x = _y = _theta = 0.0
        if beta > 0.001 or beta < -0.001:
            radius = dist / beta  # turning radius
            cx = self.x - math.sin(theta) * radius  # center of the circle
            cy = self.y - math.cos(theta) * radius  # center of the circle

            # in global coordinates of robot
            _x = cx + math.sin(theta + beta) * radius
            _y = cy + math.cos(theta + beta) * radius
            _theta = (theta + beta) % (2 * math.pi)

        else:  # straight motion
            _x = self.x + dist * math.cos(theta)
            _y = self.y - dist * math.sin(theta)
            _theta = (theta + beta) % (2 * math.pi)

        self.x = _x
        self.y = _y
        self.orientation = _theta
        self.steering_angle = alpha
        self.radar.updateRadar(self.x, self.y, math.degrees(self.orientation))
        self.time_alive -= 1
        '''
def main():
    """
  - Parse user-specified data from YaML
  - Check to see that the needed graphics are available. If not, get them.
  - Get the radar imagery, complete with warnings graphics
  - Get today's hazardous weather outlook statement and parse it
  - Check for FTM outage notifications
  - Get, parse, and write out current weather conditions to specified locations.
  - TODO: should run the getweather.sh shell script, that overlays/composites
    the weather graphics. At present, that shell script calls this script
    and runs the overlays with -bash-.
  - Check for and acquire current multi-band GOES-x imagery of a given resolution.
  """
    if os.path.exists('weatherwidget.log'):
        os.remove('weatherwidget.log')
    logging.basicConfig(
        filename='weatherwidget.log',
        level=logging.DEBUG,
        format='%(asctime)s %(levelname)s %(threadName)-10s %(message)s',
    )

    data = wf.load_settings_and_defaults(SETTINGS_DIR, 'settings.yml',
                                         'defaults.yml')
    if not data:
        logging.error('Unable to load settings files. These are required.')
        sys.exit(
            'settings files are required and could not be loaded successfully.'
        )

    logging.info('Checking for radar outage.')
    wf.outage_check(data)

    logging.info('Retrieving current weather observations.')
    right_now = Observation(data)
    right_now.get_current_conditions()
    right_now.get_backup_obs(use_json=False)
    right_now.merge_good_observations()
    logging.debug('Merged current conditions: %s', right_now.con1.obs)
    sum_con = right_now.conditions_summary()

    if right_now.con1.obs and sum_con:
        text_conditions, nice_con = right_now.format_current_conditions()
        logging.debug('Current conditions from primary source: %s', nice_con)
        wf.write_json(some_dict=nice_con,
                      outputdir=data['output_dir'],
                      filename='current_conditions.json')
    else:
        logging.error(
            'Something went wrong getting the current conditions. Halting.')
        return 1

    wf.write_text(os.path.join(data['output_dir'], 'current_conditions.txt'),
                  text_conditions)

    # Get radar image:
    current_radar = Radar(data)
    current_radar.check_assets()
    current_radar.get_radar()
    current_radar.get_warnings_box()
    if current_radar.problem:
        logging.error('Unable to retrieve weather radar image. Halting now.')

    # Hazardous Weather Outlook and alerts:
    today_alerts = Alerts(data)
    today_alerts.get_alerts()

    # Get hydrograph image.
    if wf.get_hydrograph(abbr=data['river_gauge_abbr'],
                         hydro_url=data['defaults']['water_url'],
                         outputdir=data['output_dir']).ok:
        logging.info('Requesting hydrograph for station %s, gauge "%s".',
                     data['radar_station'], data['river_gauge_abbr'])
    else:
        logging.error('Failed to get hydrograph information.')
        return 1

    forecast_obj = Forecast(data=data)
    logging.debug('Getting the forecasts.')
    forecast_obj.get_forecast()
    forecastdict = forecast_obj.parse_forecast()
    if forecastdict is None:
        logging.error('Unable to parse forecast!')
        return 1
    forecast_obj.write_forecast(outputdir=data['output_dir'])
    logging.debug('Getting area forecast discussion.')
    forecast_obj.get_afd()

    logging.debug('Getting zone forecast.')
    zoneforecast = ZoneForecast(data)
    zoneforecast.get()

    wf.write_json(some_dict=forecastdict,
                  outputdir=data['output_dir'],
                  filename='forecast.json')
    wsvg.make_forecast_icons(forecastdict, outputdir=data['output_dir'])

    # Satellite imagery:
    current_image = Imagery(band='GEOCOLOR', data=data)
    current_image.get_all()

    logging.info('Finished program run.')

    return 0
Exemple #27
0
import rospy
from agrosbuspkg.msg import CANFrameData  #info about packet from arduino
from humsensor import Humidity
from radar import Radar
from tempsensor import Temperature
#settings for topic to subscribe and Publish
rospy.init_node('ROSNODE', anonymous=True)  #node initialising
#setting publisher
PUB = rospy.Publisher('fromros', CANFrameData,
                      queue_size=10)  #for outgoing packets

#log level
LOG_LEVEL = 3  #affect logging level visble on the cmd-line

#RADAR HCSR04
RADARHCSR04 = Radar("hcsr04_topic", 2, 10, PUB)

#Temp/HUM DHT11
DHT11 = Temperature("dht11_topic", 1, 10)

#HUM DHT11
DHT11_HUM = Temperature("dht11_hum_topic", 1, 10)


def logfunction(msg_id, int_timestamp, msg_len, msg_payload, direction):
    """this function logs event with different levels"""
    s_timestamp = int_timestamp / 1000
    s_timestamp = datetime.datetime.fromtimestamp(s_timestamp)
    #direction = 1 -> outgoing packet direction=0 -> ingoing packet
    if direction == 0:
        direction = "Incoming packet "
Exemple #28
0
    if (start):
        dir = "down" if track.dir else "up"
        print track.id, "new track", dir
    else:
        print track.id, "end", len(track.speeds), track.maxSpeed, "mph"


def status(msg):
    sys.stderr.write(msg)
    sys.stderr.write("\n")


r = Radar(
    sampleRate=44100,
    alsaPeriod=1024,
    sampleBuffer=2048,
    #realtimeCallback=radarRealtimeStatus,
    #trackDebugCallback=radarTrackDebug,
    trackCallback=radarTrack)

try:
    status("Listening...")
    while (True):
        r.sample()

except alsaaudio.ALSAAudioError:
    status("No soundcard!")
except KeyboardInterrupt:
    status("Interrupted!")
except:
    status("Unexpected error!")
    exit(0)


signal.signal(signal.SIGINT, signal_handler)

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python {command} <port>".format(command=sys.argv[0]))
        exit(0)

    PORT = int(sys.argv[1])
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind((HOST, PORT))
    sock.listen(1)
    print("Listening on port {port} ...".format(port=PORT))

    client_socket, client_addr = sock.accept()
    print("Connected by: ", client_addr)

    radar = Radar(min_range=0, range_resolution=0.1)

    try:
        # Send config data first
        radar.send_config_packet(client_socket)

        # Commence data stream
        radar.start_data_stream(client_socket)
    except Exception as e:
        print(e)
        sock.close()
Exemple #30
0
			print("heyho")
			self.send(CANAL_HOKUYO, ".getdata")
			time.sleep(0.5)

	def cmd__getdata(self, **kwargs):
		"""
			Commande définie juste pour éviter de générer un message
			d'erreur sur irc lorsque un getdata est effectué
		"""
		pass

	def cmd__response(self, data, **kwargs):
		"""
			@param exploite les données renvoyées par l'hokuyo
		"""
		try:
			points = eval(data)
		except:
			pass
		else:
			self.radar.draw_points(points)


if __name__ == "__main__":
	radar = Radar()
	bot = RadarBot(radar, "10.42.43.1", 6667, True)
	t = threading.Thread(target=bot.start)
	t.setDaemon(True)
	t.start()
	radar.mainloop()
Exemple #31
0
import settings
import auth
from niantic import Niantic
from radar import Radar

token = auth.login(('google', '*****@*****.**', 'ijrjkflyjt xelj'))
auth.tokens[token.value] = token
niantic = Niantic()
radar = Radar(niantic)
niantic.connect()
location = (55.7538723, 37.6200955)
radar.locate(location)
class Functions():
    def __init__(self, token):
        self.TOKEN = token
        locale.setlocale(locale.LC_ALL, '')
        self.days = [
            'todos os dias',
            'Segunda-Feira',
            'Terça-Feira',
            'Quarta-Feira',
            'Quinta-Feira',
            'Sexta-Feira',
            'Sábado',
            'Domingo',
        ]
        self.reg = [
            r'^\d*$',  # user_id
            r'^(\d\d[/]){2}\d{4}$',  # date
            r'^[1-9]+\d*$',  # blocks
            r'^\d+([,]\d+)?$',  # perc, capital
            r'^([a-zA-Z]{4}\d{1,2}|B3SA3)(, ?([a-zA-Z]{4}\d{1,2}|B3SA3))*?$',  # tickers
            r'^([0-1]\d|2[0-3]):[0-5]\d$',  # hour
        ]
        self.modes = ['SD', 'SW', 'MD', 'MW']
        self.sm_dw = {
            self.modes[0]: 'Small Caps/Diário',
            self.modes[1]: 'Small Caps/Semanal',
            self.modes[2]: 'Mid Large Caps/Diário',
            self.modes[3]: 'Mid Large Caps/Semanal',
        }
        self.rd = Radar()

    def func_send_msg(self,
                      chat_id,
                      text,
                      reply_to_message_id='',
                      reply_markup=''):
        url = 'https://api.telegram.org/bot{}/sendMessage?' \
            'chat_id={}&text={}&reply_to_message_id={}&' \
            'reply_markup={}&parse_mode=HTML'
        requests.get(
            url.format(self.TOKEN, chat_id, text, reply_to_message_id,
                       reply_markup))

    def schedule(self):
        print('Scheduling user reports...')
        users = db.get_everything('users')
        if users:
            for user in users:
                if user[4]:
                    hour = self.rd.hour_fix(user[9])
                    kwargs = {
                        'user_id': user[0],
                        's_m': user[7],
                        'd_w': user[8],
                    }
                    self.rd.weekly(hour, self.func_radar_auto, str(user[0]),
                                   **kwargs)
        else:
            pass
        print('Reports scheduled.')

    def func_time(self, var, separator):
        if separator == '/':
            new_format = dtt.strptime(var, f'%d/%m/%Y').strftime(f'%Y-%m-%d')
        elif separator == '-':
            new_format = dtt.strptime(var, '%Y-%m-%d').strftime('%d/%m/%Y')
        return new_format

    def func_user_start(self, user_id, name, username):
        exists = db.get_info(user_id)
        if exists:
            admin_text = f'Usuário mandou novamente:\nuser_id: {user_id}\n' \
                         f'nome: {name}\nusername: @{username}'
            user_text = 'Você já deu o start! Algum problema? Pergunte ao @DanMMoreira!'
        else:
            dia = str(dtt.now().date())
            db.user_start(user_id, name, username, dia)
            admin_text = f'Novo usuário:\nuser_id: {user_id}\n' \
                         f'nome: {name}\nusername: @{username}'
            user_text = 'Bem-vindo, investidor! Por favor, aguarde até ser autorizado.'
        return admin_text, user_text

    def func_admin(self, msg, choice):
        info = msg.split(', ')
        # db.admin_queries(info_0, info_1, info_2, choice)
        # 0 se autoriza: info_0 = user_id, info_1 = full_name, info_2 = dia de hoje;
        # 1 se desativa: info_0 = user_id, info_1 = info_2 = '';
        # 2 se edita:    info_0 = user_id, info_1 = campo, info_2 = novo dado;
        # 3 se pesquisa: info_0 = campo, info_1 = pesquisa;
        # 4 pesquisa por data: info_0 = data inicial, info_1 = data final
        # 5 se reseta:   info_0 = user_id
        # The query:
        try:
            if choice < 3:
                y = re.match(self.reg[0], info[0])
                if not y:
                    response = 'Formato inválido! O user_id deve conter somente números. Tente novamente.'
                    return response, False
            if choice == 0:
                date = str(dtt.now().date())
                res = db.admin_queries(info[0], info[1], date, choice)
                action = 'autorizado'
            elif choice in {1, 5}:
                res = db.admin_queries(info[0], choice=choice)
                action = 'desativado' if choice == 1 else 'resetado'
            elif choice in {2, 3, 4}:
                if ((choice == 2 and re.match('^(nome|username|email)$', info[1], re.I)) \
                        or (choice == 3 and re.match('^(user_id|nome|username)$', info[0], re.I))):
                    if re.match('^nome$', info[0], re.I):
                        info[0] = info[0].replace('o', 'a')
                    if re.match('^nome$', info[1], re.I):
                        info[1] = info[1].replace('o', 'a')
                    res = db.admin_queries(info[0], info[1], choice=choice)

                elif (choice == 4 and re.match(self.reg[1], info[0]) \
                        and re.match(self.reg[1], info[1])):
                    info[0] = self.func_time(info[0], '/')
                    info[1] = self.func_time(info[1], '/')
                    res = db.admin_queries(info[0], info[1], choice=choice)
            # The response:
            if res == 0:
                response = 'Este usuário não existe! Tente novamente ou clique em /cancelar.'
                return response, False
            elif not res:
                response = 'Nada foi encontrado para essa pesquisa! Tente novamente ou clique em /cancelar.'
                return response, False
            elif choice in {0, 1, 5}:
                if res == 1:
                    response = f'Este usuário já está {action}!'
                else:
                    response = f'O usuário foi {action} com sucesso!'
            elif choice == 2:
                response = 'O campo foi editado com sucesso!'
            elif choice in {3, 4}:
                response = 'Resultados da pesquisa:\n\r\n\r'
                for item in res:
                    if item[3] == None: item[3] = '-'
                    item[4] = 'Desativado' if item[4] == '0' else 'Autorizado'
                    item[5] = self.func_time(item[5], '-')
                    response += (
                        f'user_id: {item[0]}\n\r'
                        f'Nome: {item[1]}\n\r'
                        f'username: {item[2]}\n\r'
                        f'E-mail: {item[3]}\n\r'
                        f'{item[4]}\n\r'
                        f'Data de entrada / última autorização: {item[5]}\n\r\n\r'
                    )
            return response, True
        except Exception as e:
            print(e)
            response = 'Formato inválido! Esqueceu algo? Tente novamente ou clique em /cancelar.'
            return response, False

    def func_init_check(self, mode, data, user_id='', all_data=''):
        if mode == 'B' and not re.match(self.reg[2], data):
            text = 'Formato inválido. Digite o valor dos bloquinhos neste formato ' \
                '(somente números, sem aspas): "8" ou "12". Tente novamente:'
            return text, False
        elif mode == 'P' and not re.match(self.reg[3], data):
            text = 'Formato inválido. Digite o valor do porcentual neste formato ' \
                '(somente números, sem aspas): "1,5" ou "2". Tente novamente:'
            return text, False
        elif mode in ['B', 'P']:
            text = 'Por último: qual o seu capital atual para investir pelo método ' \
                '(ex.: "1234,56", sem as aspas)?\r\n' \
                'Sem o capital, o gerenciamento de risco não funcionará, mas envie "0"'\
                ' (zero, sem as aspas) se não quiser responder. Ele serve para o cálculo ' \
                'automático do volume a ser comprado.'
            return text, True
        elif mode == 'p':
            if not re.match(self.reg[3], data):
                text = 'Formato inválido. Digite o valor do capital neste formato (somente números, sem aspas): ' \
                    '"1234,56" ou digite "0" se não quiser responder. Tente novamente:'
                return text, False
            else:
                hour = self.rd.hour_fix('10:30')
                kwargs = {
                    'user_id': user_id,
                    's_m': all_data[0],
                    'd_w': all_data[1],
                }
                self.rd.weekly(hour, self.func_radar_auto, str(user_id),
                               **kwargs)
                text = 'Tudo pronto!\nVocê irá receber relatórios diários conforme suas configurações ' \
                    'às 10:30. ' \
                    'Você pode mudar todas essas configurações através do /menu e ' \
                    'lá você também pode obter o relatório manualmente. Para saber mais informações ' \
                    'sobre o bot ou se precisa de ajuda, contate o desenvolvedor @DanMMoreira. ' \
                    'Este bot ainda está em fase de testes, portanto algumas coisas podem estar... ' \
                    'esquisitas. Mas muitas coisas estão por vir!\nAproveite!' # Se escolheu a escala Semanal, receberá apenas às segundas-feiras.
                return text, True

    def func_get_info(self, user_id):
        info = db.get_info(user_id)
        stock = 'Small Caps' if info[0][7] == 'S' else 'Mid Large Caps'
        freq = 'Diário' if info[0][8] == 'D' else 'Semanal'
        #day = self.days[0] if info[0][8] == 'D' else self.days[int(info[0][10])]
        if info[0][11] == 'B':
            risk = 'Bloquinho por operação\n\rBloquinhos: ' + info[0][12] + ''
        else:
            risk = 'Porcentagem relativa ao stop\n\rPorcentual: ' + info[0][
                12] + '%'
        text = 'MEU STATUS:\n\r\n\r' \
            'Capital: R$'+info[0][6]+'\n\r' \
            'Classe de ações padrão: '+stock+'\n\r' \
            'Escala temporal padrão: '+freq+'\n\r' \
            'Hora programada: ' \
            ''+info[0][9]+'\n\r' \
            'Gerenciamento de risco: '+risk #Hora e dia da semana programados:info[], day
        return text

    def func_portf_upd(self, user_id, msg, choice):
        if choice < 3 and re.match(self.reg[3], msg):
            if msg.rfind(','): msg = msg.replace(',', '.')
            msg = float(msg)
            portf = db.get_info(user_id)[0][6]
            if portf.rfind(','): portf = portf.replace(',', '.')
            portf = float(portf)
            if choice == 0: portf += msg
            if choice == 1: portf -= msg
            if choice == 2: portf = msg
            portf = '{:.2f}'.format(portf).replace('.', ',')
            db.info_upd(user_id, 'portf', portf)
            text = 'Pronto! O novo capital é de R$' + portf + '.\n\rAté mais!'
            return text, True
        elif choice == 3 and re.match('^(Sim)$', msg):
            portf = '0'
            db.info_upd(user_id, 'portf', portf)
            text = 'Pronto! O capital foi zerado.\n\rAté mais!'
            return text
        else:
            text = 'Formato inválido. Tente colocar o valor neste formato ' \
                '(somente números): "1234,56" ou clique em /fechar:'
            return text, False

    def func_get_tickers_user(self, user_id, show_only=True):
        t_list = db.get_everything(user_id)
        if t_list:
            if show_only:
                text = ''
                for m in self.modes:
                    tickers = [x[0] for x in t_list if x[1] == m]
                    if tickers:
                        text += '-- ' + self.sm_dw[m] + ' --\n' + '\n'.join(
                            tickers) + '\n\n'
            else:
                text = [x[0] for x in t_list]
        else:
            text = 'A sua carteira está vazia!'
        return text

    def func_tickers_upd_user(self, user_id, msg, choice):
        if re.match(self.reg[4], msg):
            tickers = map(lambda x: x.upper(), re.split(r'\W+', msg))
            success = db.tickers_upd_user(user_id, tickers, choice)
            action = [
                'Você adicionou o(s) ativo(s) ' + msg +
                ' com sucesso!\nAté mais!',
                'O ativo ' + msg + ' foi removido com sucesso!\nAté mais!'
            ]
            if success:
                text = action[0] if choice < 4 else action[1]
            else:
                text = 'Não existe este ativo na sua carteira!\nAté mais!'
        else:
            success = False
            text ='Tente colocar o índice neste formato: "PETR4" ' \
                '(sem as aspas) ou clique em /fechar:'
        return text, success

    def func_time_upd(self, user_id, choice):
        time = db.get_info(user_id)[0][9 + choice]
        if choice == 0:
            cb_text = 'MUDAR HORA\r\n' \
                'A hora programada atual é '+time+'. Digite a nova hora ' \
                'desejada ou selecione uma das opções:'
            text, keyboard = False, False
        else:
            d_w = db.get_info(user_id)[0][8]
            if d_w == 'D':
                cb_text = 'A escala programada no seu perfil é Diário, portanto ' \
                    'você receberá mensagens todos os dias. Para receber mensagens ' \
                    'apenas 1 vez por semana, você deve mudar a escala para ' \
                    'Semanal, em Menu > Configurações > Configurações de Modo.\r\n' \
                    'Selecione uma das opções:'
                text, keyboard = False, False
            else:
                cb_text = 'MUDAR DIA\r\n' \
                    'O dia programado atual é '+self.days[int(time)]+'.'
                text = 'Escolha abaixo o novo dia desejado:'
                keyboard = [[x] for x in self.days if not x == self.days[0]]
        return cb_text, text, keyboard

    def func_time_exit(self, user_id, choice, msg):
        if choice == 0:
            if re.match(self.reg[5], msg):
                user = db.admin_queries('user_id', str(user_id), choice=3)
                hour = self.rd.hour_fix(msg)
                kwargs = {
                    'user_id': user_id,
                    's_m': user[0][7],
                    'd_w': user[0][8],
                }
                schedule.clear(str(user_id))
                self.rd.weekly(hour, self.func_radar_auto, str(user_id),
                               **kwargs)
                db.info_upd(user_id, 'hour', msg)
                text = 'A hora programada foi atualizada com sucesso!\r\nAté mais!'
                success = True
            else:
                text = 'Tente colocar a hora neste formato: "06:18", "13:45" ' \
                    '(sem as aspas) ou clique em /fechar::'
                success = False
        else:
            if re.match('^' + '|'.join(self.days) + '$', msg):
                data = str(self.days.index(msg))
                db.info_upd(user_id, 'r_day', data)
                text = 'O dia programado foi atualizado com sucesso!\r\nAté mais!'
                success = True
            else:
                text = 'Você deve selecionar o dia da lista. Tente novamente:'
                success = False
        return text, success

    def func_mode_upd(self, user_id, choice):
        change = choice.split(',')
        choice = choice.replace(',', '')
        user = db.admin_queries('user_id', str(user_id), choice=3)
        hour = self.rd.hour_fix(user[0][9])
        kwargs = {
            'user_id': user_id,
            's_m': change[0],
            'd_w': change[1],
        }
        schedule.clear(str(user_id))
        self.rd.weekly(hour, self.func_radar_auto, str(user_id), **kwargs)
        db.info_upd(user_id, 'S_M', change[0])
        db.info_upd(user_id, 'D_W', change[1])
        text = 'O modo foi atualizado com sucesso! As mensagens automáticas de radar ' \
            'possuirão classe de ações e escala ' \
            'equivalentes a '+self.sm_dw[choice]+'.\r\nAté mais!'
        return text

    def func_risk_upd(self, user_id, choice):
        db.info_upd(user_id, 'B_P', choice)
        if choice == 'B':
            text = 'Agora, digite o número de bloquinhos que serão utilizados (ex.: "8", sem as aspas):'
        else:
            text = 'Agora, digite o porcentual de risco (ex.: "1,5", sem as aspas):'
        return text

    def func_risk_exit(self, user_id, choice, msg):
        if choice == 'B' and not re.match(self.reg[2], msg):
            text = 'Formato inválido. Digite o valor dos bloquinhos neste formato ' \
                '(somente números, sem aspas): "8" ou "12". Tente novamente ou clique em /fechar:'
            success = False
        elif choice == 'P' and not re.match(self.reg[3], msg):
            text = 'Formato inválido. Digite o valor do porcentual neste formato ' \
                '(somente números, sem aspas): "1,5" ou "2". Tente novamente ou clique em /fechar:'
            success = False
        else:
            db.info_upd(user_id, 'B_P_set', msg)
            text = 'Pronto! Seu gerenciamento de risco já está configurado.\r\nAté mais!'
            success = True
        return text, success

    def func_radar(self, choice, user_id, mode, auto=False):
        if choice == 'buy':
            info = db.get_info(user_id)
            hour = info[0][9].replace(':', '-')
            portf = info[0][6]
            if portf.rfind(','): portf = portf.replace(',', '.')
            portf = float(portf)
            b_p = info[0][11]
            b_p_set = info[0][12]
            if b_p_set.rfind(','): b_p_set = b_p_set.replace(',', '.')
            b_p_set = float(b_p_set)
            order = 0 if info[0][13] == None else int(info[0][13])
            m = self.modes[int(mode)]
            stocks = self.rd.trigger_buy(m, portf, b_p, b_p_set, auto, hour)
            if stocks == []:
                text = 'No momento, nenhum ativo está perto de romper o canal superior.\r\nRelaxe!'
            else:
                if order: stocks.sort(key=lambda x: x[order])
                text = '  | ------ Compra - '+self.sm_dw[m]+' ------ | \r\n' \
                    'Ação | Vol | Sup | Fech | Inf\r\nDist | Trend\r\n' \
                    '<i>!!Os ativos em atenção romperam o canal superior nos ' \
                    'últimos 3 dias! Cuidado!!\r\n\r\n</i>'
                for item in stocks:
                    item[2] = locale.format('%1.2f', item[2], 1)
                    item[3] = locale.format('%1.2f', item[3], 1)
                    item[4] = locale.format('%1.2f', item[4], 1)
                    item[5] = '{:.2f}'.format(item[5])
                    item[6] = '{:.2f}'.format(item[6])
                    text_A = f'{item[0]} | {item[1]} | ${item[2]} | ${item[3]} | ${item[4]}\r\n'
                    text_B = f'{item[5]}% | {item[6]}'
                    if item[7]:
                        text += '!!' + text_A + '<i>' + text_B + '!!!!</i>\r\n\r\n'
                    else:
                        text += text_A + text_B + '\r\n\r\n'
        elif choice == 'track':
            t_list = db.get_everything(user_id)
            if t_list:
                t_gen = self.rd.trigger_track(t_list)
                text = ' | ------ Carteira ------ | \r\n' \
                    'Ação | Fech | Inf -> Inf(novo)\r\n\r\n'
                for group, m in t_gen:
                    text += '---- ' + self.sm_dw[m] + ' ----\r\n\r\n'
                    for item in group:
                        if item[1]:
                            item[1] = locale.format('%1.2f', item[1], 1)
                            item[2] = locale.format('%1.2f', item[2], 1)
                            text_A = f'{item[0]} | ${item[1]}'
                            if len(item) == 4:
                                item[3] = locale.format('%1.2f', item[3], 1)
                                text += f'<i>!!{text_A} | ${item[3]} -> ${item[2]}!!</i>\r\n\r\n'
                            else:
                                text += f'{text_A} | ${item[2]}\r\n\r\n'
                        else:
                            text += f'{item[0]} | dados não encontrados - ' \
                                'ativo incorreto ou muito novo.'
                    text += '\r\n'
            else:
                text = 'A sua carteira está vazia! Acesse /menu > Carteira para adicionar ativos.'
        return text

    def func_radar_auto(self, user_id, s_m, d_w):
        if s_m == None or d_w == None:
            pass
        else:
            mode = s_m + d_w
            mode = self.modes.index(mode)
            buy_text = self.func_radar('buy', user_id, mode, True)
            track_text = self.func_radar('track', user_id, mode)
            self.func_send_msg(user_id, buy_text)
            self.func_send_msg(user_id, track_text)

    def func_order(self, user_id, order=False):
        orders = [[
            'Índice do ativo (Ação)', 'Volume (vol)', 'Canal superior (Sup)',
            'Último fechamento (Fech)', 'Canal inferior (Inf)',
            'Distância (Dist)', '"Trendabilidade" (Trend)'
        ], [
            '"Ação"', '"Vol"', '"Sup"', '"Fech"', '"Inf"', '"Dist"', '"Trend"'
        ]]
        if not order:
            info = db.get_info(user_id)
            if info[0][13] == None:
                text = orders[0][0]
            else:
                text = orders[0][int(info[0][13])]
        else:
            db.info_upd(user_id, 'sorting', order)
            text = orders[1][int(order)]
        return text