def __init__(self):
        self.pub_player1 = rospy.Publisher('airhockey/simulator/player1', Twist, queue_size=60)
        self.pub_player2 = rospy.Publisher('airhockey/simulator/player2', Twist, queue_size=60)
        self.vel_player1 = 0, 0
        self.vel_player2 = 0, 0
        self.pub_image = rospy.Publisher('/airhockey/simulator/image', ImageMsg, queue_size=60)
        self.bridge = CvBridge()

        self.space = pymunk.Space()
        self.space.gravity = (0.0, 0.0)

        self.root = tk.Tk()
        self.root.title('Airhockey')
        self.root.resizable(width=False, height=False)
        self.root.geometry("{}x{}+{}+{}".format(1595, 1000, 0, 0))
        self.root.bind("<Escape>", lambda e: self.root.quit())
        #self.root.bind('<Motion>', self.mouse_position)

        self.field_image = Image.open(os.path.join(self.dir, '../res', 'field.png'))

        self.static_body = pymunk.Body(body_type=pymunk.Body.STATIC)
        self.static_line = pymunk.Segment(self.static_body, (0, 40), (1595, 40), 0.0)
        self.static_line.elasticity = 1
        self.space.add(self.static_body, self.static_line)

        self.static_body = pymunk.Body(body_type=pymunk.Body.STATIC)
        self.static_line = pymunk.Segment(self.static_body, (0, 960), (1595, 960), 0.0)
        self.static_line.elasticity = 1
        self.space.add(self.static_body, self.static_line)

        self.static_body = pymunk.Body(body_type=pymunk.Body.STATIC)
        self.static_line = pymunk.Segment(self.static_body, (40, 0), (40, 1000), 0.0)
        self.static_line.elasticity = 1
        self.space.add(self.static_body, self.static_line)

        self.static_body = pymunk.Body(body_type=pymunk.Body.STATIC)
        self.static_line = pymunk.Segment(self.static_body, (1550, 0), (1550, 1000), 0.0)
        self.static_line.elasticity = 1
        self.space.add(self.static_body, self.static_line)

        self.player1_object = Pod(200, 500, 100, 3, 'player1', 'airhockey/simulator/player1')
        self.player2_object = Pod(1390, 500, 100, 3, 'player2', 'airhockey/simulator/player2')
        self.puck = Puck(795, 500, 60, 1)

        self.space.add(self.player1_object.body, self.player1_object.shape)
        self.space.add(self.player2_object.body, self.player2_object.shape)
        self.space.add(self.puck.body, self.puck.shape)

        self.field = ImageTk.PhotoImage(self.get_field_image(self.player1_object, self.player2_object, self.puck))

        self.canvas = tk.Canvas(self.root, width=1590, height=1000)
        self.canvas.pack()

        self.root.bind_all('<KeyPress>', self.key_pressed)
        self.root.bind_all('<KeyRelease>', self.key_released)

        self.root.after(int(round(1000 / self.FPS, 0)), func=self.tick)
Ejemplo n.º 2
0
    def update_pods(self):
        """
        Update all Pods in cluster, if Pod exists add usage statistics
        to self.monitor_pods_data
        :return:
        """
        self.status_lock.acquire(blocking=True)

        # set all current pods as inactive
        for pod in self.all_pods.items:
            pod.is_alive = False
        for pod_ in self.v1.list_pod_for_all_namespaces().items:

            skip = False

            if pod_.status.phase == 'Running':
                for pod in self.all_pods.items:
                    if pod_.metadata.name == pod.metadata.name:
                        # found in collection, so update its usage
                        skip = True  # skip creating new Pod

                        res = pod.fetch_usage()
                        pod.is_alive = True
                        # TODO what to do when metrics reciving failed
                        if res != 0:
                            if res == 404:
                                print('Metrics for pod %s not found ' %
                                      pod.metadata.name)
                            else:
                                print('Unknown metrics server error %s' % res)
                            break

                        #                        print('Updated metrics for pod %s' % pod.metadata.name)

                        break

                if not skip:
                    # this is new pod, add it to
                    pod = Pod(pod_.metadata, pod_.spec, pod_.status)
                    pod.is_alive = True
                    print('Added pod ' + pod.metadata.name)
                    self.all_pods.items.append(pod)

        print('Number of Pods ', len(self.all_pods.items))
        self.status_lock.release()
        self.garbage_old_pods()
Ejemplo n.º 3
0
    def load_create_config(self, config_file_name):
        """Read and parse configuration file for the test environment.
        """
        self._log.info("Loading configuration file %s", config_file_name)
        self._create_config = ConfigParser.RawConfigParser()
        try:
            self._create_config.read(config_file_name)
        except Exception as e:
            self._log.error("Failed to read config file!\n%s\n" % e)
            return -1

        # Now parse config file content
        # Parse [DEFAULT] section
        if self._create_config.has_option("DEFAULT", "total_number_of_pods"):
            self._total_number_of_pods = self._create_config.getint(
                "DEFAULT", "total_number_of_pods")
        else:
            self._log.error(
                "No option total_number_of_pods in DEFAULT section")
            return -1

        self._log.debug("Total number of pods %d" % self._total_number_of_pods)

        # Parse [PODx] sections
        for i in range(1, int(self._total_number_of_pods) + 1):
            # Search for POD name
            if self._create_config.has_option("POD%d" % i, "name"):
                pod_name = self._create_config.get("POD%d" % i, "name")
            else:
                pod_name = "pod-rapid-%d" % i

            # Search for POD hostname
            if self._create_config.has_option("POD%d" % i,
                                              "nodeSelector_hostname"):
                pod_nodeselector_hostname = self._create_config.get(
                    "POD%d" % i, "nodeSelector_hostname")
            else:
                pod_nodeselector_hostname = None

            # Search for POD dataplane static IP
            if self._create_config.has_option("POD%d" % i, "dp_ip"):
                pod_dp_ip = self._create_config.get("POD%d" % i, "dp_ip")
            else:
                pod_dp_ip = None

            pod = Pod(pod_name)
            pod.set_nodeselector(pod_nodeselector_hostname)
            pod.set_dp_ip(pod_dp_ip)
            pod.set_id(i)

            # Add POD to the list of PODs which need to be created
            self._pods.append(pod)

        return 0
