Example #1
0
    def setup(self):

        logger.info("Starting setup")

        if config.mouse_type == "pitft_touchscreen":
            self.touch = pitft_touchscreen()
            self.touch.start()

        self.controller = Controller(logger)

        pygame_init_done = False
        while not pygame_init_done:
            try:
                pygame.init()
                if config.raspberry:
                    pygame.mouse.set_visible(False)
                pygame_init_done = True
            except:
                logger.debug("Pygame init failed")
                pygame_init_done = False
                time.sleep(5)

        size = config.screen_width, config.screen_height
        if config.screen_fullscreen:
            logger.debug("Pygame init Fullscreen")
            self.screen = pygame.display.set_mode(size, pygame.FULLSCREEN)
        else:
            logger.debug("Pygame init Windowed")
            self.screen = pygame.display.set_mode(size)
        pygame.display.set_caption('pitft-volumioui')

        self.sm = PlayerUI(logger, controller=self.controller)

        self.mouse_event = {"x": 0, "y": 0, "touch": 0}
Example #2
0
 def setUp(self):
     self.db = SQLQuery(DBConfig)
     try:
         self.db.execute('CREATE TABLE test_table (id INT)', alter=True)
     except:
         pass
     self.control = Controller(self.db)
Example #3
0
def turn_one_wheel(v, angle, motor, g=None, c=None):
    """
    """

    L = io.motA
    R = io.motB
    servo = io.servo
    gyro = io.gyro
    col = io.col

    if angle > 0:
        direction = 1  # set the polairty switch for the wheels
    elif angle < 0:
        direction = -1
    else:  # 0 degrees = no work to be done
        return
    print(direction)

    # -------------- ROBOT ---------------------
    if motor == 'ROBOT':
        desired_angle = gyro.value() + angle
        logging.info(
            'Turning the robot to desired {} degrees'.format(desired_angle))
        turn_control = Controller(.01, 0, 0, desired_angle, history=10)

        while True:

            signal, err = turn_control.control_signal(gyro.value())

            if abs(err) <= 5 or io.btn.backspace:  # tolerance
                L.stop()
                R.stop()
                L.duty_cycle_sp = v
                R.duty_cycle_sp = v
                return g, c

            else:
                # if too small or too large, just use the default v
                if abs(v + signal) >= 100 or abs(v + signal) <= 20: signal = 0
                if direction == 1:
                    L.run_direct(duty_cycle_sp=direction * abs(v + signal))
                elif direction == -1:
                    R.run_direct(duty_cycle_sp=-1 * direction *
                                 abs(v + signal))

            logging.info(
                'GYRO = {},\tcontrol = {},\t err={}, \tL = {}, \tR = {}'.
                format(gyro.value(), signal, err, L.duty_cycle_sp,
                       R.duty_cycle_sp))
            try:
                g.set_val(gyro.value())
                c.set_val(col.value())
            except AttributeError:
                pass

    else:
        raise NameError('motor should be "ROBOT" or "SERVO"')
Example #4
0
 def __init__(self, width, height, initLoc=pg.Vector2(0, 0), delay=200):
     self.width = width
     self.height = height
     self.win = pg.display.set_mode((width, height))
     self.snake = Snake(self.win, initLoc)
     self.control = Controller()
     self.running = True
     self.delay = delay
     self.food = pg.Vector2(60, 60)
     pg.display.set_caption("Smake!")
Example #5
0
def case3():
    ## this case tests the optimizing function.
    ## elevator 0 will reach it's destination after elevator 2 starts to attempt to service the request.
    ## since elevator 0's status changes to WAITING and it is closer to floor 12
    ## elevator 2 is cancelled and elevator 0 will overtake the request.

    elevators_num = 3
    floors_num = 40

    c = Controller(elevators_num, floors_num)
    c.start()

    c.request_up(10)
    time.sleep(25)
    c.request_down(8)
    time.sleep(5)
    c.request_up(12)
    time.sleep(5)

    running1 = True
    running2 = True
    running3 = True

    while running1 or running2 or running3:
        if c.elevators[0].status == Elevator.WAITING:
            running1 = False
        if c.elevators[1].status == Elevator.WAITING:
            running2 = False
        if c.elevators[2].status == Elevator.WAITING:
            running3 = False

    for e in c.elevators:
        c.elevators[e].running = False
