Example #1
0
 def test_medium_identical_books(self):
     self.testdata.unpack_archive(1)
     self.testdata.make_duplicate(number=1)
     library = Library.Library()
     Controller.process_books(library, book_text_files=self.testdata.get_testbooks())
     verification = self.testdata.verify_results(library)
     self.assertAlmostEqual(1.0, zTestDataManager.TestBookManager.combine_results(verification),3)
Example #2
0
	def testController_run(self):
		def stub_keyInterrupt(sleepTime):
			amqpConn = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
			channel = amqpConn.channel()
			channel.queue_declare(queue = "queue")
			js = json.dumps({'agentHostName':'test_run_HostName',
							 'agentHostIp':'test_run_HostIp',
							 'agentHostTime':'test_run_HostTime',
							 'agentType':'test_run_AgentType',
							 'agentHostData':'test_run_HostData'})
			time.sleep(3)
			channel.basic_publish(exchange = '',
								  routing_key = "queue",
								  body = js)
			amqpConn.sleep(sleepTime)
			thread.interrupt_main()

		Controller.CONFIG_FILE_PATH = 'tests_Controller_config.txt'
		controller = Controller()
		thread.start_new_thread(stub_keyInterrupt,(3,))

		try:
			controller.run()
		except:
			self.fail("Unexpected Exception!")
		controller.logManager.session.commit()
		logs = controller.logManager.session.query(Log).order_by(Log.id).all()
		self.assertTrue('test_run_HostName' == logs[-1].agentHostName)
		controller.stop()
 def load(self):
         # metodo para cargar la grilla con los pacientes
         pacientes = Controller.pacientes()
         self.model = QtGui.QStandardItemModel(len(pacientes), 5)
         self.model.setHorizontalHeaderItem(0, QtGui.QStandardItem(u"Rut"))
         self.model.setHorizontalHeaderItem(1, QtGui.QStandardItem
                                           (u"Nombres"))
         self.model.setHorizontalHeaderItem(2, QtGui.QStandardItem
                                           (u"Apellidos"))
         self.model.setHorizontalHeaderItem(3, QtGui.QStandardItem
                                           (u"Ficha Medica"))
         self.model.setHorizontalHeaderItem(4, QtGui.QStandardItem
                                           (u"N Horas Medicas"))
         r = 0
         for row in pacientes:
             fk_rut_paciente = row['rut']
             index = self.model.index(r, 0, QtCore.QModelIndex())
             self.model.setData(index, row['Rut'])
             index = self.model.index(r, 1, QtCore.QModelIndex())
             self.model.setData(index, row['Nombres'])
             index = self.model.index(r, 2, QtCore.QModelIndex())
             self.model.setData(index, row['Apellidos'])
             index = self.model.index(r, 3, QtCore.QModelIndex())
             self.model.setData(index, row['Ficha_Medica'])
             index = self.model.index(r, 4, QtCore.QModelIndex())
             self.model.setData(index, Controller.obtenerNCitas(fk_rut_paciente))
             r = r + 1
         self.table.setModel(self.model)
 def load(self):
         # metodo para cargar la grilla con los medicos
         medicos = Controller.medicos()
         self.model = QtGui.QStandardItemModel(len(medicos), 5)
         self.model.setHorizontalHeaderItem(0, QtGui.QStandardItem(u"Rut"))
         self.model.setHorizontalHeaderItem(1, QtGui.QStandardItem
                                            (u"Nombres"))
         self.model.setHorizontalHeaderItem(2, QtGui.QStandardItem
                                            (u"Apellidos"))
         self.model.setHorizontalHeaderItem(3, QtGui.QStandardItem
                                            (u"Especialidad"))
         self.model.setHorizontalHeaderItem(4, QtGui.QStandardItem
                                            (u"N Horas Medicas"))
         r = 0
         for row in medicos:
             fk_rut_medico = row['rut']
             index = self.model.index(r, 0, QtCore.QModelIndex())
             self.model.setData(index, row['Rut'])
             index = self.model.index(r, 1, QtCore.QModelIndex())
             self.model.setData(index, row['Nombres'])
             index = self.model.index(r, 2, QtCore.QModelIndex())
             self.model.setData(index, row['Apellidos'])
             index = self.model.index(r, 3, QtCore.QModelIndex())
             self.model.setData(index, row['Especialidad'])
             index = self.model.index(r, 4, QtCore.QModelIndex())
             self.model.setData(index, Controller.obtenerNCitas(fk_rut_medico))
             r = r + 1
         self.table.setModel(self.model)
 def registraMedico(self):
     """
     Recoje todos los datos ingresados en la interfaz para pasarselos al
     controller. Donde este los revisara para luego agregarlos a la base de
     datos.
     Si existiese error en el ingreso de los datos mostrara un mensaje de
     error.
     """
     rut = self.ui.ledit_rut.text()
     nombres = self.ui.ledit_nombres.text()
     apellidos = self.ui.ledit_apellidos.text()
     especialidad = self.ui.ledit_especialidad.text()
     if(rut == "" or nombres == "" or apellidos == "" or especialidad == ""):
         mensaje = "Faltan Campos de Informacion"
         errorQMessageBox = QtGui.QMessageBox()
         errorQMessageBox.setWindowTitle("Error")
         errorQMessageBox.setText(mensaje)
         errorQMessageBox.exec_()
     else:
         if self.rutviejo == "":
             Controller.crearMedico(rut, nombres, apellidos,
                                  especialidad)
             self.close()
         else:
             Controller.editarMedico(self.rutviejo, rut, nombres, apellidos,
                                  especialidad)
             self.close()
Example #6
0
def main():
	pygame.init()

	# Just a couple of env variables.
	size = width, height = 250, 250
	black = (0, 0, 0)

	screen = pygame.display.set_mode(size)
	background = pygame.Surface(screen.get_size())
	background = background.convert()
	background.fill(black)
	pygame.display.set_caption("Controller Logger")
	
	# Initial screen render.
	screen.blit(background, (0, 0))
	pygame.display.flip()

	# A little "progress" spinner. Let's me know things are running.
	spinWheel = SpinWheel()
	file = open('./Resources/Controller_Logger_Log.txt', 'a')

	s = "\n******************************\n\
Launching Controller_Logger...\n\
******************************\n\n"

	file.write(s)

	# Setting up my spinner and frame clock.
	allSprites = pygame.sprite.RenderPlain((spinWheel))
	clock = pygame.time.Clock()

	# Find and initialize all of the fancy plug-in devices.
	s = "Joystick Initiailization: " + str(pygame.joystick.get_count()) + " Joystick(s) Detected\n"
	print(s)
	file.write(s)
	for joys in range(0, pygame.joystick.get_count()):
		joy = pygame.joystick.Joystick(joys)
		joy.init()
		Controller.bio(joy, file)

	# Start the main render loop.
	progRunMessage(file)
	while 1:
		# Keeps rendering at 60 frames/second.
		clock.tick(60)

		# Main event listener.
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				return progRunDone(file)
			else:
			   EventHandler.handle(event, file)

		# Keep the spinner up-to-date.
		allSprites.update()

		# Keep the screen up-to-date.
		screen.blit(background, (0, 0))
		allSprites.draw(screen)
		pygame.display.flip()
