Пример #1
0
def set_config(root_path):
    parser = configargparse.ArgParser()
    parser.add_argument('-H',
                        '--host',
                        help='Set web server listening host',
                        default='127.0.0.1')
    parser.add_argument('-P',
                        '--port',
                        type=int,
                        help='Set web server listening port',
                        default=4000)
    parser.add_argument('-l',
                        '--location',
                        type=parse_unicode,
                        help='Location, can be an address or coordinates')
    parser.add_argument(
        '-L',
        '--locale',
        help=
        'Locale for Pokemon names: default en, check locale folder for more options',
        default='en')
    parser.add_argument('-d',
                        '--debug',
                        help='Debug Mode',
                        action='store_true')
    parser.add_argument(
        '-gf',
        '--geofence',
        help=
        'Specify a file of coordinates, limiting alerts to within this area')
    parser.add_argument('-cn',
                        '--config',
                        help='Config file. default: alarms.json',
                        default='alarms.json')
    parser.set_defaults(DEBUG=False)

    args = parser.parse_args()

    config['ROOT_PATH'] = root_path
    config['HOST'] = args.host
    config['PORT'] = args.port
    config['LOCALE'] = args.locale
    config['DEBUG'] = args.debug
    config['CONFIG_FILE'] = args.config

    if args.location:
        config['LOCATION'] = get_pos_by_name(args.location)

    if args.geofence:
        config['GEOFENCE'] = Geofence(os.path.join(root_path, args.geofence))

    return config
Пример #2
0
def set_config(root_path):
	config['ROOT_PATH'] = root_path
	configpath = get_path('config/config.ini')
	parser = configargparse.ArgParser(default_config_files=[configpath])
	parser.add_argument('-H', '--host', help='Set web server listening host', default='127.0.0.1')
	parser.add_argument('-P', '--port', type=int, help='Set web server listening port', default=4000)
	parser.add_argument('-k', '--key', help='Specify a Google Maps API Key to use.')
	parser.add_argument('-c', '--config', help='Alarms configuration file. default: alarms.json', default='alarms.json')
	parser.add_argument('-l', '--location', type=parse_unicode, help='Location, can be an address or coordinates')
	parser.add_argument('-L', '--locale', help='Locale for Pokemon names: default en, check locale folder for more options', default='en')
	parser.add_argument('-u' , '--units',  help='Specify either metric or imperial . Default: metric', choices=['metric', 'imperial'], default='metric')
	parser.add_argument('-d', '--debug', help='Debug Mode', action='store_true',  default=False)
	parser.add_argument('-gf', '--geofence', help='Specify a file of coordinates, limiting alerts to within this area')
	parser.add_argument('-tl', '--timelimit', type=int, help='Minimum number of seconds remaining on a pokemon to notify', default=0)
	parser.add_argument('-tz', '--timezone', help='Timezone used for notifications.  Ex: "America/Los_Angeles"')
	
	args = parser.parse_args()
	
	config['HOST'] = args.host
	config['PORT'] = args.port
	config['CONFIG_FILE'] = args.config
	config['LOCALE'] = args.locale
	config['DEBUG'] = args.debug
	config['UNITS'] = args.units
	config['TIME_LIMIT'] = args.timelimit
	
	if args.key:
		config['API_KEY'] = key=args.key
		config['GMAPS_CLIENT'] = googlemaps.Client(key=args.key)
	
	if args.location:
		config['LOCATION'] =  get_pos_by_name(args.location)
	
	if args.geofence:
		config['GEOFENCE'] = Geofence(os.path.join(root_path, args.geofence))

	if args.timezone:
		try:
			config['TIMEZONE'] = pytz.timezone(args.timezone)
			log.info("Timezone set to: %s" % args.timezone)
		except pytz.exceptions.UnknownTimeZoneError:
			log.error("Invalid timezone. For a list of valid timezones, see https://en.wikipedia.org/wiki/List_of_tz_database_time_zones")
			sys.exit(1)

	config['REV_LOC'] = False
	config['DM_WALK'] = False
	config['DM_BIKE'] = False
	config['DM_DRIVE'] = False
	
	return config