Example #6
0
 def setup_controllers(self, pos_range, m, v, v_range):
     self.m_controller = Controller("Mass m", self.config.MASS_MIN,
                                    self.config.MASS_MAX, m, self.control_m)
     self.pos_x_controller = Controller("Position x", -pos_range, pos_range,
                                        self.pos[0], self.control_pos)
     self.pos_y_controller = Controller("Position y", -pos_range, pos_range,
                                        self.pos[1], self.control_pos)
     self.v_rho_controller = Controller("Velocity ρ", 0, v_range, v[0],
                                        self.control_v)
     self.v_phi_controller = Controller("Velocity φ", -180, 180,
                                        rad2deg(v[1]), self.control_v)
Example #7
0
def simulate(arm, traj, tf, dt_dyn, dt_control=None, u_inj=None):
    """
    Inputs:
        arm: arm object
        traj: desired trajectory
        tf: desired final simulation time
        dt: desired dt for control
        u_inj: control injection
    """

    dynamics = Dynamics(arm, dt_dyn)
    # dynamics = Dynamics(arm, dt_dyn, noise_torsion=[1e-3,0], noise_bending=[1e-3,0,0,0])

    if dt_control is None:
        dt_control = dt_dyn
    else:
        dt_control = max(np.floor(dt_control / dt_dyn) * dt_dyn, dt_dyn)
    T = int(dt_control / dt_dyn)

    dyn_reduced = Dynamics(arm, dt_control, n=arm.state.n)
    controller = Controller(dyn_reduced)

    state_list = []
    control_list = []

    t_steps = int(np.floor(tf / dt_dyn))
    t_arr = np.linspace(0, tf, t_steps + 1)
    for i, t in enumerate(t_arr):
        print('Progress: {:.2f}%'.format(float(i) / (len(t_arr) - 1) * 100),
              end='\r')

        # mode = finiteStateMachine(y,wp)
        # mode = 'none'
        # mode = 'damping'
        mode = 'mpc'

        if i % T == 0:
            j = i // T
            if j not in u_inj:
                wp = traj[:, j]
                y = simulateMeasurements(arm)
                u = controller.controlStep(y, wp, mode)
            else:
                u = {}
                u['rot'] = u_inj[j]['rot']
                u['lat'] = u_inj[j]['lat']

        arm = dynamics.dynamicsStep(arm, u)

        state_list.append(copy.copy(arm.state))
        control_list.append(u)

    return state_list, control_list, t_arr
Example #8
0
    def check_func(self):
        '''
        检查服务器连接状态、以及其他状态是否正确
        '''
        # 尝试连接服务器,若无法连接提示错误
        try:
            r = req.get(self.server)
        except:
            # raise Exception('Invalid Server')
            tm.showerror(title='INVALID', message='Invalid Server')
            return

        # self.cond 可以再做修改,添加状态检测,目前设置为True
        self.cond = True
        # 提示是否进入控制模式
        if self.cond:
            enter = tm.askquestion(title='Checked!',
                                   message='Enter Control Mode?')
        if enter == 'no':
            pass
        else:
            self.master.destroy()
            # 进入控制模式
            robot_id = self.robot_id
            token = self.token
            server = self.server
            jack_up = self.jack_up_down
            vel = self.vel
            follow = self.follow
            root = tk.Tk()
            controller = Controller(root, robot_id, token, server, jack_up,
                                    vel, follow)
            controller.master.mainloop()
Example #9
0
def est_final_params(gt_observations):

    # use dummy controller to run EM
    num_w, num_q = gt_observations.shape
    c = Controller(method=None, platform=None,
                   num_workers=num_w, num_questions=num_q)

    params,_ = c.run_em(gt_observations)

    
        
    d = params['difficulties']
    s = params['skills']
        
    parse.params_to_file('gold_params.csv',params)
    return d,s