Example #7
0
 def profilethis(self):
     print 'Test case generated. Beginning book matching'
     self.library = Library.Library()
     start = time.time()
     Controller.process_books(self.library, book_text_files=self.testdata.get_testbooks())
     runtime = time.time()-start
     #print library.print_pretty_tree()
     print 'Finished Processing {0} books in {1} seconds'.format(len(self.testdata.get_testbooks()),runtime)
Example #8
0
 def test_medium_big_error_compare(self):
     self.testdata.unpack_archive(1)
     e = zTestDataManager.ErrorMaker(error_rate=500, per_page_junk=True)
     self.testdata.make_error_dupes(number=1,errormaker=e)
     library = Library.Library()
     Controller.process_books(library, book_text_files=self.testdata.get_testbooks())
     verification = self.testdata.verify_results(library)
     self.assertAlmostEqual(1.0, zTestDataManager.TestBookManager.combine_results(verification),3)
Example #9
0
	def testController_init(self):
		Controller.CONFIG_FILE_PATH = 'tests_Controller_config.txt'
		try:
			controller = Controller()
		except:
			self.fail("Unexpected Exception!")
		self.assertIsInstance(controller, Controller)
		   #close connection for other tests
		controller.commManager.amqpConn.close()
		controller.stop()
    def ai_move(self):
        if self.player[self.ub.currentPlayer] == "Random":
            Controller.random_move(self)
        if self.player[self.ub.currentPlayer] == "Minimax":
            Controller.minimax_move(self)

        if self.player[1] != "Human" and self.player[-1] != "Human":
            self.root.after(50, self.root.update())
            self.next_move()
        else:
            self.root.after(200, self.next_move())
Example #11
0
	def testController_getConfig(self):
		Controller.CONFIG_FILE_PATH = 'tests_Controller_config.txt'
		try:
			controller = Controller()
		except:
			self.fail("Unexpected Exception!")
		self.assertIsInstance(controller.parameters['AMQP_SERVER_IP'],str)
		self.assertIsInstance(controller.parameters['AMQP_QUEUE_NAME'],str)
		self.assertIsInstance(controller.parameters['LOGGER_SQLITE_DATABASE_FILE'],str)
		   #close connection for other tests
		controller.commManager.amqpConn.close()
		controller.stop()
Example #12
0
def main():
    rospy.init_node('controller', anonymous=False)

    # Sub/Pub
    rospy.Subscriber('robot_state', RobotState, _handle_robot_state)
    rospy.Subscriber('desired_position', Pose2D, _handle_desired_position)
    pub = rospy.Publisher('vel_cmds', Twist, queue_size=10)
    pub_PIDInfo = rospy.Publisher('pidinfo', PIDInfo, queue_size=10)

    # Services
    rospy.Service('/controller/toggle', Trigger, _toggle)

    # Get the correct PID stuff
    gains = rospy.get_param('gains') # returns as a dict
    # {'x': {'P': 0, 'I': 0, 'D': 0}, ... }

    # initialize the controller
    Controller.init(gains)

    rate = rospy.Rate(int(1/_ctrl_period))
    while not rospy.is_shutdown():

        global _ctrl_on

        if _ctrl_on:
            (vx, vy, w) = Controller.update(_ctrl_period, _xhat, _yhat, _thetahat)

            # Publish Velocity Commands
            msg = Twist()
            msg.linear.x = vx
            msg.linear.y = vy
            msg.angular.z = w
            pub.publish(msg)

            # Publish PID Info
            msg = PIDInfo()
            msg.error.x = Controller.PID_x.error_d1
            msg.error.y = Controller.PID_y.error_d1
            msg.error.theta = Controller.PID_theta.error_d1
            set_point = Controller.get_commanded_position()
            msg.desired.x = set_point[0]
            msg.desired.y = set_point[1]
            msg.desired.theta = set_point[2]
            msg.actual.x = _xhat
            msg.actual.y = _yhat
            msg.actual.theta = _thetahat
            pub_PIDInfo.publish(msg)


        rate.sleep()

    # spin() simply keeps python from exiting until this node is stopped
    rospy.spin()
 def eliminar(self):
     index = self.ui.tblview_pacientes.currentIndex()  # obtiene la fila
                                                     #seleccionada
     if index.row() == -1:
         mensaje = "Seleccione un Paciente para borrar"
         errorQMessageBox = QtGui.QMessageBox()
         errorQMessageBox.setWindowTitle("Error")
         errorQMessageBox.setText(mensaje)
         errorQMessageBox.exec_()
     else:
         model = self.ui.tblview_pacientes.model()
         rut = model.index(index.row(), 0, QtCore.QModelIndex()).data()
         Controller.eliminarPaciente(rut)
Example #14
0
def _handle_robot_state(msg):
    global _xhat, _yhat, _thetahat, _initializing, _ctrl_on
    _xhat = msg.xhat
    _yhat = msg.yhat
    _thetahat = msg.thetahat

    if _initializing:
        _initializing = False
        _ctrl_on = True

        x = rospy.get_param('x_init')
        y = rospy.get_param('y_init')
        theta = rospy.get_param('theta_init')

        Controller.set_commanded_position(x, y, theta)
Example #15
0
 def setController( self, controller ):
     if not controller:
         controller = Controller.instance()
     self._addressListModel.setAddressList( controller.reviewList())
     controller.reviewSelected.connect( self.addressSelected )
     self.uReviewEditor.setController( controller )
     self._controller = controller
Example #16
0
def _handle_ctrl_timer():
    global _set_speed
    global _velocities
    if _ctrl_on:
        _velocities = Controller.update(_ctrl_timer_period, _xhat, _yhat, _thetahat)
        #print("Vel: {}\r".format(_velocities))
        _set_speed = True