Пример #3
0
def set_config(root_path):
	config['ROOT_PATH'] = root_path
	configpath = get_path('config/config.ini')
	parser = configargparse.ArgParser(default_config_files=[configpath])
	parser.add_argument('-H', '--host', help='Set web server listening host', default='127.0.0.1')
	parser.add_argument('-P', '--port', type=int, help='Set web server listening port', default=4000)
	parser.add_argument('-k', '--key', help='Specify a Google Maps API Key to use.')
	parser.add_argument('-c', '--config', help='Alarms configuration file. default: alarms.json', default='alarms.json')
	parser.add_argument('-l', '--location', type=parse_unicode, help='Location, can be an address or coordinates')
	parser.add_argument('-L', '--locale', help='Locale for Pokemon names: default en, check locale folder for more options', default='en')
	parser.add_argument('-u' , '--units',  help='Specify either metric or imperial . Default: metric', choices=['metric', 'imperial'], default='metric')
	parser.add_argument('-d', '--debug', help='Debug Mode', action='store_true',  default=False)
	parser.add_argument('-gf', '--geofence', help='Specify a file of coordinates, limiting alerts to within this area')
	parser.add_argument('-D', '--distance', type=float, help='Set web server listening port', default='inf')
	parser.add_argument('-S', '--send', type=bool, help='Set web server listening port', default='true')
	parser.add_argument('-tl', '--timelimit', type=int, help='Minimum number of seconds remaining on a pokemon to notify', default=0)
	
	args = parser.parse_args()
	
	config['HOST'] = args.host
	config['PORT'] = args.port
	config['LOCALE'] = args.locale
	config['DEBUG'] = args.debug
	config['UNITS'] = args.units
	config['TIME_LIMIT'] = args.timelimit
	config['DISTANCE'] = args.distance
	config['SEND'] = args.send
	if args.key:
		config['API_KEY'] = key=args.key
		config['GMAPS_CLIENT'] = googlemaps.Client(key=args.key)
	
	if args.location:
		config['LOCATION'] =  get_pos_by_name(args.location)
	
	if args.geofence:
		config['GEOFENCE'] = Geofence(os.path.join(root_path, args.geofence))
		
	config['REV_LOC'] = False
	config['DM_WALK'] = False
	config['DM_BIKE'] = False
	config['DM_DRIVE'] = False
	
	return config
Пример #4
0
def main():
    """
    Initializes parameters for doing donuts.
    Starts instance of ConstraintsInterface and BrakeControl.
    Creates publishers for visualization.
    Starts instance of Geofence.
    Then waits for a pose estimate for the car and geofence/donut center point to be given from rviz.
    Smooth circular or donut path is created.
    Car will start to follow path after start signal is given through /initialpose topic from rviz.
    As soon as the car completes a lap, a new circular path with a shift in starting point is created.
    Pure pursuit control is used for path tracking, PID is used for velocity control.
    Geofence, circular track path and car's tracking path are visualized in rviz.
    """
    rospy.init_node('donuts_node')

    speed_limit, path_radius, geofence_radius, gear, target_laps = init()

    # vehicle name
    # initialize constraints interface
    cont_intf = ConstraintsInterface(vehicle_name, speed_limit).start()
    cont_intf.k_d = 100

    # starts instance of brake control interface.
    brake_controller = BrakeControl(vehicle_name)
    rospy.sleep(2)

    # start publishers
    car_poly_pub = rospy.Publisher("/3D_car", PolygonStamped, queue_size=1)
    pose_pub = rospy.Publisher("/robot_pose", PoseStamped, queue_size=1)
    path_plan_pub = rospy.Publisher("/path_plan", Path, queue_size=1)
    past_path_pub = rospy.Publisher("/past_path", Path, queue_size=1)
    target_pub = rospy.Publisher("/target", PointStamped, queue_size=1)
    rospy.sleep(0.2)

    # start geofence
    geofence = Geofence().start()

    # starting car position subscriber
    car_position = StateSubscriber().start()
    rospy.loginfo('Waiting for initial pose')
    rospy.wait_for_message('/initialpose', PoseWithCovarianceStamped)
    rospy.loginfo('Received initial pose')

    rospy.sleep(1)
    # define the geofence
    geofence.set_center_radius(geofence_radius)

    # create circular path
    cx, cy, cyaw = smooth_donut_path(geofence.center, path_radius)
    publish_path(path_plan_pub, cx, cy)

    # publish the geofence to rviz
    geofence.define_marker()
    geofence.publish_marker()

    # wait for the initial position of the car
    rospy.loginfo('Waiting for start signal')
    rospy.wait_for_message('/clicked_point', PointStamped)
    rospy.loginfo('Received start signal')

    while not car_position.x:
        print('waiting for initial car position')

    # initialize pure pursuit variables
    lastIndex = len(cx) - 1
    # target_ind = pure_pursuit.calc_target_index(car_position, cx, cy)
    target_ind = pure_pursuit.calc_target_index(car_position, cx, cy)

    x = []
    y = []
    yaw = []
    # donut loop
    steering = 0.0
    rate = rospy.Rate(30)
    laps = 0
    while laps < target_laps and not rospy.is_shutdown():
        cx, cy, cyaw = smooth_donut_path(geofence.center, path_radius,
                                         laps * math.pi / 3)
        lastIndex = len(cx) - 1
        target_ind = 0
        while lastIndex > target_ind and not rospy.is_shutdown():
            # compute control input via pure pursuit
            steering, target_ind = \
                pure_pursuit.pure_pursuit_control(car_position, cx, cy, target_ind)
            if geofence.is_outside_geofence(car_position):
                brake_controller.brake_car(steering)
                cont_intf.integral = 0  # reset integrator in PID
            else:
                cont_intf.send_constrained_control(steering, 0, gear, 1, 1)
            # publish stuff for rviz.
            x.append(car_position.x)
            y.append(car_position.y)
            yaw.append(car_position.yaw)
            publish_3Dcar(car_poly_pub, pose_pub, car_position.x,
                          car_position.y, car_position.yaw)
            publish_path(path_plan_pub, cx, cy)
            publish_path(past_path_pub, x, y, yaw)
            publish_target(target_pub, cx[target_ind], cy[target_ind])

            rate.sleep()
        laps = laps + 1
        rospy.loginfo('finished lap')
    if not rospy.is_shutdown():
        rospy.loginfo("Trajectory finished.")