Example #10
0
class Game:
    def __init__(self, width, height, initLoc=pg.Vector2(0, 0), delay=200):
        self.width = width
        self.height = height
        self.win = pg.display.set_mode((width, height))
        self.snake = Snake(self.win, initLoc)
        self.control = Controller()
        self.running = True
        self.delay = delay
        self.food = pg.Vector2(60, 60)
        pg.display.set_caption("Smake!")

    def display(self):
        pg.init()
        while self.running:
            self.getInput()
            self.main()
        pg.quit()

    def main(self):
        self.win.fill((0, 0, 0))
        vel = 20 * self.getControll()
        self.drawFood(self.food)
        pg.time.delay(self.delay)
        
        self.snake.updateLoc(vel)
        if self.snake.ateFood(self.food):
            self.snake.addToTail()
            self.makeFood()
        self.crashChecked()

        self.snake.draw()

        pg.display.update()

    def getInput(self):
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.running = False

    def getControll(self):
        command = pg.key.get_pressed()
        vel = self.control.getKey(command)
        return vel
    
    def makeFood(self):
        x = r.randint(0, self.width/20 - 1)
        y = r.randint(0, self.height/20 - 1)
        self.food = 20 * pg.Vector2(x, y)

    def drawFood(self, loc):
        pg.draw.rect(self.win, (255, 0, 0), (loc.x, loc.y, 20, 20))

    def crashChecked(self):
        snake = self.snake.getLoc()
        if 0 <= snake.x <= self.width and 0 <= snake.y <= self.height:
            return
        
        self.running = False
Example #11
0
def status():
    response_data = {}
    if request.method == 'GET':
        pluginID = request.args.get('pluginID', '')
        if len(pluginID) > 0:
            status = Controller.control("status", pluginID)
            response_data["status"] = status
    return jsonify(response_data)
Example #12
0
class MyTestCase(unittest.TestCase):
    def setUp(self) -> None:
        self.controller = Controller()
        self.controller.click_on_rel_pos(
            self.controller.start_button_rel_coord)

    # def test_tile_clicking(self):
    #     tile_ids = tuple(product(range(self.controller.tile_rows), range(self.controller.tile_cols)))
    #     self.controller.click_on_tiles(tile_ids, interval=0.0)

    def test_img_capturing(self):
        img = self.controller.take_screenshot()
        img.save("../local/raw_test.png")
        region = detect_tile_region(img, self.controller.tile_region_area)
        region.save("../local/test.png")

    def tearDown(self) -> None:
        self.controller.shut_down()
Example #13
0
def main(system, ai, mode):
    """
    TrafficAI command line tool
    """
    controller = Controller()
    controller.load_system(system, ai)

    if mode == 'run':
        controller.present()
    elif mode == 'train':
        controller.develop()
Example #14
0
class Game(object):
    def __init__(self):
        self.view = OpenGLDisplay(self, width=1600, height=900)
        self.controller = Controller(self)
        self.model = HexGrid(self)

        self.setupUniverse()

    def setupUniverse(self):
        self.view.setupView()
        self.controller.setupController()

        glutMainLoop()

    def teardownUniverse(self):
        self.controller.teardownController()
        self.view.teardownView()

        exit()
Example #15
0
def control():
    if request.method == 'POST':
        data = request.form['data']
        if len(data) > 0:
            json_data = eval(data)
            Config().p(json_data)
            return Controller.parse_commands(json_data["msgcontent"],
                                             json_data["target"])
        else:
            return "-1"
Example #16
0
    def __init__(self, grid, astar, plan_and_drive):
        # other classes
        self.grid = grid
        self.astar = astar
        self.controller = Controller()

        # visual display
        self.fig, self.ax = plt.subplots()

        if plan_and_drive:
            self.display(False)
        else:
            self.display(True)

        self.l = 0.1
        self.wait = 0.01

        # threshold distance goal/waypoint
        self.threshold = 0.15
Example #17
0
 def _run_jobs(self):
     """
     Runs the control script with the selected json file
     """
     self.is_controlling = True
     with open(self.window.filename, "r", encoding='utf-8') as f:
         events = Event.schema().load(json.load(f), many=True)
         ctrlr = Controller(events, self.controller_terminate)
         iterations = int(self.spinbox.get())
         t = Thread(target=ctrlr.run, args=[iterations])
         t.start()