Example #17
0
def fileservice():
    inputdatetime = datetime.datetime.now().time().isoformat()
    absfile = "./Data/" + str(inputdatetime).replace(":", "").replace(".", "") + ".wav"

    soundata = request.data
    soundata = base64.b64decode(soundata[soundata.index(",")+1:])

    with open(absfile, "wb") as f:
        f.write(soundata)
    f.close()
    resultData = Controller.main(absfile,False)
    print resultData

    emotion = "You are feeling "
    i=0
    for key in resultData.keys():
        if key != "data":
            if ((resultData[key]==1.0)) :
               if i < len(resultData.keys())-1:
                    emotion= emotion+key+" "
               else:
                    emotion = emotion+"OR "+key+"."
        i=i+1;
    finalData ={}
    finalData["input"] = resultData["data"]
    finalData["result"] = emotion
    resp = make_response(json.dumps(finalData))
    resp.headers['Content-Type'] = "application/json"
    resp.headers['Access-Control-Allow-Origin'] = "*"
    return resp
Example #18
0
def webservice():
    inputdatetime = datetime.datetime.now().time().isoformat()
    absfile = "./Data/"+str(inputdatetime).replace(":","").replace(".","")+".wav"

    datarequest = json.loads(request.data)["data"]
    data= json.loads(datarequest)
    samplerate = json.loads(request.data)["samplerate"]

    ##sc.write(absfile, rate=samplerate,data=np.asarray(data, dtype=np.float32))
    filecontents = convert_float32_wav_file(data,samplerate)

    with open(absfile,"wb") as f:
        for data in filecontents:
            f.write(data)
    f.close()
    resultData = Controller.main(absfile,False)
    print resultData

    emotion = "You are feeling "
    i = 0
    for key in resultData.keys():
        if key != "data":
            if ((resultData[key] == 1.0)):
                if i < len(resultData.keys()) - 1:
                    emotion = emotion + key + " "
                else:
                    emotion = emotion + "OR " + key + "."
        i = i + 1;
    finalData = {}
    finalData["input"] = resultData["data"]
    finalData["result"] = emotion
    resp = make_response(json.dumps(finalData))
    resp.headers['Content-Type'] = "application/json"
    resp.headers['Access-Control-Allow-Origin'] = "*"
    return resp
Example #19
0
def main(argc,argv):
    # inicializar subsistemas
    # son las cosas minimas necesarias para crear la ventana
    c = Controller()
    v = View((WIDTH,HEIGHT),(90.0, 0.1, 100.0))
    # m = Model(Triangle((5,5,-15),(-5,-5,-15),(5,-5,-15)))
    m = Model(Cube((-5,-5,-5),(5,5,5)))

    # configurar la ventana
    v.init_GL((0.0, 0.5, 0.5, 1.0))
    # Creamos el Shader
    shader_program = Shader("basic_shader")
    shader_program.compile()

    # Configuramos las ubicaciones de los uniformes
    shader_program.uniform_location = {
        "lightPos": glGetUniformLocation(shader_program.program, "lightPos"),
        "lightCol": glGetUniformLocation(shader_program.program, "lightCol")
    }
    # Configuramos las ubicaciones de los atributos
    shader_program.bindAttributeLocation({
        "position": 0,
        "color": 1,
        "normal": 2
    })

    # Le entregamos los shaders a la vista para que los use
    v.useShader(shader_program)

    # Le entregamos el modelo a la vista
    v.model = m

    run = True
    while run:
        # actualizar subsistemas
        dt = c.update()
        m.update(dt)
        v.update(dt)

        run = c.check_close()

    shader_program.delete()

    # cerrar subsistemas
    c.close()
    m.close()
    v.close()
Example #20
0
def Print_entry():
  global result
  print var.get().split()[2][1:-2]
  stubpara = var.get().split()[2][1:-2]
  retval = Controller.main(var.get().split()[2][1:-2])
  print('@@@@@@@@@@@@@@@')
  print(retval)
  resultWindow(retval)
Example #21
0
class Game:

	def __init__(self, size, frame_rate=60):

		
		self.size=size
		self.frame_rate = frame_rate

		pygame.init()
		self.surface = pygame.display.set_mode(self.size)
		
		self.running = False

		self.clock = pygame.time.Clock()

		self.view = View(frame_rate=frame_rate)
		self.model = Model(view=self.view, size=self.size)
		self.controller = Controller(self.model)

		self.model.addAgent('AI')

	def play(self):
		self.running = True
		self.run()

	def pause(self):
		self.running = False

	def run(self):


		# TODO: modify play/pause/run interaction to easily 
		#    be able to play/pause the game

		while self.running:

			self.controller.getMouseInput()
			
			self.model.step()
			
			self.view.draw(self.surface, self.model)
			
			self.clock.tick(self.view.frame_rate)
			
			pygame.display.flip()
Example #22
0
class Application:

    def __init__(self):
        # setup pygame
        pygame.init()

        self.running_flag = False
        self.player_count = 1

        self.model = Model(PLAYER_COUNT = self.player_count)
        self.view = View(MODEL = self.model, SCREEN_SIZE = Vec2(500,500))
        self.controller = Controller(self.model, self.view)
        self.fpsTime = pygame.time.Clock()


    def run(self):
        self.running_flag = True
        while self.running_flag:
            self.controller.run(self.fpsTime)
Example #23
0
 def setController(self, controller):
     if not controller:
         controller = Controller.instance()
     if controller == self._controller:
         return
     if self._controller:
         self._controller.jobLoading.disconnect(self.showMessage)
     self._controller = controller
     self._controller.jobLoading.connect(self.showMessage)
     self.uJobSummaryTab.setController(self._controller)
     self.uAddressesTab.setController(self._controller)
Example #24
0
 def setController( self, controller ):
     if not controller:
         controller = Controller.instance()
     if controller == self._controller:
         return
     if self._controller:
         self._controller.jobLoaded.disconnect( self.loadJob )
         self._controller.jobUpdated.disconnect( self.loadJob )
     self._controller = controller
     self._controller.jobLoaded.connect( self.loadJob )
     self._controller.jobUpdated.connect( self.loadJob )