Ejemplo n.º 4
0
    def createPodFleet(self):
        """
        Create a number of new pods and assign a new route.
        This is currently randomly assigned
        """
        for podIndex in range(0, self.maxNumberOfPods):
            # Create new Pod
            self.podArray.append(Pod(podIndex, self.pathNetwork))

            # Select a random speed for each pod
            if (config.randomPodSpeed):
                self.podArray[len(self.podArray) -
                              1].speed = (random.randrange(7, 10) * 0.1)
Ejemplo n.º 5
0
    def assignFleet(self):
        for podIndex in range(0, self.maxNumberOfPods):
            # Create new Pod

            self.podArray.append(
                Pod(podIndex,
                    self.pathNetwork,
                    allocatedStartBox=self.chromosome.genes[podIndex]))

            # Select a random speed for each pod
            if (config.randomPodSpeed):
                self.podArray[len(self.podArray) -
                              1].speed = (random.randrange(7, 10) * 0.1)
Ejemplo n.º 6
0
    def run(self):
        """
        Main thread, run and listen for events,
        If an event occurred, call monitor.update_nodes()
        and proceed scoring and scheduling process.
        """
        print('Scheduler running')

        p1 = Thread(target=self.monitor.monitor_runner)
        p1.start()

        while True:
            try:
                for event in self.watcher.stream(
                        self.v1.list_pod_for_all_namespaces):
                    print('Event type ', event['type'])
                    if event['type'] == 'ADDED' and event[
                            'object'].spec.scheduler_name == self.scheduler_name:
                        new_pod = Pod(event['object'].metadata,
                                      event['object'].spec,
                                      event['object'].status)
                        print('New pod ADDED', new_pod.metadata.name)

                        self.monitor.update_nodes()
                        self.monitor.print_nodes_stats()

                        new_node = self.choose_node(new_pod)

                        if new_node is not None:
                            self.bind_to_node(new_pod.metadata.name,
                                              new_node.metadata.name)
                        else:
                            print('Pod cannot be scheduled..')
                            # when Pod cannot be scheduled it is being deleted and after
                            # couple seconds new Pod is created and another attempt
                            # of scheduling this Pod is being made

            except Exception as e:
                print(str(e))
            sleep(5)

        p1.join()
Ejemplo n.º 7
0
Archivo: jun.py Proyecto: Alan-mag/Jun
def send():
    sent = True;
    pods = []
    result_xml = None
    if request.method == 'POST':
        i = request.form['i']
        payload = i + "&appid=VJ8YWP-VV56V4PPV2"
        result_xml = requests.get('http://api.wolframalpha.com/v2/query?input=' + payload)
        xmlstr = result_xml.text

        root = ET.fromstring(xmlstr)

        # returns true is there is valid data found
        data_return = root.attrib.get('success')
        print (data_return)

        for pod in root:
            title = pod.get('title')
            #print title
            subpods = []
            for subpodITR in pod:
                sb = Subpod(None, None, None)
                if subpodITR.get('title') is not None:
                    sb.title = subpodITR.get('title')
                if subpodITR.find('img') is not None:
                    img = subpodITR.find('img')
                    sb.img = img.get('src')
                if subpodITR.find('plaintext') is not None:
                    sb.text = subpodITR.find('plaintext').text
                subpods.append(sb)

            g = Pod(title, subpods)
            pods.append(g)
            #print g
        for pod in pods:
            print (pod.title)
            for element in pod.podsubpod:
                print (element)
            print ("-------------------------")
    return render_template('/index.html', result_xml=result_xml,
                           data_return=data_return, title="Jun", pods=pods, sent=sent)
Ejemplo n.º 8
0
 def get_pods(self):
     """
     :return: All the pods of the job
     """
     self.job_spec = self.get_spec()
     return {Pod(self, iid) for iid in xrange(self.job_spec.instance_count)}
Ejemplo n.º 9
0
 def get_pod(self, instance_id):
     """
     :param instance_id: The instance id of the pod
     :return: The Pod of the job based on the instance id
     """
     return Pod(self, instance_id)