Пример #5
0
def main():
    """
    Initializes the parameters from launch file.
    Creates publishers for visualization.
    Starts the instances of ConstraintsInterface, BrakeControl, Geofence and StateSubscriber.
    Waits for center point and radius to be given in rviz.
    Creates geofence, can be seen in rviz.
    When operated through remote: If the car senses the emergency, it stops. 
                                  Or if the car is outside the geofence, it stops.
                                  Otherwise, it runs with limited velocity.
    """
    rospy.init_node('velocity_constraint_node')

    # Gets the current speed limit from the launch file.
    speed_limit_param = rospy.search_param('speed_limit')
    speed_limit = rospy.get_param(speed_limit_param)
    speed_limit = float(speed_limit)

    # Gets the trigger sensitivity from the launch file
    trigger_param = rospy.search_param('trigger_sensitivity')
    trigger_sensitivity = rospy.get_param(trigger_param)
    trigger_sensitivity = float(trigger_sensitivity)

    car_poly_pub = rospy.Publisher("/3D_car", PolygonStamped, queue_size=1)
    pose_pub = rospy.Publisher("/robot_pose", PoseStamped, queue_size=1)

    # wait for the initial position of the car
    rospy.loginfo('Waiting for initial pose')
    rospy.wait_for_message('/initialpose', PoseWithCovarianceStamped)
    rospy.loginfo('Received initial pose')

    vehicle_name = rospy.get_param(rospy.get_name() + '/vehicle_name')

    # starts instance of control interface with speed constraints functionality
    cont_intf = ConstraintsInterface(vehicle_name, speed_limit,
                                     trigger_sensitivity).start()

    # starts instance of brake control interface.
    brake_controller = BrakeControl(vehicle_name)

    # start geofence
    geofence = Geofence().start()

    # starting car position subscriber
    car_position = StateSubscriber().start()

    rospy.sleep(1)
    # define the geofence
    geofence.set_center()
    geofence.set_radius()

    # publish the geofence to rviz
    geofence.define_marker()
    geofence.publish_marker()

    rate = rospy.Rate(30)
    # sends commands from controller but with constrained speed.
    # if there is an emergency the car brakes.
    while not rospy.is_shutdown():

        if brake_controller.is_emergency:
            brake_controller.brake_car()
            print('brake')
            cont_intf.integral = 0  # reset integrator in PID
        if geofence.is_outside_geofence(car_position):
            brake_controller.brake_car_extreme()
            cont_intf.integral = 0  # reset integrator in PID
        else:
            error = cont_intf.control_error()
            velocity = cont_intf.pid_controller(error)
            cont_intf.send_control(
                cont_intf.remote_steering,
                velocity,
                0,  # zero brake force
                cont_intf.remote_transmission)
        publish_3Dcar(car_poly_pub, pose_pub, car_position.x, car_position.y,
                      car_position.yaw)
        rate.sleep()
Пример #6
0
 def __init__(self):
     self.geofence = Geofence()
     self.capture = Capture()
     self.capturesinprogress = {}
     self.vesseldetails = self.load_vessel_details()
     print "Loaded", len(self.vesseldetails.keys()), "Vessels"