Example #25
0
	def testController_on_msg_recv(self):
		Controller.CONFIG_FILE_PATH = 'tests_Controller_config.txt'
		controller = Controller()

		data = {'agentHostName':'test_on_msg_recv_HostName',
				'agentHostIp':'test_on_msg_recv_HostIp',
				'agentHostTime':'test_on_msg_recv_HostTime',
				'agentType':'test_on_msg_recv_AgentType',
				'agentHostData':'test_on_msg_recv_HostData'}
		js = json.dumps(data)
		try:
			controller.on_msg_recv(None,None,None,js)
		except:
			self.fail("Unexpected Exception!")
		controller.logManager.session.commit()
		logs = controller.logManager.session.query(Log).order_by(Log.id).all()
		self.assertTrue('test_on_msg_recv_HostName' == logs[-1].agentHostName)
		   #close connection for other tests
		controller.commManager.amqpConn.close()
		controller.stop()
 def setController( self, controller ):
     """  
     Access and assign the single instance of the Controller 
     
     @param controller: instance of the plugins controller
     @type  controller: AimsUI.AimsClient.Gui.Controller
     """
     
     import Controller
     if not controller:
         controller = Controller.instance()
     self._controller = controller
 def setController( self, controller ):
     """
     Assign the controller to the QueueWditorWidget
     
     @param controller: controller Instance      
     @type  AimsUI.AimsClient.Gui.Controller() Instance
     """
     
     import Controller
     if not controller:
         controller = Controller.instance()
     self._controller = controller
Example #28
0
def main():
	view = View()
	controller = Controller()
	controller.view = view

	chunk_shader = shaderFromFile("shaders/chunk.vert","shaders/chunk.frag")
	chunk_shader.compile()
	chunk_shader.use()
	chunk_shader.setAttribLocation(0,"position")
	chunk_shader.setAttribLocation(1,"color")
	chunk_shader.setAttribLocation(2,"normal")

	view.shader = chunk_shader

	view.reshape()

	chunk = SuperChunk()
	loadHGT(chunk)

	controller.model = view.model = chunk
	view.camera = Camera(25,15,25)

	while controller.running:
		controller.update()
		view.update()

	controller.close()
Example #29
0
    def __init__(self, ip):
        self.ip = ip

        self._asn = Controller.getAS(self.ip)
        self._org = Controller.getLocation(self.ip)
    
        for k, v in zip( ('_locid',
                          'country',
                          'region',
                          'city',
                          'postalCode',
                          'latitude',
                          'longitude',
                          'metroCode',
                          'areaCode'),
                          self._org ):

            self.__setattr__(k, v)

        if self._asn.startswith('AS'):
            self.asnum, self.orgname = self._asn.split(' ', 1)
        else:
            self.asnum, self.orgname = ('', '')
Example #30
0
def fileservice():
    inputdatetime = datetime.datetime.now().time().isoformat()
    absfile = "./Data/" + str(inputdatetime).replace(":", "").replace(".", "") + ".wav"
    soundata = request.data
    soundata = base64.b64decode(soundata[soundata.index(",")+1:])

    with open(absfile, "wb") as f:
        f.write(soundata)
    f.close()
    resultData = Controller.main(absfile,False)
    finalData = getSentiData(resultData)
    resp = make_response(json.dumps({"response":finalData}))
    print resp
    resp.headers['Content-Type'] = "application/json"
    return resp
Example #31
0
 def post(self):
     post_data = dict(urlparse.parse_qsl(self.request.body))
     c = Controller.Controller()
     self.write(
         c.test_lab(post_data['lab_id'], post_data['lab_src_url'],
                    post_data.get('version', None)))
Example #32
0
def SingleTest():
    # Set goals to go to
    GOALS = [(1, 1, 2), (1, -1, 4), (-1, -1, 2), (-1, 1, 4)]
    YAWS = [0, 3.14, -1.54, 1.54]
    # Define the quadcopters
    QUADCOPTER = {
        'q1': {
            'position': [2, 2, 0],
            'orientation': [0, 0, 0],
            'L': 0.3,
            'r': 0.1,
            'prop_size': [10, 4.5],
            'weight': 1.2
        }
    }
    # Controller parameters
    CONTROLLER_PARAMETERS = {
        'Motor_limits': [4000, 9000],
        'Tilt_limits': [-10, 10],
        'Yaw_Control_Limits': [-900, 900],
        'Z_XY_offset': 500,
        'Linear_PID': {
            'P': [300, 300, 7000],
            'I': [0.04, 0.04, 4.5],
            'D': [450, 450, 5000]
        },
        'Linear_To_Angular_Scaler': [1, 1, 0],
        'Yaw_Rate_Scaler': 0.18,
        'Angular_PID': {
            'P': [22000, 22000, 1500],
            'I': [0, 0, 1.2],
            'D': [12000, 12000, 0]
        },
    }

    # Catch Ctrl+C to stop threads
    signal.signal(signal.SIGINT, signal_handler)
    # Make objects for quadcopter, gui and controller
    quad = copter.Quadcopter(QUADCOPTER)
    gui_object = GUI.GUIQuad(quads=QUADCOPTER)
    ctrl = Controller.Controller_Point2Point(quad.get_state,
                                             quad.get_time,
                                             quad.set_motor_speeds,
                                             params=CONTROLLER_PARAMETERS,
                                             quad_identifier='q1')
    # Start the threads
    quad.start_thread(dt=QUAD_DYNAMICS_UPDATE, time_scaling=TIME_SCALING)
    ctrl.start_thread(update_rate=CONTROLLER_DYNAMICS_UPDATE,
                      time_scaling=TIME_SCALING)
    # Update the GUI while switching between destination poitions
    while (run == True):
        for goal, y in zip(GOALS, YAWS):
            ctrl.update_target(goal)
            ctrl.update_yaw_target(y)
            for i in range(300):
                gui_object.quads['q1']['position'] = quad.get_position('q1')
                gui_object.quads['q1']['orientation'] = quad.get_orientation(
                    'q1')
                gui_object.update()
    quad.stop_thread()
    ctrl.stop_thread()
Example #33
0
                    print

                if objective['objective_id'] not in level_objectives:
                    print "\t" + objective['name'],
                    level_objectives.append(objective['objective_id'])

            print


if __name__ == "__main__":
    import Model_SQLite
    #	model = Model_SQLite.Model(":memory:")
    model = Model_SQLite.Model("priorities.sqlite")

    import Controller
    controller = Controller.Controller(model)

    interface = Test(controller)
    #	interface.InsertTestData()
    #	interface.InsertTestData2()
    interface.ShowTestResults()