class AirhockeyScreen:
    dir = os.path.dirname(__file__)
    FPS = 60.0

    player1_keys = ['d', 'q', 'z', 's']
    player2_keys = ['Right', 'Left', 'Up', 'Down']

    score = {'player_1': 0, 'player_2': 0}

    def __init__(self):
        self.pub_player1 = rospy.Publisher('airhockey/simulator/player1', Twist, queue_size=60)
        self.pub_player2 = rospy.Publisher('airhockey/simulator/player2', Twist, queue_size=60)
        self.vel_player1 = 0, 0
        self.vel_player2 = 0, 0
        self.pub_image = rospy.Publisher('/airhockey/simulator/image', ImageMsg, queue_size=60)
        self.bridge = CvBridge()

        self.space = pymunk.Space()
        self.space.gravity = (0.0, 0.0)

        self.root = tk.Tk()
        self.root.title('Airhockey')
        self.root.resizable(width=False, height=False)
        self.root.geometry("{}x{}+{}+{}".format(1595, 1000, 0, 0))
        self.root.bind("<Escape>", lambda e: self.root.quit())
        #self.root.bind('<Motion>', self.mouse_position)

        self.field_image = Image.open(os.path.join(self.dir, '../res', 'field.png'))

        self.static_body = pymunk.Body(body_type=pymunk.Body.STATIC)
        self.static_line = pymunk.Segment(self.static_body, (0, 40), (1595, 40), 0.0)
        self.static_line.elasticity = 1
        self.space.add(self.static_body, self.static_line)

        self.static_body = pymunk.Body(body_type=pymunk.Body.STATIC)
        self.static_line = pymunk.Segment(self.static_body, (0, 960), (1595, 960), 0.0)
        self.static_line.elasticity = 1
        self.space.add(self.static_body, self.static_line)

        self.static_body = pymunk.Body(body_type=pymunk.Body.STATIC)
        self.static_line = pymunk.Segment(self.static_body, (40, 0), (40, 1000), 0.0)
        self.static_line.elasticity = 1
        self.space.add(self.static_body, self.static_line)

        self.static_body = pymunk.Body(body_type=pymunk.Body.STATIC)
        self.static_line = pymunk.Segment(self.static_body, (1550, 0), (1550, 1000), 0.0)
        self.static_line.elasticity = 1
        self.space.add(self.static_body, self.static_line)

        self.player1_object = Pod(200, 500, 100, 3, 'player1', 'airhockey/simulator/player1')
        self.player2_object = Pod(1390, 500, 100, 3, 'player2', 'airhockey/simulator/player2')
        self.puck = Puck(795, 500, 60, 1)

        self.space.add(self.player1_object.body, self.player1_object.shape)
        self.space.add(self.player2_object.body, self.player2_object.shape)
        self.space.add(self.puck.body, self.puck.shape)

        self.field = ImageTk.PhotoImage(self.get_field_image(self.player1_object, self.player2_object, self.puck))

        self.canvas = tk.Canvas(self.root, width=1590, height=1000)
        self.canvas.pack()

        self.root.bind_all('<KeyPress>', self.key_pressed)
        self.root.bind_all('<KeyRelease>', self.key_released)

        self.root.after(int(round(1000 / self.FPS, 0)), func=self.tick)

    def tick(self):
        self.player1_object.move()
        self.player2_object.move()
        self.space.step(1 / self.FPS)
        self.render()
        self.puck.check_goal(self.score)
        self.root.after(int(round(1000 / self.FPS, 0)), func=self.tick)

    def render(self):
        self.canvas.delete('all')
        image = self.get_field_image(self.player1_object, self.player2_object, self.puck)
        field = ImageTk.PhotoImage(image)
        self.canvas.create_image((795, 500), image=field)
        self.canvas.image = field
        self.canvas.create_text(799, 75, fill='darkblue', font='Times 80 bold',
                                text='{}:{}'.format(self.score['player_1'], self.score['player_2']))
        """
        Subscribe to this topic to analyze the board in ROS with OpenCV
        To move the player publish a message of geometry_msgs.msg.Twist to /airhockey/player1 or /airhockey/player2.
        """
        self.pub_image.publish(self.bridge.cv2_to_imgmsg(cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR), 'bgr8'))

    def get_field_image(self, *args):
        img_to_show = Image.new('RGB', (1590, 1000), color=(255, 255, 255, 1))
        img_to_show.paste(self.field_image, (0, 0), self.field_image)
        for game_object in args:
            img_to_show.paste(game_object.image, (game_object.get_position()), game_object.image)
        return img_to_show

    def mouse_position(self, event):
        pos_x, pos_y = event.x, event.y
        self.player1_object.set_position(pos_x, pos_y)

    def key_pressed(self, event):
        motion_command = Twist()
        if event.keysym in self.player1_keys:
            velocity = self.get_velocity(event, self.vel_player1)
            self.vel_player1 = velocity
            motion_command.linear.x = velocity[0]
            motion_command.linear.y = velocity[1]
            self.pub_player1.publish(motion_command)
        elif event.keysym in self.player2_keys:
            velocity = self.get_velocity(event, self.vel_player2)
            self.vel_player2 = velocity
            motion_command.linear.x = velocity[0]
            motion_command.linear.y = velocity[1]
            self.pub_player2.publish(motion_command)

    def key_released(self, event):
        motion_command = Twist()
        if event.keysym in self.player1_keys:
            velocity = self.reset_velocity(event, self.vel_player1)
            self.vel_player1 = velocity
            motion_command.linear.x = velocity[0]
            motion_command.linear.y = velocity[1]
            self.pub_player1.publish(motion_command)
        elif event.keysym in self.player2_keys:
            velocity = self.reset_velocity(event, self.vel_player2)
            self.vel_player2 = velocity
            motion_command.linear.x = velocity[0]
            motion_command.linear.y = velocity[1]
            self.pub_player2.publish(motion_command)

    def get_velocity(self, event, velocity):
        _vel_x, _vel_y = velocity
        if 'Right' == event.keysym or event.keysym  == 'd':
            _vel_x = 15
        elif 'Left' == event.keysym or event.keysym == 'q':
            _vel_x = -15
        elif 'Up' == event.keysym or event.keysym == 'z':
            _vel_y = -15
        elif 'Down' == event.keysym or event.keysym == 's':
            _vel_y = 15
        return _vel_x, _vel_y

    def reset_velocity(self, event, velocity):
        _vel_x, _vel_y = velocity
        if 'Right' == event.keysym or event.keysym == 'd' or 'Left' == event.keysym or event.keysym == 'q':
            _vel_x = 0
        elif 'Up' == event.keysym or event.keysym == 'z' or 'Down' == event.keysym or event.keysym == 's':
            _vel_y = 0
        return _vel_x, _vel_y
 def CreatePod(self, deployment):
     podName = deployment.deploymentLabel + "_" + str(
         self.GeneratePodName())
     pod = Pod(podName, deployment.cpuCost, deployment.deploymentLabel)
     #print("Pod " + pod.podName + " created")
     self.etcd.pendingPodList.append(pod)
