def start_round(sock, team_id): game = Game(sock, team_id) game.register() with open("log.txt", "a+") as f: f.write("success register") while True: game.receive_msg() msg_name = game.get_msg_name() if msg_name == "round": game.round_start() control = Control(team_id, game.our_tank_id, game.maps, game.data) # 操作函数 for tank_id in game.our_tank_id: control.move(tank_id, "up") control.fire(tank_id, "up", 0) control.send_msg(sock) game.round_clear() elif msg_name == "leg_start": game.leg_start() elif msg_name == MSG_NAME_LEG_END: print(game.data["msg_data"]) game.leg_clear() elif msg_name == MSG_NAME_GAME_OVER: print("Game Over ...") break
def loadPoseFile(fileName): poses = {} #should use the g.pandaPath ? -Michael reed s10 file = findCSV(fileName) if file is not None: fileLoader = open(file, "r") contents = fileLoader.read().split("\n") for line in contents[1:]: data = line.split(",") if len(data) >= 5: poseName = data[0].strip() jointName = data[1].strip() jointHpr = SHPR(float(data[2].lstrip("(")), float(data[3]), float(data[4].rstrip(")"))) if not poses.has_key(poseName): poses[poseName] = {} poses[poseName][jointName] = jointHpr fileLoader.close() result = {} for pose, dict in poses.iteritems(): result[pose] = Control(dict) return result print "File " + fileName + " not found." exit()
def start_round(sock, team_id): game = Game(sock, team_id) game.register() with open("log.txt", "a+") as f: f.write("success register") while True: game.receive_msg() msg_name = game.get_msg_name() if msg_name == "round": game.round_start() control = Control(team_id, game.our_tank_id, game.maps, game.data) strategy = Strategy(game) # 操作函数 game.set_tank_msg() try: # AI_zx.start_zx(game,control) new_start.start_5_28(game, control, strategy) except Exception as e: log.log("start:") log.log(e) control.send_msg(sock) game.round_clear() elif msg_name == "leg_start": game.leg_start() elif msg_name == MSG_NAME_LEG_END: print(game.data["msg_data"]) game.leg_clear() elif msg_name == MSG_NAME_GAME_OVER: print("Game Over ...") break
def initControl(): ''' Initialize our controller with the qube job. ''' control = Control.Control(qb.jobobj()) return control
def main(argv): parser = argparse.ArgumentParser(description='RoboRinth Robot Explorer') parser.add_argument('--host', type=str, help='host of the mqtt broker to connect', default="192.168.0.200") parser.add_argument('--port', type=int, default=1883, help='port of the mqtt broker to connect') parser.add_argument('--roboName', type=str, default="robo-01", help='Robot MQTT topic/name to connect') parser.add_argument('--clientId', type=str, default="", help='MQTT client connection id') parser.add_argument( '--log', type=str, choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"], default="INFO", help='Loglevel ') args = parser.parse_args() _initializeLogging(args.log) logger.debug("Main started") # Setup mqtt client client = MqttClient(args.host, args.port, args.clientId) client.startAsync() time.sleep(2) # Test code for MapMatcher roboName = args.roboName roboDriver = RoboDriver(roboName) client.subscribeTopics(roboName + '/notification/#') client.addMessageHandler(roboDriver.getMqttHandlerList()) roboDriver.setMqttClient(client) mapMatcher = MapMatcher() mapMatcher.registerRobotDriver(roboName, roboDriver) robots = {} robots[roboName] = Control(roboName, mapMatcher, roboDriver) robots[roboName].start() # End test code input("\n\nPress Enter to abort...\n\n") # Terminate client.stop() logger.debug("Terminate")
def __init__(self): self.tcp_flag = False self.led = Led() self.adc = ADS7830() self.servo = Servo() self.buzzer = Buzzer() self.control = Control() self.sonic = Ultrasonic() self.control.Thread_conditiona.start()
class Main: m_Download_Data = Download_Data() m_Fromat_Data = Fromat_Data() m_Control = Control() m_Save_Biodata = Save_Biodata() m_show = show()
def __init__(self, name): self.name = name # init control as it is independent of the state of planning while interacting and needed to build behaviors self.control = Control() self.planning = None self.defaultSocialProfile = SocialProfile("Default", ComposedBehavior(self.control, []), 30.0, []) self.defaultCreativityProfile = CreativityProfile("Default", 5, {}, StoryArcBehaviorType.MIRROR, 5.0, {}, StoryArcBehaviorType.MIRROR, 5.0, {}, StoryArcBehaviorType.MIRROR) self.defaultGeneralProfile = self.generateGeneralProfile("Default", Color(rgb=(0.1 ,0.1 ,0.1)), 1.0)
def __init__(self, dimension, master=None): Frame.__init__(self, master) self.master.title('Tediumrobo') self.pack() self.create_label(master) self.control = Control.Control(dimension) self.my_label = Label() self.my_label.pack() self.contents = StringVar() self.contents.set(self.control.refresh()) self.my_label["textvariable"] = self.contents
def LogicAnalyzer(): controler = Control() Infodoc.addWidget(controler) global probes probes = controler.getProbes() #Add plot Widgets to Docks probe1.addWidget(probes[0]) probe2.addWidget(probes[1]) probe3.addWidget(probes[2]) probe4.addWidget(probes[3])
def launch_game(self): """ Launch the game """ self.window = pygame.display.set_mode((300, 400)) land = ld.Land(self.window) land.background() maps = land.map() control = Control(maps[0], maps[1], self.window) if control == None: pygame.display.quit() while pygame.event.wait().type != pygame.QUIT: pass
def Main(): targetFPS = 60 pygame.init() screen = pygame.display.set_mode(View.WindowSize) #make window running = True clock = pygame.time.Clock() #keeps framerate synced try: #in case of error, close app Model.Initialize() View.Initialize(screen) while running: #main loop for event in pygame.event.get( ): #check if red X is pressed to close app if event.type == pygame.QUIT: running = False inputState = Control.Control( ) #get the current input state from controller #mainly gets key presses but can also be mouse position if necessary Model.player.controller.PlayerInput(inputState) deltaTime = clock.get_time() / 1000 Model.Model(deltaTime) #updates game logic #passes in the new input and time since last frame in seconds View.View(screen, deltaTime) #update visuals clock.tick(targetFPS) #wait for next frame except Exception as e: #close app on exception pygame.quit() raise e pygame.quit() #quit app
def __init__(self, parent, path, rvizPath, node): super(MainWidget, self).__init__(parent) self.parent = parent self.path = path self.node = node self.rvizPath = rvizPath self.btn1 = QPushButton("modal dialog", clicked=self.on_btn1_clicked) self.btn1.setMaximumWidth(87) self.btn2 = QPushButton("modal dialog", clicked=self.on_btn2_clicked) self.btn2.setMaximumWidth(87) self.btn3 = QPushButton("modal dialog", clicked=self.on_btn3_clicked) self.btn3.setMaximumWidth(87) self.btn1.setDisabled(True) self.btn2.setDisabled(True) self.btn3.setDisabled(True) self.setWindowTitle('ROS Control Panel') # if not self.isFullScreen(): # self.showMaximized() self.resize(1280, 720) self.setWindowIcon(QIcon(''.join([self.path, '/source/icon.jpg']))) self.ros = Control(self.node) self.InitRviz(self.rvizPath)
# -*- coding: utf-8 -*- """Main function for Daily Generator App This Module defines main function for Daily Generator App. """ import Control if __name__ == '__main__': control = Control.Control() control.start()
def __init__(self): self.servo = Servo() self.control = Control() self.servo.setServoAngle(15, 90)
# Digital OUT TPR_pin = 6 Heater_pin = 7 Stirrer_pin = 8 Lift_pin = 9 Lift2_pin = 10 Crusher_pin = 11 Cleaning_Pump_pin = 12 Circulator_pin = 13 Cooling_Fan_pin = 13 Pump_pin = 13 #---SET SX1509---------------------------------------------------------- addr = 0x3e sx = SX1509.SX1509(addr) ctl = Control.Control(sx) #======================================================================= #---GET Temperature----------------------------------------------------- def get_temp(): ''' heater temperature = top_temp = internal_temp stirrer temperature = bottom_temp = external_temp ''' global avg_bottom_temp, avg_top_temp global arr_count global bottom_temp_arr, top_temp_arr top_temp = round(sensor1.readTempC(), 1)
import Control piezas_maquina = [[2, 3, 1], [2, 1, 2, 3], [3, 1, 2], [2, 3, 1, 2], [3, 2]] piezas_tiempo = [[2, 2, 1], [0.5, 2, 0.5, 2.5], [1.5, 2.5, 1], [1, 2.5, 3, 1], [0.5, 2]] control = Control.Control(piezas_maquina, piezas_tiempo) control.algoritmo() a = 2 piezas_maquina = [[], [], [], [], []]
from Control import * import time import BrickPi_thread el, er = Engine.Engine('A'), Engine.Engine('B') thread = BrickPi_thread.BrickPi_Thread([el, er]) thread.on() control = Control(el, er) for i in range(100): control.drive(1, 1, 0.1) time.sleep(0.1)
def control(driver, timee, email): response = Control.Control(driver, timee, email).sayfaKontrol() if response == "successful": driver.quit() sys.exit()
def main(): time.sleep(0.1) #control class control = Control() #initail serail nano = serial.Serial("/dev/ttyACM0", 9600) font = cv2.FONT_HERSHEY_SIMPLEX offset = [0, 0, 0, 0, 0] Images = [] N_SLICES = 5 # 4 frame_count = 0 frame_rate = 0 nano_info = 0 control_data = 0 for q in range(N_SLICES): Images.append(Image()) blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN( ) # attempt KNN training if blnKNNTrainingSuccessful == False: # if KNN training was not successful print( "\nerror: KNN traning was not successful\n") # show error message return # and exit program # end if cap = cv2.VideoCapture( "nvcamerasrc ! video/x-raw(memory:NVMM), width=(int)1280, height=(int)720,format=(string)I420, framerate=(fraction)30/1 ! nvvidconv flip-method=0 ! video/x-raw, format=(string)BGRx ! videoconvert ! video/x-raw, format=(string)BGR ! appsink" ) while True: if not cap.isOpened(): return if (nano.inWaiting()): nano_info = nano.readline() if frame_count == 0: start_time = time.time() frame_count = frame_count + 1 ret, imgOriginalScene = cap.read() img = imgOriginalScene.copy() # cv2.imshow('debug',imgOriginalScene) if imgOriginalScene is None: # if image was not read successfully print("\nerror: image not read from file \n\n" ) # print error message to std out os.system("pause") # pause so user can see error message return # and exit program # track recognition ########################################################################################### else: SlicePart(imgOriginalScene, Images, N_SLICES) for i in range(N_SLICES): offset[i] = Images[i].dir - 1 control_data = control.update(offset) print(control_data) nano.write(bytes(control_data, 'UTF-8')) if frame_count == 15: frame_rate = round(frame_count / (time.time() - start_time), 3) #print information print(nano_info, " fps= ", frame_rate) nano_info = "" ########################################################################################## listOfPossiblePlates = DetectPlates.detectPlatesInScene( img) # detect plates listOfPossiblePlates = DetectChars.detectCharsInPlates( listOfPossiblePlates) # detect chars in plates #cv2.imshow("imgOriginalScene", imgOriginalScene) # show scene image if len(listOfPossiblePlates) == 0: # if no plates were found print("\nno license plates were detected\n" ) # inform user no plates were found else: # else # if we get in here list of possible plates has at leat one plate # sort the list of possible plates in DESCENDING order (most number of chars to least number of chars) listOfPossiblePlates.sort( key=lambda possiblePlate: len(possiblePlate.strChars), reverse=True) # suppose the plate with the most recognized chars (the first plate in sorted by string length descending order) is the actual plate licPlate = listOfPossiblePlates[0] #cv2.imshow("imgPlate", licPlate.imgPlate) # show crop of plate and threshold of plate #cv2.imshow("imgThresh", licPlate.imgThresh) if len(licPlate.strChars ) == 0: # if no chars were found in the plate print("\nno characters were detected\n\n") # show message # end if drawRedRectangleAroundPlate( imgOriginalScene, licPlate) # draw red rectangle around plate print("\nlicense plate read from image = " + licPlate.strChars + "\n") # write license plate text to std out print("----------------------------------------") ####################################################################################################### if len(licPlate.strChars) >= 3: if ( licPlate.strChars == "ST0P" ): # && licPlate.strChars[1] == 'T' && licPlate.strChars[2] == '0' && licPlate.strChars[3] == 'P'): if (nano.inWaiting()): nano_info = nano.readline() # print('f**k') # check nano.write(bytes("r200000\n", 'UTF-8')) nano_info = "" ###################################################################################################### writeLicensePlateCharsOnImage( imgOriginalScene, licPlate) # write license plate text on the image #cv2.imshow("imgOriginalScene", imgOriginalScene) # re-show scene image cv2.imwrite("imgOriginalScene.png", imgOriginalScene) # write image out to file # end if else #cv2.waitKey(0) # hold windows open until user presses a key return
def Main(SONG_INFO): #all the background and font of the words background = pygame.image.load('image/Main.jpg').convert() Start_button = pygame.image.load('image/Start_button.png').convert_alpha() Control_Button = pygame.image.load( 'image/Control_Button.png').convert_alpha() High_Score_Button = pygame.image.load( 'image/High_Score_Button.png').convert_alpha() ACCEPT = pygame.image.load('image/ACCEPT.png').convert_alpha() ACCEPT_ON = pygame.image.load('image/ACCEPT_ON.png').convert_alpha() pygame.display.set_caption('MEGA MUSIC KEY-BUSTER') WORD = pygame.font.SysFont("none", 50) WORD2 = pygame.font.SysFont("none", 30) #this will randomly creat a mission, player will have 50% chance of reciving a mission MISSION = random.randint(0, 1) #blit the background screen.blit(background, (0, 0)) #Up dates the screen pygame.display.flip() #delay pygame.time.delay(500) #Main loop while True: #Get the event of the screen events = pygame.event.get() for e in events: #if the user click quit if e.type == QUIT: #import def and from def, it will exit pygame and sys Exit_Pygame.EXIT() #get the position of mouse pos = pygame.mouse.get_pos() butt = pygame.mouse.get_pressed() x = pos[0] y = pos[1] #if the mouse is within the mouse if x > 267 and x < 437 and y > 464 and y < 634: #blit the image onto the screen screen.blit(Start_button, (252, 450)) #if the button is pressed down if butt[0] == 1: #goes to next page Def.NORMAL(SONG_INFO) ########## EVERYTHING IS THE SAME, EXCEPT for the location and page ############ elif x > 64 and x < 236 and y > 464 and y < 634 and ( butt[0] == 0 or butt[0] == 1): screen.blit(Control_Button, (52, 450)) if butt[0] == 1: total = Control.Control(SONG_INFO) elif x > 466 and x < 634 and y > 464 and y < 634 and ( butt[0] == 0 or butt[0] == 1): screen.blit(High_Score_Button, (452, 450)) if butt[0] == 1: SCORE_DISPLAY.SCORE_DISPLAY(SONG_INFO) elif x > 514 and x < 685 and y > 218 and y < 383 and MISSION == 0: screen.blit(ACCEPT_ON, (500, 200)) if butt[0] == 1: Def.RANDOM_MISSION(SONG_INFO) else: # blit the background screen.blit(background, (0, 0)) #if the mission is 0, this will show up if MISSION == 0: #display the message MISSION_NAME = 'New Challenge, do you accept?' #blit the message screen.blit( WORD2.render(MISSION_NAME, 1, THECOLORS["red"]), (10, 280)) #Blit the image ACCEPT screen.blit(ACCEPT, (500, 200)) #said welcome to the name that player has entered NAME = 'Welcome DJ ' + SONG_INFO[0] #gives the current score SCORE = 'Your current EXP is: ' + str(SONG_INFO[1]) #info Info = 'If you dont know the keys, go to control' #blit the word and name screen.blit(WORD.render(Info, 1, THECOLORS["green"]), (10, 400)) screen.blit(WORD.render(NAME, 1, THECOLORS["green"]), (220, 100)) screen.blit(WORD.render(SCORE, 1, THECOLORS["green"]), (220, 150)) #update the screen pygame.display.flip()
import check from Control import * ##### 변수 설정 부분 ##### DATA_PATH = "./data/" HOST = '127.0.0.1' TCP_FORWARDED_HOST = '1.tcp.jp.ngrok.io:25327' PORT = 8000 url = "https://kakaoi-newtone-openapi.kakao.com/v1/recognize" key = 'my key' headers = { "Content-Type": "application/octet-stream", "X-DSS-Service": "DICTATION", "Authorization": "KakaoAK " + key, } control = Control() ########################### def threaded(client_socket, addr): print('Connected by :', addr[0], ':', addr[1]) # 클라이언트가 접속을 끊을 때 까지 반복합니다. data_transferred = 0 count = 0 while True: try: data = client_socket.recv(1024)
import Control as ctl from models import particle_swarm as ps from models import simulated_annealing as sa if __name__ == "__main__": # El siguiente objeto, contiene el pipeline principal para: # Crear y cargar la base de datos # Transormar los datos a un formato adecuado de trabajo # Calcular las rutas de todas las fuerzas de ventas de manera secuencial objControl = ctl.Control() objControl.CargarBase() objControl.Transform() objControl.CalcularRutasPar(ps.ParticleSwarm, objControl.dict_Hiper_PS) objControl.grafo_Ejecucion.compute() objControl.CalcularRutasSeq(sa.SimulatedAnnealing, objControl.dict_Hiper_SA)
#Import everything in the control module, #including functions, classes, variables, and more. from Control import * #Creating object 'control' of 'Control' class. c = Control() #example: #data=['CMD_MOVE', '1', '0', '25', '10', '0'] #Move command:'CMD_MOVE' #Gait Mode: "1" #Moving direction: x='0',y='25' #Delay:'10' #Action Mode : '0' Angleless turn #Move forward in action mode 1 and gait mode 1 for i in range(3): data = ['CMD_MOVE', '1', '0', '35', '10', '0'] c.run(data) #Move right in action mode 1 and gait mode 1 for i in range(3): data = ['CMD_MOVE', '1', '35', '0', '10', '0'] c.run(data) #Move backward in action mode 2 and gait mode 2 for i in range(3): data = ['CMD_MOVE', '2', '0', '-35', '10', '10'] c.run(data) #Move right in action mode 2 and gait mode 2 for i in range(3):
except KeyboardInterrupt: tornado.ioloop.IOLoop.instance().stop() logger.debug("User interrupt (main)") interrupted = True logger.debug("Main terminated with interrupt = " + str(interrupted)) return interrupted # This is the main application to be called to run the whole robot if __name__ == '__main__': logger.debug("Starting control thread") logger.debug("Starting senor thread") s = Sense.Sense() s.start() c = Control.Control(s) c.start() v = Vision.Vision() v.start() while (1): logger.info("Starting web server") interrupted = main() if (interrupted == True): break # Signal termination logger.info("User interrupt") s.terminate() c.terminate() v.terminate() logger.debug("Main loop finished (__main__") # Wait for actual termination (if needed)
import sys import Control, Vista from PyQt5.QtWidgets import QApplication from PyQt5.QtCore import QFile, QTextStream from PyQt5 import QtCore, QtGui # creamos la aplicación app = QApplication(sys.argv) file = QFile("stylesheet.qss") file.open(QFile.ReadOnly | QFile.Text) stream = QTextStream(file) app.setStyleSheet(stream.readAll()) app_icon = QtGui.QIcon() app_icon.addFile('icon.png', QtCore.QSize(256, 256)) app.setWindowIcon(app_icon) #creamos el controlador ctr = Control.Control() #creamos la ventana view = Vista.Vista(ctr) #asociamos la ventana al controlados ctr.asignarVentana(view) #mostramos todo view.show() sys.exit(app.exec_())