#	import Tkinter
#	from Tkconstants import *
#	tk = Tkinter.Tk()
#	frame = Tkinter.Frame(tk, relief=RIDGE, borderwidth=2)
#	frame.pack(fill=BOTH,expand=1)
#	label = Tkinter.Label(frame, text="Hello, World")
#	label.pack(fill=X, expand=1)
#	button = Tkinter.Button(frame,text="Exit",command=tk.destroy)
#	button.pack(side=BOTTOM)
Example #34
0
def main():

    channel = 'VICON_sawbot'
    r_wheel = 125  #mm
    dt = 1.0 / 5.0
    dt = 0.15
    '''Q should be 1/distance deviation ^2
    R should be 1/ speed deviation^2
    '''

    dist = 20.0  #mm
    ang = 0.25  # radians

    Q = np.diag([1.0 / (dist * dist), 1.0 / (dist * dist), 1.0 / (ang * ang)])

    R = np.eye(2)
    command_variation = 20.0
    R = np.diag([
        1 / (command_variation * command_variation),
        1 / (command_variation * command_variation)
    ])

    maxUc = 20

    r_circle = 300  #mm
    speed = 25  #64
    Xks = circle(r_circle, dt, speed)
    #Xks = straight(1000,1.0/5.0,speed)
    #Xks = loadTraj('../Media/card2-dist5.20-rcut130.00-trajs-0.npy')
    Xks, Uks = TrajToUko(Xks, r_wheel, dt)
    #Xks = Xks[:50]

    lock = Lock()

    start = np.matrix(Xks[0][0:3]).transpose()

    print start

    speedup = 100.0

    sh = StateHolder(lock, start)
    timelock = TickTock()

    runNum = 8

    #Setup the logging
    LogQ = Queue(0)
    Log_stopper = Event()
    logname = "Run%i.csv" % runNum
    Log = Logger(logname, Log_stopper, LogQ)

    LogQ2 = Queue(0)
    Log_stopper2 = Event()
    logname2 = "time%i.csv" % runNum
    Log2 = Logger(logname2, Log_stopper2, LogQ2)

    LogQ3 = Queue(0)
    Log_stopper3 = Event()
    logname3 = "cmds%i.csv" % runNum
    Log3 = Logger(logname3, Log_stopper3, LogQ3)

    #setup the controller
    T = 5  #horizon
    RunControl = True
    CC_stopper = Event()
    CRC = KillerSim(LogQ3)  # CRC_Sim()
    CC = Controller(CC_stopper, CRC, sh, Xks, Uks, r_wheel, dt, Q, R, T, maxUc,
                    LogQ, not RunControl, speedup, timelock, LogQ2)

    VSim_stopper = Event()
    #setup the simulator
    VSim = Simulator(VSim_stopper, CRC, sh, Xks, r_wheel, dt, Q, speedup,
                     timelock)
    CRC.start()
    VSim.start()
    #time.sleep(0.005)
    CC.start()
    Log.start()
    Log2.start()
    Log3.start()

    CC.join()
    CRC.stop()
    VSim_stopper.set()
    Log_stopper.set()
    Log_stopper2.set()
    Log_stopper3.set()
    VSim.join()
    Log.join()
    Log2.join()
    Log3.join()
    print 'Done'
    time.sleep(0.05)
    plotCSVRun(logname)
    return 0
Example #35
0
import os, sys

sys.path.insert(0, Comm)
sys.path.insert(1, Common)
sys.path.insert(2, Controller)

import SystemLoader
import Controller

if __name__ == "__main__":

    print("[SERVER] - Starting the ringbell server...")

    # Load preferences
    sl = SystemLoader.SystemLoader()
    pwds = sl.loadPwd()
    if len(pwds) != 0:
        status = "OK"
    else:
        status = "NOK"

    # start Controller
    ct = Controller.Controller(pwds)
    print("[SERVER] - Status is [" + status + "]")

    # loop until it never ends !
    ct.run_the_magic(pwds)
Example #36
0
from View import *
from Player import *
from Torus import *
from Map import *
from Model import *
from Controller import *

view = View()
controller = Controller(view)
view.setController(controller)
model = Model(view, controller)
view.setModel(model)
controller.setModel(model)

view.run()

#player=Player("Quentin",10,4,2)
Example #37
0
def main():
    try:
        global args
        global canvas
        global settings

        controller = None
        filemerge = None
        view = None
        model = None

        settings.initialize_prefs(canvas.max_colors())

        # Only POSIX systems are supported at this point
        fileops = FileOpsPOSIX.FileOpsPOSIX()

        if len(args) == 2:
            left = args[0]
            right = args[1]

            left = os.path.realpath(left)
            right = os.path.realpath(right)

            # Instantiate the classes and link them together.
            model = Model2.Model(fileops, left, right)
            view = View2.View(canvas, model, settings)
        else:
            # len(args) == 3
            left = args[0]
            middle = args[1]
            right = args[2]

            left = os.path.realpath(left)
            middle = os.path.realpath(middle)
            right = os.path.realpath(right)

            # Instantiate the classes and link them together.
            model = Model3.Model(fileops, left, middle, right)
            view = View3.View(canvas, model, settings)

        requested_filemerge = settings.get_value('file_merge_program')
        # print('file_merge_program:', requested_filemerge)
        if requested_filemerge == 'vim':
            filemerge = FileMergeVim.FileMergeVim()
        else:
            filemerge = FileMergeEmacs.FileMergeEmacs()
        controller = Controller.Controller(model, view, canvas, filemerge)

        # Start the model. It will enumerate and then start comparing.
        model.start_enumerate()

        # Main event loop
        while not controller.need_to_quit:
            if canvas.need_to_resize:
                view.resize()
            model.render_again = False
            view.render()
            if ((model.state() == Model2.STATE_NORMAL
                 or model.state() == Model3.STATE_NORMAL)
                    and not model.render_again and not canvas.need_to_resize):
                input = canvas.get_input(0)  # wait indefinitely
            else:
                input = canvas.get_input(1)  # timeout in 1/10 second
            controller.process_input(input)

    finally:
        # print("quitting")
        if controller is not None:
            controller.destroy()
        if filemerge is not None:
            filemerge.destroy()
        if view is not None:
            view.destroy()
        if model is not None:
            model.destroy()
Example #38
0
from Controller import *
import sys