Ejemplo n.º 12
0
    def __init__(self, config, working_dir=None):
        self.logger = logging.getLogger("Sim")

        self.logger.info("Initializing simulation")

        # Config
        self.config = config

        # Working directory (for csv files and whatnot)
        if working_dir is not None:
            self.set_working_dir(working_dir)

        self.logger.info("Working directory is {} ({})".format(
            self.config.working_dir,
            os.path.join(os.getcwd(), self.config.working_dir)))

        self.ensure_working_dir()

        # Simulator control
        self.step_listeners = []  # For in-sim control (per step)
        self.end_conditions = []
        self.end_listeners = []

        # Pre and post
        self.preprocessors = []
        self.postprocessors = []

        # Time
        self.fixed_timestep_usec = Units.usec(
            config.fixed_timestep)  # Convert to usec
        self.time_dialator = TimeDialator(self)  # We're going to step this

        # Components
        self.pusher = Pusher(self, self.config.pusher)
        self.track = Track(self, self.config.track)
        self.pod = Pod(self, self.config.pod)
        #self.fcu = Fcu(self, self.config.fcu)

        # Component setup

        # Set the initial pusher position to meet the pusher plate
        # @todo: should we set this somewhere else? Like in a run controller?
        self.pusher.position = self.pod.pusher_plate_offset

        # Sensors
        self.sensors = {}
        self.sensors['pod'] = PodSensor(self, self.config.sensors.pod)
        self.sensors['pod'].add_step_listener(
            SensorCsvWriter(self, self.config.sensors.pod))

        self.sensors['pusher'] = PusherSensor(self, self.config.sensors.pusher)
        self.sensors['pusher'].add_step_listener(
            SensorCsvWriter(self, self.config.sensors.pusher))

        # - Accelerometers
        self.sensors['accel'] = []

        for idx, sensor_config in self.config.sensors.accel.iteritems():
            # Note: we need to create a Config object here because Config does not currently handle lists very well...
            self.sensors['accel'].append(
                Accelerometer(self, Config(sensor_config)))
            sensor = self.sensors['accel'][idx]
            sensor.add_step_listener(
                AccelerometerTestListener(self, sensor.config))
            sensor.add_step_listener(SensorCsvWriter(self, sensor.config))
            #sensor.add_step_listener(SensorRawCsvWriter(self, sensor.config))

        # - Laser Contrast Sensors
        """
        self.sensors['laser_contrast'] = []
        for idx, sensor_config in self.config.sensors.laser_contrast.iteritems():
            self.sensors['laser_contrast'].append(LaserContrastSensor(self, Config(sensor_config)))
            sensor = self.sensors['laser_contrast'][idx]
            #sensor.add_step_listener(LaserContrastTestListener(self, sensor.config))  # For debugging
            sensor.add_step_listener(SensorCsvWriter(self, sensor.config))
            #sensor.add_step_listener(SensorRawCsvWriter(self, sensor.config))  # These don't have 'raw' values since they just call an interrupt

        # - Laser Opto Sensors (height and yaw)
        self.sensors['laser_opto'] = []
        for idx, sensor_config in self.config.sensors.laser_opto.iteritems():
            self.sensors['laser_opto'].append(LaserOptoSensor(self, Config(sensor_config)))
            sensor = self.sensors['laser_opto'][idx]
            #sensor.add_step_listener(LaserOptoTestListener(self, sensor.config))  # For debugging
            sensor.add_step_listener(SensorCsvWriter(self, sensor.config))
            #sensor.add_step_listener(SensorRawCsvWriter(self, sensor.config))   
        
        # - Laser Distance Sensor
        self.sensors['laser_dist'] = LaserDistSensor(self, Config(self.config.sensors.laser_dist))
        sensor = self.sensors['laser_dist']
        sensor.add_step_listener(SensorCsvWriter(self, sensor.config))
        #sensor.add_step_listener(SensorRawCsvWriter(self, sensor.config))
        """

        # - Brake Sensors: MLP, limit switches (for both)
        pass

        # Networking
        self.comms = PodComms(self, self.config.networking)
        self.add_end_listener(self.comms)

        # FCU (!)
        if self.config.fcu.enabled:
            self.fcu = Fcu(self, self.config.fcu)
            self.add_end_listener(self.fcu)
        else:
            # @todo: will this have any side effects (e.g. not having an fcu?)
            self.logger.info(
                "Not initializing FCU because it is disabled via config.")

        # Initial setup
        # @todo: write a method by which we can maybe control the push from the ground station or rpod_control vb.net app
        # @todo: write a means by which we can start the push some configurable amount of time after the pod enters READY state
        #self.pusher.start_push()  # Only for testing

        # Volatile
        self.elapsed_time_usec = 0
        self.n_steps_taken = 0