Example #18
0
def main():
    tf.compat.v1.disable_eager_execution()

    # dataset
    dset = Dataset(config)
    dset.build()
    config.vocab_size = len(dset.word2id)
    config.pos_size = len(dset.pos2id)
    config.ner_size = len(dset.ner2id)
    config.dec_start_id = dset.word2id["_GOO"]
    config.dec_end_id = dset.word2id["_EOS"]
    config.pad_id = dset.pad_id
    config.stop_words = dset.stop_words

    model = LatentBow(config)
    with tf.compat.v1.variable_scope(config.model_name):
        model.build()

    # controller
    controller = Controller(config)
    controller.train(model, dset)
Example #19
0
def main():
    """Main function."""
    # Create an instance of QApplication
    pycalc = QApplication(sys.argv)
    # Show the calculator's GUI
    view = GUI()
    view.show()

    # Create instances of the model and the controller
    Model = evaluateExpression
    Controller(model=Model, view=view)

    # Execute the calculator's main loop
    sys.exit(pycalc.exec_())
Example #20
0
    def Startup(self):
        # Importing takes sometime, therefore it will be done
        # while splash is being shown
        from gui.frame import Frame
        from control import Controller
        from project import Project

        self.main = Frame(None)
        self.control = Controller(self.main)

        self.fc = wx.FutureCall(1, self.ShowMain)
        wx.FutureCall(1, parse_comand_line)

        # Check for updates
        from threading import Thread
        p = Thread(target=utils.UpdateCheck, args=())
        p.start()
Example #21
0
class Game(object):
    def __init__(self):
        self.input = Controller()
        self.world = World(debug=True)

    def output(self, o):
        print '\n' * 100, o

    def play(self):
        world_output = self.world.start
        while True:
            try:
                self.output(world_output)
                action = self.input.get_action()
                world_output = self.world.make_action(action)
            except SystemExit:
                print "\nBye Bye"
                sys.exit(0)
Example #22
0
class Game(object):
    def __init__(self):
        self.input  = Controller()
        self.world  = World(debug=True)

    def output(self, o):
        print '\n'*100, o

    def play(self):
        world_output = self.world.start
        while True:
            try:
                self.output(world_output)
                action = self.input.get_action()
                world_output = self.world.make_action(action)
            except SystemExit:
                print "\nBye Bye"
                sys.exit(0)
Example #23
0
def main(screen):
    app_log = startLog(LOGFILE)
    screen.addstr(0, 0, 'Loading Nutmeg...')
    screen.refresh()

    with open('testuser-password', 'r') as passFile:
        PASSWORD = passFile.read().strip()
    HOMESERVER = 'lrizika.com'
    USERNAME = '******'
    ROOMNAME = '#test4:lrizika.com'
    app_log.info('Building Controller...')
    controller = Controller(screen,
                            HOMESERVER,
                            username=USERNAME,
                            password=PASSWORD)
    inputController = InputController(controller)
    controller.stateManager.joinRoom(ROOMNAME)

    inputController.listen()
Example #24
0
def case2():

    # CASE 2 - crash elevator.
    elevators_num = 2
    floors_num = 40

    c = Controller(elevators_num, floors_num)
    c.start()

    # create some random floors to use for testing
    random_floors = []
    for i in range(10):
        floor = random.randrange(1,floors_num-1)
        random_floors.append(floor)

    called_floors = []

    floor = random_floors.pop()
    print floor
    called_floors.append(floor)
    c.request_up(floor)

    time.sleep(5)

    for e in c.elevators:
        if c.elevators[e].status != Elevator.WAITING:
            c.crash(e)

    time.sleep(10)

    running1 = True
    running2 = True
    while running1 or running2:
        if c.elevators[0].status == Elevator.WAITING or c.elevators[0].status == Elevator.OFFLINE:
            running1 = False
        if c.elevators[1].status == Elevator.WAITING or c.elevators[0].status == Elevator.OFFLINE:
            running2 = False

    for e in c.elevators:
        c.elevators[e].running = False