b = Model_Handler(sys.argv[1])
Controller(b).Go()
Example #39
0
def look_around(vrep, clientID, kinectd_h, robot_Handle, robot_LeftMotorHandle,
                robot_RightMotorHandle):
    #function to gather obstacle info
    denied_actions = []
    flag_denied = False
    flag_exist = False

    #Make robot face x axis before all data collection
    state = Controller.localise(vrep, clientID, robot_Handle)
    Controller.orient_robot(state[2], 0.0)
    #Get start pos
    res, start_robot_Position = vrep.simxGetObjectPosition(
        clientID, robot_Handle, -1, vrep.simx_opmode_buffer)
    res, start_robot_Orientation = vrep.simxGetObjectOrientation(
        clientID, robot_Handle, -1, vrep.simx_opmode_buffer)

    print('Looking around at', start_robot_Position[0:2])

    #Cycle through to see which actions are possible and which not
    for i, action in enumerate(params.delta):

        print('action', action)
        #get robot position
        state = Controller.localise(vrep, clientID, robot_Handle)

        #Get action
        new = Planner.expander(state[0:2], action)  #get new node

        #Set params:
        flag_go = True
        flag_prev = True
        counter = 0

        while flag_go:
            [V, W] = Controller.gtg(state, new)
            Controller.robot_setvel(V, W, vrep, clientID,
                                    robot_LeftMotorHandle,
                                    robot_RightMotorHandle)
            state = Controller.localise(vrep, clientID, robot_Handle)
            #print('state', state)

            #Get the sensor info
            res, res1, buffer = vrep.simxGetVisionSensorDepthBuffer(
                clientID, kinectd_h, vrep.simx_opmode_oneshot_wait)
            buffer = np.reshape(buffer, (48, 64))
            buffer = buffer * 255
            buffer = buffer.astype(int)
            buffer = cv2.flip(buffer, 0)
            res, robot_Orientation = vrep.simxGetObjectOrientation(
                clientID, robot_Handle, -1, vrep.simx_opmode_buffer)
            alpha = np.rad2deg(robot_Orientation[0])
            alpha = (alpha + 40.0) / 80.0
            beta = np.rad2deg(robot_Orientation[1])
            beta = (beta + 40.0) / 80.0
            temp = CNN.model.predict([
                buffer[None, ..., None],
                np.array(float(alpha))[None, ...],
                np.array(float(beta))[None, ...]
            ])
            #print(temp[0][0])
            if temp[0][0] <= 0.2:
                if flag_prev == False:
                    counter += 1
                flag_prev = False
            else:
                counter = 0
                flag_prev = True

            #Checks
            if counter > 5 or Planner.at_goal(state[0:2], new):
                flag_go = False
                if Planner.at_goal(state[0:2], new):
                    print('reached goal')
                else:
                    print('detected obs')

        #Stop robot, stop simulation, reset robot loc and start simulation
        Controller.robot_stop(vrep, clientID, robot_LeftMotorHandle,
                              robot_RightMotorHandle)
        vrep.simxStopSimulation(clientID, vrep.simx_opmode_oneshot)
        if counter > 5:
            cv2.namedWindow('depth', cv2.WINDOW_NORMAL)
            cv2.imshow('depth', buffer / 255.0)
            cv2.waitKey(200)
        print('resetting robot to', start_robot_Position)
        vrep.simxSetObjectPosition(clientID, robot_Handle, -1,
                                   start_robot_Position,
                                   vrep.simx_opmode_oneshot)
        vrep.simxSetObjectOrientation(clientID, robot_Handle, -1,
                                      start_robot_Orientation,
                                      vrep.simx_opmode_oneshot)
        time.sleep(3.0)  #So that the motion is completed
        vrep.simxStartSimulation(clientID, vrep.simx_opmode_oneshot)
        cv2.destroyAllWindows()

        if counter > 5:
            flag_denied = True
            denied_actions.append(i)

    #Get the grid based location as seen by the planner
    #Translate to planner coordinates
    start_loc = [0, 0]
    start_loc[0] = start_robot_Position[0] * 1000.0
    start_loc[1] = start_robot_Position[1] * 1000.0
    start_loc = Planner.translator(start_loc)

    #If atleast one denied action
    if flag_denied:
        #If already existing then just update
        for node in params.obs_list:
            if [node.x, node.y] == start_loc:
                node.obs_actionlist = node.obs_actionlist + denied_actions
                node.obs_actionlist = list(set(node.obs_actionlist))
                flag_exist = True
                break

        #If not existing then just append
        if flag_exist == False:
            temp = params.obsinfo(start_loc, denied_actions)
            params.obs_list.append(temp)
Example #40
0
#Position the robot
vrep.simxSetObjectPosition(clientID, robot_Handle, -1, [0.0, 0.0, 0.0],
                           vrep.simx_opmode_oneshot)
vrep.simxSetObjectOrientation(clientID, robot_Handle, -1, [0.0, 0.0, 0.0],
                              vrep.simx_opmode_oneshot)
time.sleep(4)  #So that the motion is completed

#Start the simulation
res = vrep.simxStartSimulation(clientID, vrep.simx_opmode_oneshot)
if res == vrep.simx_return_ok:
    print("---!!! Started Simulation !!! ---")
    time.sleep(4)  #So that the robot stabilizes

#Extract current location of the robot
state = Controller.localise(vrep, clientID, robot_Handle)

#Define main gaol
main_goal = [params.x_g, params.y_g]

#Build the planning boundaries
Planner.boundary_builder()

#start the run
while Planner.at_goal(state[0:2], main_goal) == False:

    #Gather information and store obstacle info in global thingy
    look_around(vrep, clientID, kinectd_h, robot_Handle, robot_LeftMotorHandle,
                robot_RightMotorHandle)

    #Get the new local goal from the plan
Example #41
0
    elif log_level == "ERROR":
        logging.error("%d (%d, %d)-%d-%.2f %s %s" % (car_id,
                                                     car_state['location'][0],
                                                     car_state['location'][1],
                                                     car_state['battery'],
                                                     car_state['mileage'],
                                                     car_event,
                                                     information))
    else:
        return


if __name__ == '__main__':
    setup_logging(default_path="logging.yaml")
    logger("INFO", "SLEEP", "Initialize car...")
    car = Controller.Controller(gyro_address=0x68, gpio_trigger=20, gpio_echo=21)
    logger("INFO", "WAIT", "Initialize successfully.")

    current_location = car.getLoc()
    if orientation == 'forward':
        current_location = ravine_length-current_location-car_length
    else:
        current_location = current_location+car_length

    try:
        # 将小车姿态设为初始状态
        car.forward(plants[0]-current_location, 100, end_time=0.2)
        if plants_side == 'right':
            car.turnRight(90, 60, end_time=0.2)
        else:
            car.turnLeft(90, 60, end_time=0.2)
Example #42
0
# -*- coding: utf-8 -*-

from Controller import *

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    myapp = Controller()
    myapp.show()
    sys.exit(app.exec_())
    pass
Example #43
0
from View import *
from Controller import *
from PyQt5.QtWidgets import QApplication
import sys

if __name__ == '__main__':
    app = QApplication(sys.argv)
    a = View()
    b = Controller(a)
    a.setControl(b)
    a.show()
    sys.exit(app.exec_())
Example #44
0

from Interpreter import *
from Controller import *
from TheView.ConsoleView import *

if __name__ == "__main__":
    ctrl = Controller(ConsoleView(), Interpreter())
    ctrl.go()