Ejemplo n.º 13
0
class Sim(object):
    def __init__(self, config, working_dir=None):
        self.logger = logging.getLogger("Sim")

        self.logger.info("Initializing simulation")

        # Config
        self.config = config

        # Working directory (for csv files and whatnot)
        if working_dir is not None:
            self.set_working_dir(working_dir)

        self.logger.info("Working directory is {} ({})".format(
            self.config.working_dir,
            os.path.join(os.getcwd(), self.config.working_dir)))

        self.ensure_working_dir()

        # Simulator control
        self.step_listeners = []  # For in-sim control (per step)
        self.end_conditions = []
        self.end_listeners = []

        # Pre and post
        self.preprocessors = []
        self.postprocessors = []

        # Time
        self.fixed_timestep_usec = Units.usec(
            config.fixed_timestep)  # Convert to usec
        self.time_dialator = TimeDialator(self)  # We're going to step this

        # Components
        self.pusher = Pusher(self, self.config.pusher)
        self.track = Track(self, self.config.track)
        self.pod = Pod(self, self.config.pod)
        #self.fcu = Fcu(self, self.config.fcu)

        # Component setup

        # Set the initial pusher position to meet the pusher plate
        # @todo: should we set this somewhere else? Like in a run controller?
        self.pusher.position = self.pod.pusher_plate_offset

        # Sensors
        self.sensors = {}
        self.sensors['pod'] = PodSensor(self, self.config.sensors.pod)
        self.sensors['pod'].add_step_listener(
            SensorCsvWriter(self, self.config.sensors.pod))

        self.sensors['pusher'] = PusherSensor(self, self.config.sensors.pusher)
        self.sensors['pusher'].add_step_listener(
            SensorCsvWriter(self, self.config.sensors.pusher))

        # - Accelerometers
        self.sensors['accel'] = []

        for idx, sensor_config in self.config.sensors.accel.iteritems():
            # Note: we need to create a Config object here because Config does not currently handle lists very well...
            self.sensors['accel'].append(
                Accelerometer(self, Config(sensor_config)))
            sensor = self.sensors['accel'][idx]
            sensor.add_step_listener(
                AccelerometerTestListener(self, sensor.config))
            sensor.add_step_listener(SensorCsvWriter(self, sensor.config))
            #sensor.add_step_listener(SensorRawCsvWriter(self, sensor.config))

        # - Laser Contrast Sensors
        """
        self.sensors['laser_contrast'] = []
        for idx, sensor_config in self.config.sensors.laser_contrast.iteritems():
            self.sensors['laser_contrast'].append(LaserContrastSensor(self, Config(sensor_config)))
            sensor = self.sensors['laser_contrast'][idx]
            #sensor.add_step_listener(LaserContrastTestListener(self, sensor.config))  # For debugging
            sensor.add_step_listener(SensorCsvWriter(self, sensor.config))
            #sensor.add_step_listener(SensorRawCsvWriter(self, sensor.config))  # These don't have 'raw' values since they just call an interrupt

        # - Laser Opto Sensors (height and yaw)
        self.sensors['laser_opto'] = []
        for idx, sensor_config in self.config.sensors.laser_opto.iteritems():
            self.sensors['laser_opto'].append(LaserOptoSensor(self, Config(sensor_config)))
            sensor = self.sensors['laser_opto'][idx]
            #sensor.add_step_listener(LaserOptoTestListener(self, sensor.config))  # For debugging
            sensor.add_step_listener(SensorCsvWriter(self, sensor.config))
            #sensor.add_step_listener(SensorRawCsvWriter(self, sensor.config))   
        
        # - Laser Distance Sensor
        self.sensors['laser_dist'] = LaserDistSensor(self, Config(self.config.sensors.laser_dist))
        sensor = self.sensors['laser_dist']
        sensor.add_step_listener(SensorCsvWriter(self, sensor.config))
        #sensor.add_step_listener(SensorRawCsvWriter(self, sensor.config))
        """

        # - Brake Sensors: MLP, limit switches (for both)
        pass

        # Networking
        self.comms = PodComms(self, self.config.networking)
        self.add_end_listener(self.comms)

        # FCU (!)
        if self.config.fcu.enabled:
            self.fcu = Fcu(self, self.config.fcu)
            self.add_end_listener(self.fcu)
        else:
            # @todo: will this have any side effects (e.g. not having an fcu?)
            self.logger.info(
                "Not initializing FCU because it is disabled via config.")

        # Initial setup
        # @todo: write a method by which we can maybe control the push from the ground station or rpod_control vb.net app
        # @todo: write a means by which we can start the push some configurable amount of time after the pod enters READY state
        #self.pusher.start_push()  # Only for testing

        # Volatile
        self.elapsed_time_usec = 0
        self.n_steps_taken = 0

        # Testing laser opto sensor class
        # self.laser_opto_sensors = LaserOptoSensors(self, self.config.sensors.laser_opto)

        #self.pod_sensor_writer.pause()  # Paused for use in the gui

        # Testing brakes  (pod now has brakes)
        #from brakes import Brake
        #self.brake_1 = Brake(self, None)
        #self.brake_1.gap = 0.025 # Set it to test forces

        # End condition checker (to stop the simulation)
        #self.add_end_condition(SimEndCondition())  # Currently disabled in favor of using the RunController

        # Handle data writing
        # @ todo: handle data writing. Note: Each sim instance should be handed a directory to use for writing data

    @classmethod
    def load_config_files(cls, config_files):
        """ Load one or more config files (later files overlay earlier ones) """

        ymls = []
        for configfile in config_files:
            with open(configfile, 'rb') as f:
                ymls.append(yaml.load(f))
        merged = {}
        for yml in ymls:
            merged = yaml_merge(merged, yml)

        config = Config(merged)
        return config.sim

        #config = Config()
        #for configfile in config_files:
        # Note: each file loaded by the config will overlay on the previously loaded files
        #    config.loadfile(configfile)
        #return config.sim

    def set_working_dir(self, working_dir):
        """ Set our working directory (for file writing and whatnot) """
        self.config.working_dir = working_dir

    def data_logging_enabled(self, data_writer, sensor):
        """ Tell data writers whether or not to log data (e.g. csv writers) """
        # @todo: write something that gets a value from runtime config
        # @todo: write something that turns data logging on and off based on FCU state (assuming the FCU is enabled)
        # @todo: potentially turn on or off based on sensor, writer type, or a combination of the two
        return True  # Turn data logging off for now

    def step(self, dt_usec):

        # Step the pusher first (will apply pressure and handle disconnection)
        self.pusher.step(dt_usec)

        # Step the pod (will handle all other forces and pod physics)
        self.pod.step(dt_usec)

        # Step the sensors
        for sensor in self.sensors.values():
            # Some of our sensors are lists of sensors
            if isinstance(sensor, list):
                for s in sensor:
                    s.step(dt_usec)
            else:
                sensor.step(dt_usec)

        # Step the time dialator to keep our timers in sync
        self.time_dialator.step(dt_usec)
        if self.n_steps_taken % 500 == 0:
            self.logger.debug(
                "Time dialation factor is {} after {} steps".format(
                    self.time_dialator.dialation, self.n_steps_taken))

            # Debugging
            self.logger.debug("Track DB {}".format(
                self.fcu.lib.u32FCU_FCTL_TRACKDB__Get_CurrentDB()))

            info = [
                #self.fcu.lib.u8FCU_FCTL_TRACKDB__Accel__Get_Use(),  # Deprecated
                self.fcu.lib.
                s32FCU_FCTL_TRACKDB__Accel__Get_Accel_Threshold_mm_ss(),
                self.fcu.lib.
                s16FCU_FCTL_TRACKDB__Accel__Get_Accel_ThresholdTime_x10ms(),
                self.fcu.lib.
                s32FCU_FCTL_TRACKDB__Accel__Get_Decel_Threshold_mm_ss(),
                self.fcu.lib.
                s16FCU_FCTL_TRACKDB__Accel__Get_Decel_ThresholdTime_x10ms(),
            ]
            self.logger.debug("Track DB: Accel: {}".format(info))

            info = {
                'psa': self.pusher.acceleration,
                'psv': self.pusher.velocity,
                'psp': self.pusher.position,
                'pda': self.pod.acceleration,
                'pdv': self.pod.velocity,
                'pdp': self.pod.position,
            }
            self.logger.debug(
                "Pusher avp:  {psa}  {psv}  {psp};  Pod avp:  {pda}  {pdv}  {pdp}"
                .format(**info))

        self.elapsed_time_usec += dt_usec
        self.n_steps_taken += 1

        for step_listener in self.step_listeners:
            step_listener.step_callback(self)

    def run_threaded(self):
        """ Run the simulator in a thread and return the thread (don't join it here) """

        t = threading.Thread(target=self.run, args=())
        t.daemon = True
        t.start()
        return t  # Return the thread, but don't join it (the caller can join if they want to)

    def run(self):

        self.logger.info("Starting simulation")

        self.end_flag = False
        sim_start_t = time.time()

        # Notify preprocessors
        for processor in self.preprocessors:
            processor.process(self)

        # Networking
        self.comms.run_threaded()  # Start the network node listeners

        # FCU
        if self.config.fcu.enabled:
            self.fcu.run_threaded()

        while (True):

            # Check our end listener(s) to see if we should end the simulation (e.g. the pod has stopped)
            for listener in self.end_conditions:
                if listener.is_finished(self):
                    self.end_flag = True

            if self.end_flag:
                # Notify our 'finished' listeners and break the loop
                for end_listener in self.end_listeners:
                    end_listener.end_callback(self)

                break

            self.step(self.fixed_timestep_usec)

        sim_end_t = time.time()
        sim_time = sim_end_t - sim_start_t
        #print "LaserOptoTestListener: gap sensor took {} samples that were within a gap.".format(self.lotl.n_gaps)
        self.logger.info(
            "Simulated {} steps/{} seconds in {} actual seconds.".format(
                self.n_steps_taken, self.elapsed_time_usec / 1000000,
                sim_time))

        # Notify postprocessors
        for processor in self.postprocessors:
            processor.process(self)

    def add_step_listener(self, listener):
        """ 
        Register a listener that will be called every step. 
        A step listener can be any class that implements the following method:
        - step_callback(sim)
        """
        self.step_listeners.append(listener)

    def add_end_condition(self, listener):
        """ Add a listener that will tell us if we should end the simulator """
        self.end_conditions.append(listener)

    def add_end_listener(self, listener):
        """ Add a listener for when we've ended the sim """
        self.end_listeners.append(listener)

    def add_preprocessor(self, processor):
        self.preprocessors.append(processor)

    def add_postprocessor(self, processor):
        self.postprocessors.append(processor)

    def ensure_working_dir(self):
        """ Ensure existence of base directory for data storage """
        # @todo: Log the error/exception if there is one
        # Try to make the directory(s)

        path = self.config.working_dir

        try:
            os.makedirs(path)
        except OSError as exc:  # Python >2.5
            if exc.errno == errno.EEXIST and os.path.isdir(path):
                pass
            else:
                raise