Example #25
0
 def loop_dir():
     data = {}
     plug_dir = Config().root_dir + 'plugs/'
     for s in os.listdir(plug_dir):
         plug_id = s.encode('utf-8')
         md5File = plug_dir + plug_id + "/policy/md5"
         print md5File
         try:
             f = file(md5File)
             policyInfo = json.load(f)
             f.close()
             policyID = policyInfo["id"].encode('utf-8')
             policyMD5 = policyInfo["hashcode"].encode('utf-8')
             status = Controller.control("status", plug_id)
             data[plug_id] = {
                 "pluginId": plug_id,
                 "status": status,
                 "policyId": [{
                     "id": policyID,
                     "hashcode": policyMD5
                 }]
             }
         except Exception, e:
             print e
Example #26
0
    def hashGet(cls, pluginID, pluginHash):
        plugDir = Config.root_dir + "plugs/" + pluginID + "/"
        plugInstallDir = Config.root_dir + "install/" + pluginID + "/"

        if os.path.exists(plugDir) is False:
            if os.path.exists(plugInstallDir) is False:
                Controller.download(pluginID, pluginHash)
            else:
                hashFile = plugInstallDir + "md5"
                try:
                    f = file(hashFile)
                    line = f.readline()
                    f.close()
                except Exception, e:
                    print e
                    #插件不存在,下载插件
                    Controller.download(pluginID, pluginHash)
                    return
                if line != pluginHash:
                    Controller.download(pluginID, pluginHash)
            return
Example #27
0
def main():
    con = Controller("sample.cfg", "True")
    con.run()
Example #28
0
from control import Controller

main = Controller()
main.inicio()



Example #29
0
    def __init__(self):
        self.view = OpenGLDisplay(self, width=1600, height=900)
        self.controller = Controller(self)
        self.model = HexGrid(self)

        self.setupUniverse()
Example #30
0
import tkinter as tk
import gui.FirstInteface as FI
import control.Controller as Con

if __name__ == '__main__':
    root = tk.Tk()
    root.title("الحسابات")
    FI.MainInterface(root, Con.Controller())
    root.mainloop()
Example #31
0
def turn_on_spot(v, angle, motor, g=None, c=None):
    """
    Turn the robot or servo motor on the spot by the angle.
    :param v - the duty_cycle_sp at which the motor should travel at
    :param motor - either 'SERVO' or 'MOTOR'
    :param angle - If the angle is negative, it will turn CCW else CW.
    It sets the goal state of the robot or servo as the sum
    of its current heading (gyro.value()) and the angle.
    """

    L = io.motA
    R = io.motB
    servo = io.servo
    gyro = io.gyro
    col = io.col

    if angle > 0:
        direction = 1  # set the polairty switch for the wheels
    elif angle < 0:
        direction = -1
    else:  # 0 degrees = no work to be done
        return
    print(direction)

    # -------------- ROBOT ---------------------
    if motor == 'ROBOT':
        desired_angle = gyro.value() + angle
        logging.info(
            'Turning the robot to desired {} degrees'.format(desired_angle))
        turn_control = Controller(.01, 0, 0, desired_angle, history=10)

        while True:

            signal, err = turn_control.control_signal(gyro.value())

            signal, err = turn_control.control_signal(gyro.value())

            if abs(err) <= 5 or io.btn.backspace:  # tolerance
                L.stop()
                R.stop()
                L.duty_cycle_sp = v
                R.duty_cycle_sp = v
                return

            else:
                # if too small or too large, just use the default v
                if abs(v + signal) >= 100 or abs(v + signal) <= 20: signal = 0
                L.run_direct(duty_cycle_sp=direction * abs(v + signal))
                R.run_direct(duty_cycle_sp=-1 * direction * abs(v + signal))

            logging.info(
                'GYRO = {},\tcontrol = {},\t err={}, \tL = {}, \tR = {}'.
                format(gyro.value(), signal, err, L.duty_cycle_sp,
                       R.duty_cycle_sp))
            try:
                g.set_val(gyro.value())
                c.set_val(col.value())
            except AttributeError:
                pass

    # -------------- SERVO ---------------------
    elif motor == 'SERVO':
        turn_control = Controller(.001,
                                  0,
                                  .5,
                                  servo.position + angle,
                                  history=10)
        # servo.duty_cycle_sp = servo.duty_cycle_sp * direction
        ev3.Sound.speak('Turning servo {} degrees'.format(angle)).wait()
        logging.info('Turning servo {} degrees'.format(angle))

        while True:

            signal, err = turn_control.control_signal(servo.position)
            if abs(err) <= 4 or io.btn.backspace:  # tolerance
                servo.stop()
                servo.speed_sp = v
                servo.duty_cycle_sp = servo.duty_cycle_sp * \
                    direction  # return to the original number
                return

            if (v + abs(signal) >= 100): signal = 0
            signal = (direction) * (v + abs(signal))
            servo.run_direct(duty_cycle_sp=signal)
            logging.info(
                'POS = {},\tcontrol = {},\t err={}, \tspd = {}'.format(
                    servo.position, signal, err, servo.speed_sp))
            try:
                g.set_val(gyro.value())
            except AttributeError:
                pass
    else:
        raise NameError('motor should be "ROBOT" or "SERVO"')