Example #45
0
"""
Created on May 11, 2019

@author: Dave
"""
import Controller
import CurrentData
import Logic
from MapTest import MapTest
import MqttConnection
from MainGui import MainGui
from Decorator import *


@debug_only
def debug_print():
    print("==========DEBUG MODE==========")


if __name__ == '__main__':
    debug_print()
    CurrentData.CurrentData()
    connection = MqttConnection.MqttConnection()
    logic = Logic.Logic(connection)
    occupancy_map = MapTest()
    controller = Controller.Controller(connection, logic, occupancy_map)
    gui = MainGui(controller, occupancy_map)
Example #46
0
def drive_example(c, num):
    global accumulateSpeedTime, accumulateStrTime, targetSpeed, targetStrE, timeIntervalSpeed, timeIntervalStr
    global Vl
    global trackPoslast
    S, R = c.S.d, c.R.d

    if (num == 0):
        # The first car controller
        # random the target speed and the target position of the first car
        if (S['curLapTime'] < .20):
            accumulateSpeedTime = 0.0
            accumulateStrTime = 0.0

            #Random generation of the leader car speed
            targetSpeed = random.gauss(70.0, 30.0)
            speedMin = 0.0
            speedMax = 70.0
            targetSpeed = min(speedMax, targetSpeed)
            targetSpeed = max(speedMin, targetSpeed)

            #Random generation of the leader car track position
            targetStrE = random.gauss(0.0, 0.5)
            strMin = -0.7
            strMax = 0.7
            targetStrE = min(strMax, targetStrE)
            targetStrE = max(strMin, targetStrE)

            #Random time interval generator within the current lap
            timeIntervalSpeed = float(random.randint(10, 25))
            timeIntervalStr = float(random.randint(10, 25))
            #print('New Lap is Starting....', temp_speed, temp_strE)

        #Random generation of the leader car speed
        if (S['curLapTime'] > accumulateSpeedTime + timeIntervalSpeed):
            accumulateSpeedTime += timeIntervalSpeed
            timeIntervalSpeed = float(random.randint(10, 25))
            targetSpeed = random.gauss(70.0, 30.0)
            speedMin = 0.0
            speedMax = 70.0
            targetSpeed = min(speedMax, targetSpeed)
            targetSpeed = max(speedMin, targetSpeed)
            #print('update the target speed to', temp_speed)

        #Random generation of the leader car track position
        if (S['curLapTime'] > accumulateStrTime + timeIntervalStr):
            accumulateStrTime += timeIntervalStr
            timeIntervalStr = float(random.randint(10, 25))
            targetStrE = random.gauss(0.0, 0.5)
            strMin = -0.9
            strMax = 0.9
            targetStrE = min(strMax, targetStrE)
            targetStrE = max(strMin, targetStrE)

        #Acctuators of the first car
        R['steer'] = Controller.steeringControl(S, targetStrE)
        R['accel'] = Controller.speedControl(S, R, targetSpeed)
        R['gear'] = Controller.automaticGear(S)

        Vl = S[
            'speedX']  # transfer the leader car speed to the second car controller

    if (num == 1):
        # The second car controller
        #R['steer'] = Controller.ACCSteeringController(S)
        [acc, brake, Xr] = Controller.ACCVelocityController(Vl, S)
        #R['accel'] = acc
        #R['brake'] = brake

        # nn controller
        trackPos = Controller.trackPosCalc(S['track'])
        distance = min(S['opponents'])
        row = [
            S['speedX'], S['speedY'], trackPos, trackPoslast, distance, Vl, Xr
        ]
        row = (row - dataNormalization['X_mean']) / dataNormalization['X_std']
        trackPoslast = trackPos
        Y = Controller.nncontroller(row, model)
        #Y = Y * dataNormalization['Y_std']
        R['steer'] = Y[0]
        R['accel'] = Y[1]
        R['brake'] = Y[2]
        R['gear'] = Controller.automaticGear(S)
window.connect("delete-event", Gtk.main_quit)
window.set_default_size(1500, 1500)
window.set_title('TestDrawChronograph')

#using matplotlib creation of canvas
fig = Figure(figsize=(12, 12), dpi=80)
ax = fig.add_subplot(111)

canvas = FigureCanvas(fig)
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
window.add(box)
box.pack_start(canvas, True, True, 0)

#init controller
model = md.Model()
controller = ct.Controller(model)
A = D.DrawChronoMap(ax, controller)

controller.create_new_graph("GraphChronomap")

#create node in controller
nodeA = A.controller.create_evenement("outdated research material",
                                      "01-01-2016 00:00:00",
                                      "01-02-2016 00:00:00", 1,
                                      "BLAH BLAH BLAH", "http://")
nodeB = A.controller.create_evenement("Projected tsunami frequency too low",
                                      "08-08-2016 00:00:00",
                                      "09-10-2016 00:00:00", 1, "OK",
                                      "http://")