Ejemplo n.º 14
0
from os import path

from kubernetes import client, config, watch

from deployment import Deployment
from pod import Pod

config.load_kube_config()

v1 = client.CoreV1Api()
print("Listing pods with their IPs:")
ret = v1.list_pod_for_all_namespaces(watch=False)
for i in ret.items:
    print("%s\t%s\t%s" %
          (i.status.pod_ip, i.metadata.namespace, i.metadata.name))

if __name__ == '__main__':
    yaml_file = "yamls/deployments/nginx-deployment.yaml"
    yaml_file_path = path.join(path.dirname(__file__), yaml_file)
    deployment = Deployment("nginx-deployment", "default", yaml_file_path)
    deployment.patch()
    # deployment.patch()
    # deployment.delete()
    pods = Pod()
    pods.get_pods()
Ejemplo n.º 15
0
    def __init__(self, config, working_dir=None):
        self.logger = logging.getLogger("Sim")

        self.logger.info("Initializing simulation")

        # Config
        self.config = config

        # Working directory (for csv files and whatnot)
        if working_dir is not None:
            self.set_working_dir(working_dir)

        self.logger.info("Working directory is {} ({})".format(
            self.config.working_dir,
            os.path.join(os.getcwd(), self.config.working_dir)))

        self.ensure_working_dir()

        # Simulator control
        self.end_conditions = []
        self.end_listeners = []

        # Pre and post
        self.preprocessors = []
        self.postprocessors = []

        # Time
        self.fixed_timestep_usec = Units.usec(
            config.fixed_timestep)  # Convert to usec
        self.time_dialator = TimeDialator(self)  # We're going to step this

        # Components
        self.pusher = Pusher(self, self.config.pusher)
        self.track = Track(self, self.config.track)
        self.pod = Pod(self, self.config.pod)
        #self.fcu = Fcu(self, self.config.fcu)

        # Sensors
        self.sensors = {}
        self.sensors['pod'] = PodSensor(self, self.config.sensors.pod)
        self.sensors['pod'].add_step_listener(
            SensorCsvWriter(self, self.config.sensors.pod))

        # - Accelerometers
        self.sensors['accel'] = []

        for idx, sensor_config in self.config.sensors.accel.iteritems():
            # Note: we need to create a Config object here because Config does not currently handle lists very well...
            self.sensors['accel'].append(
                Accelerometer(self, Config(sensor_config)))
            sensor = self.sensors['accel'][idx]
            sensor.add_step_listener(
                AccelerometerTestListener(self, sensor.config))
            sensor.add_step_listener(SensorCsvWriter(self, sensor.config))
            #sensor.add_step_listener(SensorRawCsvWriter(self, sensor.config))

        # - Laser Contrast Sensors
        self.sensors['laser_contrast'] = []
        for idx, sensor_config in self.config.sensors.laser_contrast.iteritems(
        ):
            self.sensors['laser_contrast'].append(
                LaserContrastSensor(self, Config(sensor_config)))
            sensor = self.sensors['laser_contrast'][idx]
            #sensor.add_step_listener(LaserContrastTestListener(self, sensor.config))  # For debugging
            sensor.add_step_listener(SensorCsvWriter(self, sensor.config))
            #sensor.add_step_listener(SensorRawCsvWriter(self, sensor.config))  # These don't have 'raw' values since they just call an interrupt

        # - Laser Opto Sensors (height and yaw)
        self.sensors['laser_opto'] = []
        for idx, sensor_config in self.config.sensors.laser_opto.iteritems():
            self.sensors['laser_opto'].append(
                LaserOptoSensor(self, Config(sensor_config)))
            sensor = self.sensors['laser_opto'][idx]
            #sensor.add_step_listener(LaserOptoTestListener(self, sensor.config))  # For debugging
            sensor.add_step_listener(SensorCsvWriter(self, sensor.config))
            #sensor.add_step_listener(SensorRawCsvWriter(self, sensor.config))

        # - Laser Distance Sensor
        self.sensors['laser_dist'] = LaserDistSensor(
            self, Config(self.config.sensors.laser_dist))
        sensor = self.sensors['laser_dist']
        sensor.add_step_listener(SensorCsvWriter(self, sensor.config))
        #sensor.add_step_listener(SensorRawCsvWriter(self, sensor.config))

        # - Brake Sensors: MLP, limit switches (for both)
        pass

        # Networking
        self.comms = PodComms(self, self.config.networking)
        self.add_end_listener(self.comms)

        # FCU (!)
        if self.config.fcu.enabled:
            self.fcu = Fcu(self, self.config.fcu)
            self.add_end_listener(self.fcu)
        else:
            # @todo: will this have any side effects (e.g. not having an fcu?)
            self.logger.info(
                "Not initializing FCU because it is disabled via config.")

        # Initial setup
        self.pusher.start_push()

        # Volatile
        self.elapsed_time_usec = 0
        self.n_steps_taken = 0

        # Testing laser opto sensor class
        # self.laser_opto_sensors = LaserOptoSensors(self, self.config.sensors.laser_opto)

        #self.pod_sensor_writer.pause()  # Paused for use in the gui

        # Testing brakes  (pod now has brakes)
        #from brakes import Brake
        #self.brake_1 = Brake(self, None)
        #self.brake_1.gap = 0.025 # Set it to test forces

        # End condition checker (to stop the simulation)
        self.add_end_condition(SimEndCondition())