Example #32
0
 def __init__(self):
     self.input  = Controller()
     self.world  = World(debug=True)
    def getParams(self, params):
            parsed_params = {}
            length = int(self.headers['Content-Length'])
            post_data = urlparse.parse_qs(self.rfile.read(length).decode('utf-8'))
            logger.debug("Parameters received: %s" % post_data)
            for p in params:
                if (post_data.has_key(p)):
                    parsed_params[p] = post_data[p][0]
            return parsed_params
            
        

if __name__ == '__main__':
    setup_logging()
    logger = logging.getLogger(__name__)
    controller = Controller()
    # initialize tcp port
    nmeaDataSource = NmeaDataSource(NMEA_HOST, NMEA_PORT, controller, watchFields)
    if not test:
        nmeaDataSource.connect()
        nmeaDataSource.start()

    httpd = BaseHTTPServer.HTTPServer((HTTP_HOST, HTTP_PORT), MyHandler)
    logger.info(time.asctime() + " Server Starts - %s:%s" % (HTTP_HOST, HTTP_PORT))
    try:
        logger.info("Serving Forever")
        httpd.serve_forever()
    except KeyboardInterrupt:
        logger.info("Interrupted By Keyboard")
    controller.reset_control()
    nmeaDataSource.close()
Example #34
0
 def setUp(self) -> None:
     self.controller = Controller()
     self.controller.click_on_rel_pos(
         self.controller.start_button_rel_coord)
Example #35
0
class ControllerTestCase(unittest.TestCase):
    def setUp(self):
        self.db = SQLQuery(DBConfig)
        try:
            self.db.execute('CREATE TABLE test_table (id INT)', alter=True)
        except:
            pass
        self.control = Controller(self.db)

    def test_hello(self):
        hello = self.control.get_hello()
        self.assertIsInstance(hello, str)

    def test_help(self):
        help = self.control.get_help()
        self.assertIsInstance(help, str)

    def test_scheduled_stats(self):
        stats = self.control.get_stats(scheduled=True)
        self.assertTrue('Запланированный отчет' in stats)

    def test_requested_stats(self):
        stats = self.control.get_stats()
        self.assertTrue('Внеплановый отчет' in stats)

    # Altering queries
    def test_correct_altering_query_as_admin(self):
        query = 'INSERT INTO test_table VALUES (1)'
        result = self.control.execute_command(query, rightful=True)
        self.assertEqual(result, 'База данных успешно изменена!')

    def test_wrong_altering_query_as_admin(self):
        query = 'DELETE * FROM test_table WHERE'
        result = self.control.execute_command(query, rightful=True)
        self.assertTrue('Запрос сформулирован неправильно' in result)

    def test_correct_altering_query_as_user(self):
        query = 'INSERT INTO test_table VALUES (2)'
        result = self.control.execute_command(query)
        self.assertTrue('У вас недостаточно прав' in result)

    def test_wrong_altering_query_as_user(self):
        query = 'INSERT INTO test_table VALUES (2)'
        result = self.control.execute_command(query)
        self.assertTrue('У вас недостаточно прав' in result)

    # Simple queries
    def test_correct_simple_query_as_admin(self):
        query = 'SELECT * FROM test_table'
        result = self.control.execute_command(query, rightful=True)
        self.assertIsInstance(result, str)

    def test_wrong_simple_query_as_admin(self):
        query = 'SELECT non_existing_colum FROM test_table'
        result = self.control.execute_command(query, rightful=True)
        self.assertIsInstance(result, str)

    def test_correct_simple_query_as_user(self):
        query = 'SELECT * FROM test_table'
        result = self.control.execute_command(query)
        self.assertIsInstance(result, str)

    def test_wrong_simple_query_as_user(self):
        query = 'SELECT non_existing_colum FROM test_table'
        result = self.control.execute_command(query)
        self.assertIsInstance(result, str)

    def tearDown(self):
        self.db.execute('DROP TABLE test_table', alter=True)