Пример #7
0
class Ais_Processor:
    def __init__(self):
        self.geofence = Geofence()
        self.capture = Capture()
        self.capturesinprogress = {}
        self.vesseldetails = self.load_vessel_details()
        print "Loaded", len(self.vesseldetails.keys()), "Vessels"

    def ingeofence(self, ais):
        if 'x' not in ais or 'y' not in ais: return False
        return self.geofence.point_in_fence(ais['y'], ais['x'])

    def load_vessel_details(self):
        with open(vesseldetails_persist_file, "r") as json_data:
            try:
                return json.load(json_data)
            except ValueError:
                return {}

    def persist_vessel_details(self):
        with open(vesseldetails_persist_file, "w") as vesseldetails_file:
            json.dump(self.vesseldetails, vesseldetails_file)

    def get_vessel_details(self, mmsi):
        mmsi = str(mmsi)
        if mmsi not in self.vesseldetails:
            return {
                "name": "",
                "details": "",
                "size": "",
                "notes": "",
                "identified": False,
                "ignored": True
            }
        return self.vesseldetails[mmsi]

    def process_ais5(self, ais):
        # http://catb.org/gpsd/AIVDM.html#_type_5_static_and_voyage_related_ais
        if ais['id'] != 5:
            raise ValueError('Not an AIS5 message', ais)

        dim_b = ais['dim_a']
        dim_s = ais['dim_b']
        dim_p = ais['dim_c']
        dim_sb = ais['dim_d']
        # If too small to photograph we'll ignore it
        ignored = True
        if dim_b + dim_s > 80:  # Vessel is > 80m long, excluding ferries, tugs and smaller craft
            ignored = False

        if str(ais['mmsi']) in self.vesseldetails:
            return

        vesseldetails = {
            'name':
            clean(ais['name']),
            'flag':
            '',
            'gross_tonnage':
            '',
            'url':
            '',
            'details':
            classifications[str(ais['type_and_cargo'])],
            'size':
            str(dim_b + dim_s) + 'm x ' + str(dim_p + dim_sb) + 'm',
            'notes':
            'Destination ' + (clean(ais['destination']) or 'Unknown') +
            ', ETA:' + str(ais['eta_day']) + '/' + str(ais['eta_month']),
            'callsign':
            clean(ais['callsign']),
        }
        vesseldetails['mmsi'] = ais['mmsi']
        vesseldetails['ignored'] = ignored
        vesseldetails['identified'] = True
        self.vesseldetails[str(ais['mmsi'])] = vesseldetails

        print "Update vessel", ais['mmsi'], vesseldetails['name']
        self.persist_vessel_details()

    def process(self, ais):
        mmsi = ais['mmsi']

        vesseldetails = self.get_vessel_details(mmsi)

        identified = vesseldetails['identified']
        ignored = vesseldetails['ignored']

        if mmsi in self.capturesinprogress:  # If already capturing this vessel
            if not self.ingeofence(ais):  # If vessel has left the geofence
                #self.capture.stop(self.capturesinprogress[mmsi])
                images = self.capture.get_images(self.capturesinprogress[mmsi])
                del self.capturesinprogress[mmsi]
                del currently_inside_fence[mmsi]
        elif self.ingeofence(ais):
            now = datetime.datetime.utcnow()
            if mmsi not in geofence_last_seen:
                geofence_last_seen[mmsi] = now
                return

            geofence_last_seen[mmsi] = now

            if mmsi not in currently_inside_fence:
                print time.strftime('%H:%M'), ":", str(
                    mmsi
                ), " : Ignored :" if ignored else "", vesseldetails['name']

                currently_inside_fence[mmsi] = {
                    'date': u'' + now.isoformat(),
                    'mmsi': mmsi,
                    'details': vesseldetails
                }  # Log once only when a ship enters the geofence
            if not ignored:
                print "Attempt capture", mmsi, vesseldetails['name']

                n = datetime.datetime.now()
                captureid = str(mmsi) + str(int(time.time()))
                self.capture.start(captureid, mmsi, vesseldetails)
                self.capturesinprogress[mmsi] = captureid
        else:
            if mmsi in currently_inside_fence:  # When a ship leaves the fenced region mark it as outside
                del currently_inside_fence[mmsi]
Пример #8
0
parser = basic_std_parser("pokestops")
parser.add_argument('-k',
                    '--gmaps-key',
                    help='Google Maps Javascript API Key.',
                    required=False)
add_geofence(parser)
args = parser.parse_args()
args.system_id = "levelup-routes"

loop = asyncio.get_event_loop()
setup_default_app(args, loop)
log = logging.getLogger(__name__)

fence = Geofence("hamburg", [(53.7351445815432, 9.5635986328125),
                             (53.363088956906395, 9.57183837890625),
                             (53.31389056047761, 10.513916015625),
                             (53.793591468075, 10.4754638671875),
                             (53.824405643545084, 9.55810546875)])
box = fence.box()
sps = fence.filter_forts(spawnpoints_in_box(box))
pokestops = fence.filter_forts(pokestops_in_box(box))
gyms = fence.filter_forts(gyms_in_box(box))


def dump_elem(text_file, x, idfield, type):
    text_file.write("{},{},{},{},{}\n".format(str(x[idfield]), type,
                                              str(x["latitude"]),
                                              str(x["longitude"]),
                                              str(x["altitude"])))