Ejemplo n.º 16
0
class Sim:
    def __init__(self, config, working_dir=None):
        self.logger = logging.getLogger("Sim")

        self.logger.info("Initializing simulation")

        # Config
        self.config = config

        # Working directory (for csv files and whatnot)
        if working_dir is not None:
            self.set_working_dir(working_dir)

        self.logger.info("Working directory is {} ({})".format(
            self.config.working_dir,
            os.path.join(os.getcwd(), self.config.working_dir)))

        self.ensure_working_dir()

        # Simulator control
        self.end_conditions = []
        self.end_listeners = []

        # Pre and post
        self.preprocessors = []
        self.postprocessors = []

        # Time
        self.fixed_timestep_usec = Units.usec(
            config.fixed_timestep)  # Convert to usec
        self.time_dialator = TimeDialator(self)  # We're going to step this

        # Components
        self.pusher = Pusher(self, self.config.pusher)
        self.track = Track(self, self.config.track)
        self.pod = Pod(self, self.config.pod)
        #self.fcu = Fcu(self, self.config.fcu)

        # Sensors
        self.sensors = {}
        self.sensors['pod'] = PodSensor(self, self.config.sensors.pod)
        self.sensors['pod'].add_step_listener(
            SensorCsvWriter(self, self.config.sensors.pod))

        # - Accelerometers
        self.sensors['accel'] = []

        for idx, sensor_config in self.config.sensors.accel.iteritems():
            # Note: we need to create a Config object here because Config does not currently handle lists very well...
            self.sensors['accel'].append(
                Accelerometer(self, Config(sensor_config)))
            sensor = self.sensors['accel'][idx]
            sensor.add_step_listener(
                AccelerometerTestListener(self, sensor.config))
            sensor.add_step_listener(SensorCsvWriter(self, sensor.config))
            #sensor.add_step_listener(SensorRawCsvWriter(self, sensor.config))

        # - Laser Contrast Sensors
        self.sensors['laser_contrast'] = []
        for idx, sensor_config in self.config.sensors.laser_contrast.iteritems(
        ):
            self.sensors['laser_contrast'].append(
                LaserContrastSensor(self, Config(sensor_config)))
            sensor = self.sensors['laser_contrast'][idx]
            #sensor.add_step_listener(LaserContrastTestListener(self, sensor.config))  # For debugging
            sensor.add_step_listener(SensorCsvWriter(self, sensor.config))
            #sensor.add_step_listener(SensorRawCsvWriter(self, sensor.config))  # These don't have 'raw' values since they just call an interrupt

        # - Laser Opto Sensors (height and yaw)
        self.sensors['laser_opto'] = []
        for idx, sensor_config in self.config.sensors.laser_opto.iteritems():
            self.sensors['laser_opto'].append(
                LaserOptoSensor(self, Config(sensor_config)))
            sensor = self.sensors['laser_opto'][idx]
            #sensor.add_step_listener(LaserOptoTestListener(self, sensor.config))  # For debugging
            sensor.add_step_listener(SensorCsvWriter(self, sensor.config))
            #sensor.add_step_listener(SensorRawCsvWriter(self, sensor.config))

        # - Laser Distance Sensor
        self.sensors['laser_dist'] = LaserDistSensor(
            self, Config(self.config.sensors.laser_dist))
        sensor = self.sensors['laser_dist']
        sensor.add_step_listener(SensorCsvWriter(self, sensor.config))
        #sensor.add_step_listener(SensorRawCsvWriter(self, sensor.config))

        # - Brake Sensors: MLP, limit switches (for both)
        pass

        # Networking
        self.comms = PodComms(self, self.config.networking)
        self.add_end_listener(self.comms)

        # FCU (!)
        if self.config.fcu.enabled:
            self.fcu = Fcu(self, self.config.fcu)
            self.add_end_listener(self.fcu)
        else:
            # @todo: will this have any side effects (e.g. not having an fcu?)
            self.logger.info(
                "Not initializing FCU because it is disabled via config.")

        # Initial setup
        self.pusher.start_push()

        # Volatile
        self.elapsed_time_usec = 0
        self.n_steps_taken = 0

        # Testing laser opto sensor class
        # self.laser_opto_sensors = LaserOptoSensors(self, self.config.sensors.laser_opto)

        #self.pod_sensor_writer.pause()  # Paused for use in the gui

        # Testing brakes  (pod now has brakes)
        #from brakes import Brake
        #self.brake_1 = Brake(self, None)
        #self.brake_1.gap = 0.025 # Set it to test forces

        # End condition checker (to stop the simulation)
        self.add_end_condition(SimEndCondition())

        # Handle data writing
        # @ todo: handle data writing. Note: Each sim instance should be handed a directory to use for writing data

    @classmethod
    def load_config_files(cls, config_files):
        """ Load one or more config files (later files overlay earlier ones) """

        config = Config()
        for configfile in config_files:
            # Note: each file loaded by the config will overlay on the previously loaded files
            config.loadfile(configfile)
        return config.sim

    def set_working_dir(self, working_dir):
        """ Set our working directory (for file writing and whatnot) """
        self.config.working_dir = working_dir

    def step(self, dt_usec):

        # Step the pusher first (will apply pressure and handle disconnection)
        self.pusher.step(dt_usec)

        # Step the pod (will handle all other forces and pod physics)
        self.pod.step(dt_usec)

        # Step the sensors
        for sensor in self.sensors.values():
            # Some of our sensors are lists of sensors
            if isinstance(sensor, list):
                for s in sensor:
                    s.step(dt_usec)
            else:
                sensor.step(dt_usec)

        # Step the time dialator to keep our timers in sync
        self.time_dialator.step(dt_usec)
        if self.n_steps_taken % 500 == 0:
            self.logger.debug(
                "Time dialation factor is {} after {} steps".format(
                    self.time_dialator.dialation, self.n_steps_taken))

        self.elapsed_time_usec += dt_usec
        self.n_steps_taken += 1

    def run_threaded(self):
        """ Run the simulator in a thread and return the thread (don't join it here) """

        t = threading.Thread(target=self.run, args=())
        t.daemon = True
        t.start()
        return t  # Return the thread, but don't join it (the caller can join if they want to)

    def run(self):

        self.logger.info("Starting simulation")

        self.end_flag = False
        sim_start_t = time.time()

        # Notify preprocessors
        for processor in self.preprocessors:
            processor.process(self)

        # Networking
        self.comms.run_threaded()  # Start the network node listeners

        # FCU
        if self.config.fcu.enabled:
            self.fcu.run_threaded()

        while (True):

            # Check our end listener(s) to see if we should end the simulation (e.g. the pod has stopped)
            for listener in self.end_conditions:
                if listener.is_finished(self):
                    self.end_flag = True

            if self.end_flag:
                # Notify our 'finished' listeners and break the loop
                for end_listener in self.end_listeners:
                    end_listener.end_callback(self)

                break

            self.step(self.fixed_timestep_usec)

        sim_end_t = time.time()
        sim_time = sim_end_t - sim_start_t
        #print "LaserOptoTestListener: gap sensor took {} samples that were within a gap.".format(self.lotl.n_gaps)
        self.logger.info(
            "Simulated {} steps/{} seconds in {} actual seconds.".format(
                self.n_steps_taken, self.elapsed_time_usec / 1000000,
                sim_time))

        # Notify postprocessors
        for processor in self.postprocessors:
            processor.process(self)

    def add_end_condition(self, listener):
        """ Add a listener that will tell us if we should end the simulator """
        self.end_conditions.append(listener)

    def add_end_listener(self, listener):
        """ Add a listener for when we've ended the sim """
        self.end_listeners.append(listener)

    def add_preprocessor(self, processor):
        self.preprocessors.append(processor)

    def add_postprocessor(self, processor):
        self.postprocessors.append(processor)

    def ensure_working_dir(self):
        """ Ensure existence of base directory for data storage """
        # @todo: Log the error/exception if there is one
        # Try to make the directory(s)

        path = self.config.working_dir

        try:
            os.makedirs(path)
        except OSError as exc:  # Python >2.5
            if exc.errno == errno.EEXIST and os.path.isdir(path):
                pass
            else:
                raise