Example #36
0
                        help='List of hosts')
    parser.add_argument('--clear',
                        required=False,
                        type=int,
                        help='Clear control backup file')

    args = parser.parse_args()

    if (args.clear == 1):
        # Remove control layer data
        try:
            os.remove(args.control)
        except:
            pass

    controller = Controller(args.control)

    hosts = []
    #hosts = [("172.17.0.2", 18861), ("172.17.0.3", 18861)]  # IP,PORT TUPLE
    for host in args.hosts:
        hosts.append((host, args.port))

    hasActiveHost = controller.generateNodes(hosts)
    if (not hasActiveHost):
        exit(0)

    k = Thread(target=t, args=(controller, ))
    k.start()

    print(f"Mounting {args.real} on {args.virtual}")
    FUSE(Passthrough(controller, args.real),
Example #37
0
def main():
	con = Controller("sample.cfg", "True");
	con.run()
Example #38
0
@author: Leon Bonde Larsen

This is a quick test of the algorithm developed to generate s-curves in a system
with varying setpoints. Most implementations are based on systems where the entire
curve can be calculated on beforehand, but this is not possible in a system where
the setpoint varies over time.

The actual ode implemented in C++ is an exact copy of the code running in this 
simulation.

Being just an internal test, the settings are placed in the init method on the
Controller class. The controller is based on the constant jerk principle leading
to linear accelerations and second order velocities.

In the current test, the initial velocity is -1m/s and the user setpoint is +2m/s.
What is seen in the plot is that the system first brakes with  ramp to velocity 0m/S
and then accelerates and decelerates to hit the 2m/s velocity.
'''
from matplotlib import pyplot as plt
from control import Controller

plt.figure(num=None, figsize=(10, 6), dpi=80, facecolor='w', edgecolor='k')
ctrl = Controller()
           
ctrl.simulate()

plt.plot(ctrl.time,ctrl.pos)
plt.plot(ctrl.time,ctrl.vel)
plt.plot(ctrl.time,ctrl.acc)
plt.legend(["position","velocity","acceleration"])
plt.show()
Example #39
0
def case1():

    # CASE 1 - service random requests.
    elevators_num = 1
    floors_num = 40

    c = Controller(elevators_num, floors_num)
    c.start()

    # create some random floors to use for testing
    random_floors = []
    for i in range(19):
        floor = random.randrange(1,floors_num-20)
        random_floors.append(floor)

    called_floors = []

    floor = random_floors.pop()
    print floor
    called_floors.append(floor)
    c.request_up(floor)

    time.sleep(5)

    while random_floors:
        for e in c.elevators:
            if c.elevators[e].status == Elevator.WAITING:
                print 'Elevator ' + str(e)
                floor = random_floors.pop()
                print floor
                called_floors.append(floor)
                c.request_floor(e, floor)

                floor = random_floors.pop()
                print floor
                called_floors.append(floor)
                c.request_floor(e, floor)

                floor = random_floors.pop()
                print floor
                called_floors.append(floor)
                c.request_floor(e, floor)

                time.sleep(5)

    for e in c.elevators:
        c.elevators[e].running = False
Example #40
0
def case4():
    ## test the ability for an elevator to switch it final request and store the previous request into a pending request array
    ## initially elevator 2 will be heading for floor 12
    ## but we recieve a 5th request before any other elevators can service this request.
    ## since elevator 2 is going to floor 12.  It switches to floor 14 and then comes back down to floor 12

    elevators_num = 4
    floors_num = 40

    c = Controller(elevators_num, floors_num)
    c.start()

    c.request_up(10)
    time.sleep(1)
    c.request_down(8)
    time.sleep(1)
    c.request_down(12)
    time.sleep(1)
    c.request_up(15)
    time.sleep(1)
    c.request_down(14)
    time.sleep(1)

    running1 = True
    running2 = True
    running3 = True
    running4 = True

    while running1 or running2 or running3 or running4:
        if c.elevators[0].status == Elevator.WAITING:
            running1 = False
        if c.elevators[1].status == Elevator.WAITING:
            running2 = False
        if c.elevators[2].status == Elevator.WAITING:
            running3 = False
        if c.elevators[3].status == Elevator.WAITING:
            running3 = False

    for e in c.elevators:
        c.elevators[e].running = False
Example #41
0
args = parser.parse_args()

logger.critical("hoge")

camera = PiCamera()  # PiCamera object
camera.resolution = (640, 480)
camera.framerate = 30
window_size = 600
buffer = PiRGBArray(camera)  # PiRGBArray object
num_green = 5
time.sleep(0.1)  # 100ms

running = True
con = serial.Serial("/dev/ttyACM0", 9600)
con.write(b"I")
controller = Controller(num_green, window_size)
while running:
    for stream in camera.capture_continuous(buffer,
                                            format="bgr",
                                            use_video_port=True):

        frame = stream.array
        frame = imutils.resize(frame, width=window_size)
        blurred = cv2.GaussianBlur(frame, (11, 11), 0)
        hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)
        hsv = hsv[:-100, :, :]
        if (controller.key == "green"):
            centre_info = find_green(hsv)
        else:
            centre_info = find_red(hsv)
        controller.control(con, centre_info)
Example #42
0
def main(argv=None):
    floors = 0
    elevators = 0

    if argv is None:
        argv = sys.argv
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "f:e:h", ["floors=", "elevators=", "help"])
        except getopt.error, msg:
             raise Usage(msg)

        for opt, arg in opts:
            if opt in ('-e', '--elevators'):
                elevators = arg
            if opt in ('-f', '--floors'):
                floors = arg

        if elevators > 0 and floors > 0:
            c = Controller(int(elevators), int(floors))
            c.start()
            process = True

            while process:
                var = raw_input("Enter command: ")
                var =  var.split(' ')
                command = var[0]
                if command == 'quit':
                    process = False
                else:

                    if command == 'up':
                        # command expected in the form of 'up floor_num'
                        floor = var[1]
                        c.request_up(int(floor))
                    elif command == 'down':
                        # command expected in the form of 'down floor_num'
                        floor = var[1]
                        c.request_down(int(floor))
                    elif command == 'elevator':
                        # command expected in the form of 'elevator elevator_num floor_num'
                        elevator_num = var[1]
                        floor = var[2]
                        c.request_floor(int(elevator_num), int(floor))
                    elif command == 'crash':
                        # command expected in the form of 'crash elevator_num'
                        elevator_num = var[1]
                        c.crash(int(elevator_num))


        else:
            print 'Elevator Bank Program'
            print 'usage: python elevator_bank.py -f num_floors -e num_elevators\n'
            print 'f num_floors    : enter the number of floors as a positive integer.  The first floor is 0.'
            print 'e num_elevators : enter the number of elevators as a positive integer.  The first elevator is 0.'
            print '-----------'
            print 'COMMANDS'
            print 'up floor_num - request up from a floor'
            print 'down floor_num - request down from a floor'
            print 'elevator elevator_num floor_num - Once inside of an elevator request a floor'
            print 'crash elevator_num - Crash an elevator'