Пример #1
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))
 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()
Пример #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)
Пример #4
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()
Пример #5
0
def main():
    start_game()
    radar = Radar((HIT_X, HIT_Y))
    player = PlayerCharacter(radar)

    reactor.callWhenRunning(player.start)
    reactor.callWhenRunning(radar.start)
    reactor.run()
Пример #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
Пример #7
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)
Пример #8
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)
Пример #9
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))
Пример #10
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))
Пример #11
0
    def main(self):
        self.radar = Radar()
        self.radar.draw_radar()

        self.radar.display.getMouse()
        self.radar.display.close()
Пример #12
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 "
Пример #13
0
 def __init__(self):
     self._camera = Camera()
     self._radars = [Radar('test', 18, 24)]
     self._agent = Agent()
Пример #14
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")
Пример #15
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),
    ]
Пример #16
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
Пример #17
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!")
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
    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()
Пример #20
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))