nodeC = A.controller.create_evenement("EV C", "08-07-2016 00:00:00",
                                      "09-08-2016 00:00:00", 1, "HOOOOO",
Example #48
0
def tcplink(sock, addr, player_id, game):
    # 将plyaer_id 发给玩家
    conn = Controller()
    data = json.dumps({'player_id' : player_id})
    sock.send(data.encode('utf-8'))
    my_turn = False
    while True:
        data = sock.recv(1024)
        if game.get_current_player() == player_id and not my_turn:
            data = json.dumps({'mess':'begin'})
            sock.send(data.encode('utf-8'))
            my_turn = True
            continue
        if not my_turn:
            time.sleep(1)
            data = json.dumps({'mess':'not your turn'})
            sock.send(data.encode('utf-8'))
            continue

        mess = json.lodas(data)
        replay = {}
        infoclass = mess['InfoClass']
        # 结束当前回合
        if infoclass == 'end':
            print('end roud')
            game.update_action_stack()
            game.update_round()
            my_turn = False
            data = json.dumps({'mess':"end"})
            sock.send(data.encode('utf-8'))
            continue
        # 行动
        if infoclass == 'Action':
            player_id = game.get_current_player()
            action = mess['action']
            chess_id = mess['chess_id']
            if action == 'move':
                x = mess['x']
                y = mess['y']
                pos = {'x':x, 'y':y}
                flag = conn.move_chess(game, chess_id, player_id, pos)

            if action == 'hide':
                flag = conn.hidden_action(game, player_id, chess_id )

            if action == 'conquer':
                village_id = mess['village_id']
                flag = conn.conquer_village(game, player_id, chess_id, village_id)

            if action == 'get_on_car':
                car_id = mess['car_id']
                flag = conn.get_on_car(game,player_id, chess_id, car_id)

            if action == 'get_off_car':
                car_id = mess['car_id']
                flag = conn.get_on_car(game,player_id, chess_id, car_id)

            if action == 'fire':
                target_id = mess['target_id']
                flag = conn.fire_action(game, player_id, chess_id, target_id)
        if flag :
            replay['mess'] = 'Sucess'
        else :
            replay['mess'] = 'Fail'
        data = json.dumps(replay)
        sock.send(data.encode('utf-8'))
    sock.close()
    print ('Connection from %s:%s closed.' % addr)
Example #49
0
 def Follow_path(self, path):
     Controller.followpath(path, self.objectPicked)
     self.Get_postiton()
Example #50
0
 def get_walk_value(self):
     con.x = self.lcd1.value()
     con.y = self.lcd2.value()
     con.r = self.lcd3.value()
     con.walk_motion(con.x, con.y, con.r)
Example #51
0
from Controller import *
from Fuzificare import *

fuz = Fuzificare()
ctrl = Controller(fuz, 'temperature.in', 'capacity.in', 'power.in',
                  'functionality.in')
r = ctrl.run(100, 2)
print("Defuzificare:", ctrl.getDefuzificare())
print("Fuzificare capacitate:", fuz.fuzificareCapacitate(3, (0, 5)))
print(r)
Example #52
0
 def Click_Record_Clicked(self):
     print("Start Recording with Button Mode")
     if (mD.check_record_name(self.inputName1.toPlainText()) == True):
         con.click_record(self.inputName1.toPlainText())
     self.set_animationList()
Example #53
0
import Controller
from LedCube import LedCube
from visual_common import create_display

# # # # MAIN means start the application --> HERE <-- # # # #

# initialize led_cube and controller
led_cube = LedCube()
Controller.start(led_cube)

# vpython bs
while True:
    # caps the vpython framerate to 60fps
    create_display.rate(60)
Example #54
0
import Menu
import Controller
import sys

while True:
    menu = Menu.menuPrincipal()
    #
    # obter código da opção = menu["opcao"]
    # obter descrição da opção = menu["menu"][menu["opcao"]]
    #
    codOpcao = menu["opcao"]
    descOpcao = menu["menu"][codOpcao]
    #
    if (descOpcao.lower() == "lançamento"):
        Controller.lancamento()

    elif (descOpcao.lower() == "consultar saldo"):
        Controller.consultarSaldo()

    elif (descOpcao.lower() == "consultar extrato"):
        Controller.consultarExtrato()

    elif (descOpcao.lower() == "sair"):
        sys.exit("Bye bye :)")
"""

import numpy as np
import numpy.random as rnd
import matplotlib.pyplot as plt

import GoalSelector
import GoalPredictor
import GoalMaker
import Controller
import utils.kinematics as KM

if __name__ == "__main__":

    controller = Controller.SensorimotorController()

    gs = GoalSelector.GoalSelector(
        dt=0.001,
        tau=0.08,
        alpha=0.1,
        epsilon=1.0e-10,
        eta=0.01,
        n_input=controller.pixels[0] * controller.pixels[0],
        n_goal_units=10,
        n_echo_units=100,
        n_rout_units=controller.actuator.NUMBER_OF_JOINTS * 2,
        im_decay=0.2,
        noise=.5,
        sm_temp=0.2,
        g2e_spars=0.01,
Example #56
0
def getDataDetails(filepath, app):
    if filepath:
        if re.findall(".csv$", filepath):
            app.getDatasheetChooseCombobox().config(state="disabled")
            Controller.setComboboxValue(app.getDatasheetChooseCombobox(), ("CSV文件无需选择数据表!",))
            with open(filepath, newline='') as csvfile:
                c = csv.reader(csvfile)
                for i in c:
                    Controller.setComboboxValue(app.getXChooseCombobox(), i)
                    app.getXChooseCombobox().config(state="readonly")
                    Controller.setComboboxValue(app.getYChooseCombobox(), i)
                    app.getYChooseCombobox().config(state="readonly")
                    return

        else:
            Controller.setComboboxValue(app.getDatasheetChooseCombobox(), getDatasheets(filepath))
            app.getDatasheetChooseCombobox().config(state="readonly")
            xy = getFirstLineBySheetName(filepath, app.getDatasheetChooseCombobox().get())
            Controller.setComboboxValue(app.getXChooseCombobox(), xy)
            app.getXChooseCombobox().config(state="readonly")
            Controller.setComboboxValue(app.getYChooseCombobox(), xy)
            app.getYChooseCombobox().config(state="readonly")
Example #57
0
def _handle_desired_position(msg):
    Controller.set_commanded_position(msg.x, msg.y, msg.theta)
Example #58
0
# -*- coding:utf-8 -*- 

#DATE:2017-11-30
#Description:
#	用于自动重启uap,解决portal授权时间结束后,再次连接AP,会提示为授权用户,接着自动下线,触发认证.


from Controller import *

if __name__=="__main__":
	#APMAC = ['04:18:d6:00:70:db']
	c = Controller()
	# for apmac in APMAC:
	# 	c.restart_AP(apmac)
	APMAC = c.get_AP_MAC()
	for apmac in APMAC:
		c.restart_AP(apmac)
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 26 07:45:01 2018

@author: miile7
"""

print("Importing packages...")
import sys
from PyQt5 import QtWidgets

import View.ToolWizard.ToolWizard
import View.ToolWizard.BackgroundCreationTool
import Controller

print("Preparing program...")
app = QtWidgets.QApplication.instance()
if not app or app == None:
    app = QtWidgets.QApplication(sys.argv)

controller = Controller.Controller(False)

print("Starting editing GUI...")
tools = (View.ToolWizard.BackgroundCreationTool.BackgroundCreationTool(), )

wizard = View.ToolWizard.ToolWizard.ToolWizard(controller, None, *tools)

print("Ready.")
wizard.show()

sys.exit(app.exec_())
Example #60
0
import zmq
import time
import constraints as c
import threading
from Manual_Drive import *

# In testing mode no drive commands are executed
TESTING_MODE = True

if not TESTING_MODE:
    # Import the controller
    import Controller
    # create controller entity
    controller = Controller.Controller()
    manualDrive = ManualDrive(controller.start_command, controller.forward,
                              controller.backward, controller.left,
                              controller.right, controller.stop)
    import lupa
    from lupa import LuaRuntime

# The port to which this server will listen
PORT = '5060'
# Setting up 0mq to work as socket server
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://0.0.0.0:%s" % PORT)

# Global variable storing wheter or not some one has a lock
LOCK = False
# Global variable storing whether someone has a superlock
SUPERLOCK = False