Example #1
0
 def screen(self):
     #loading Ui file named untitled.ui. It contains a label box named screen
     uic.loadUi('untitled.ui', self)
     self.myThread = Thread(self)
     self.myThread.stream = 0
     self.myThread.changePixmap.connect(self.screen.setPixmap)
     self.myThread.start()
Example #2
0
 def InstallAllOptioned(self):
     self.Install.setDisabled(True)
     self.InstallThread = Thread({
         'vc2015-2019_x86.exe':
         self.vc2015to19x86.isChecked(),
         'vc2015-2019_x64.exe':
         self.vc2015to19x64.isChecked(),
         'vc2013_x86.exe':
         self.vc2013x86.isChecked(),
         'vc2013_x64.exe':
         self.vc2013x64.isChecked(),
         'vc2012_x86.exe':
         self.vc2012x86.isChecked(),
         'vc2012_x64.exe':
         self.vc2012x64.isChecked(),
         'vc2010_x86.exe':
         self.vc2010x86.isChecked(),
         'vc2010_x64.exe':
         self.vc2010x64.isChecked(),
         'vc2008_x86.exe':
         self.vc2008x86.isChecked(),
         'vc2008_x64.exe':
         self.vc2008x64.isChecked()
     })
     self.InstallThread.EmptyOption.connect(self.EmptyOptionTip)
     self.InstallThread.UnzipFile.connect(self.UnzipFileTip)
     self.InstallThread.Installing.connect(self.InstallingTip)
     self.InstallThread.InstallFinish.connect(self.InstallFinishTip)
     self.InstallThread.start()
 def Open(self):
     SwitchWindow(self.masterFrame, self.root)
     self.Refresh()
     if self.refreshingThread == None:
         self.refreshingThread = Thread('refreshingThread',
                                        self.SensorRefresh, 0.5)
         self.refreshingThread.start()
Example #4
0
 def Open(self):
     #retour = Popup(self, 2, texte= "ATTENTION: Ce menu est reservé au personnel habilité", valider= "Continuer", fermer= "Retour")
     #if retour == False:
     #    return
     SwitchWindow(self.masterFrame, self.root)
     self.Refresh()
     if self.refreshingThread == None:
         self.refreshingThread = Thread('refreshingThread',
                                        self.SensorRefresh, 0.1)
         self.refreshingThread.start()
Example #5
0
    def __init__(self, server_manager):
        """The function receives server manager and respectively to this server manager instance it received it create
        an receive thread."""

        Thread.__init__(self, 1, "Receive")

        self.server_manager = server_manager

        self.general = server_manager.general

        # The main socket of the current server.
        self.server_socket = server_manager.socket
 def __init__(self, directory='.', prefix='', postfix='', extension='log', note='LOGGER', yday=False, pid=False, name=None):
     Thread.__init__(self, name=name)
     self.file_handles = {}
     self.logger = Logger(directory=directory, prefix=prefix, postfix=postfix, extension=extension, note=note, yday=yday)
     self._log_note = note
     self.logger.set_log_debug(False)
     #self.logger.set_log_debug(True)
     self.logger.set_log_to_file(False)
     self.logger.set_log_to_screen(True)
     self.logger.set_log_note(note)
     self.logger.set_note_first(True)
     self.logger.set_log_pid(pid)
Example #7
0
    def __init__(self):

        """The function create a db functions instance.
        The function does not return parameters."""

        Thread.__init__(self, 5, "DbFunctions")

        self.asks = []

        #flag that sign if there is duplicates of the user name it get or not

        self.user_name_duplicates_flags = {}
Example #8
0
    def run(self):

        try:
            old_path = self.lineEdit_old.text()
            new_path = self.lineEdit_new.text()
            if not all([old_path, new_path]): return
            self.t = Thread(self, old_path, new_path)
            self.t.sig_msg.connect(self.update_label)
            self.t.finished.connect(self.t.deleteLater)
            self.t.start()
            QMessageBox.information(self, '提示', '运行完成')
        except Exception as e:
            QMessageBox.warning(self, '错误', str(e))
Example #9
0
class Window(base, form):
    def __init__(self):
        super(base, self).__init__()
        # default setup
        self.setupUi(self)

        # create thread for updating the GUI
        self.thread = Thread()
        # connect thread of incoming data to updateData method
        self.thread.newData.connect(self.updateData)
        # start thread
        self.thread.start()

        # handle button clicks
        self.buttonPlayPause.clicked.connect(onPlayPauseClick)
        self.buttonPreviousTrack.clicked.connect(onPreviousTrackClick)
        self.buttonNextTrack.clicked.connect(onNextTrackClick)

    # update GUI data
    def updateData(self, data):
        # set current track label
        self.labelCurrentTrack.setText(data['currentTrack'])
        # set current artist label
        self.labelCurrentArtist.setText(data['currentArtist'])
        # set previous track label
        self.labelPreviousTrack.setText(data['prevTrack'])
        # set previous artist label
        self.labelPreviousArtist.setText(data['prevArtist'])
        # store previous track for reference
        prevTrack = data['prevTrack']
        # if the track has been changed and it is not the first iteration
        if prevTrack not in trackHistory and len(prevTrack) > 0:
            # add track to track history
            trackHistory.append(prevTrack)
            # add track to list widget in GUI
            self.listTrackHistory.addItem(data['prevArtist'] + " - " +
                                          prevTrack)
        # create image object to store cover art
        coverArtImage = QImage()
        # load in image from given URL
        coverArtImage.loadFromData(requests.get(data['coverArt']).content)
        # convert to pixmap
        pixmap = QPixmap(coverArtImage)
        # scale it to fit GUI
        scaledPixmap = pixmap.scaledToHeight(180)
        # update GUI with cover art
        self.labelCoverArt.setPixmap(scaledPixmap)
        # update track popularity bar
        self.trackPopularity.setValue(data['trackPopularity'])
        # update timer
        self.labelTime.setText(data['timeString'])
Example #10
0
    def start_btn_clicked(self):
        btn = self.sender()
        prob_rule4 = int(self._prob_rule4.text())
        self._mesh.set_prob_for_rule4(prob_rule4)
        if self._mesh.is_running():
            btn.setText("START")
        else:
            btn.setText("STOP")
            self._thread = Thread(self._mesh)
            self._thread.update_ui.connect(self._update_UI)
            self._thread.update_btn.connect(self._update_button)

            self._thread.start()
        self._mesh.change_started()
Example #11
0
    def __init__(self, server_manager):
        """The function receives server manager and respectively to this server manager instance it received it create
        an send thread."""

        Thread.__init__(self, 2, "Send")

        self.general = server_manager.general

        # The main socket of the current Server.
        self.socket = server_manager.socket

        # The current message this class has to send.
        self.current_messages = []

        # The current message the class sends. [client, content].
        self.message = []
Example #12
0
    def __init__(self):
        super(base, self).__init__()
        # default setup
        self.setupUi(self)

        # create thread for updating the GUI
        self.thread = Thread()
        # connect thread of incoming data to updateData method
        self.thread.newData.connect(self.updateData)
        # start thread
        self.thread.start()

        # handle button clicks
        self.buttonPlayPause.clicked.connect(onPlayPauseClick)
        self.buttonPreviousTrack.clicked.connect(onPreviousTrackClick)
        self.buttonNextTrack.clicked.connect(onNextTrackClick)
Example #13
0
    def run_simulation(self):
        """
        Iniciar el simulador de ICESym
        """

        # TODO: Verificar si hay componentes desconectados
        
        simulator = None
        if 'linux' in platform:
            simulator = os.path.join(SIMULATOR_PATH,"exec")
        elif 'win' in platform:
            simulator = os.path.join(SIMULATOR_PATH,"exec.exe")
        if not simulator or not os.path.isfile(simulator):
            show_message('Cannot find exec file. Please, create this file to run the simulator')
            return

        # Salvar el caso
        self.save_data_f(None,True)

        logfile = os.path.join(SIMULATOR_PATH,'run.log')
        errorlogfile = os.path.join(SIMULATOR_PATH,'error.log')
        if 'linux' in platform:
            command = "%s %s %s 1> %s 2> %s"%(simulator,self.case_dir,self.case_name,logfile,errorlogfile)
        elif 'win' in platform:
            command = "echo.> %s"%logfile
            os.system(command)
            while not os.path.isfile(logfile):
                None
            command_ex = "%s %s %s 1^> %s 2^> %s"%(simulator,self.case_dir,self.case_name,logfile,errorlogfile)
            execwfile = os.path.join(SIMULATOR_PATH,'execw.bat')
            command = "echo %s > %s"%(command_ex,execwfile)
            os.system(command)
            while not os.path.isfile(execwfile):
                None
            command = os.path.join(SIMULATOR_PATH,'execw.bat')

        self.thread_runSimulation = Thread(command)
        # limpio el log y agrego el archivo al watcher
        self.ui_tab_widget.logPlainTextEdit.clear()
        self.thread_runSimulation.started.connect(lambda: self.init_log(logfile))
        self.thread_runSimulation.started.connect(self.show_info)
        self.thread_runSimulation.finished.connect(self.reset_log)
        self.thread_runSimulation.finished.connect(self.reset_pid)
        self.thread_runSimulation.finished.connect(self.success_simulation)
        # inicio el thread
        self.thread_runSimulation.start()
        return
	def makeThreads(self, numberOfTracks, divisionConstant):
		threadProbability = 100 / divisionConstant #threadProbability for first thread (see note below at divisionConstant decleration)
		self.threads = [] #array of threadObjects that will be used
		for each in range(0, numberOfTracks): #making one Thread object for each possible numberOfTracks that will play at one time
			self.threads.append(Thread((threading.Thread()), (threadProbability)))
			#First parameter for Thread() - a new thread
			#Second parameter - the probability that the thread will play when it is checked, calculated on the next line
			threadProbability = (self.threads[each].getProbability() / 2) #to be used for the next thread to be created
		return
Example #15
0
class MainWindow(QMainWindow, Ui_MainWindow):

    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.retranslateUi(self)
        self.setFixedSize(self.width(), self.height())

        self.signals()

    def signals(self):
        self.pushButton_old.clicked.connect(lambda: self.open_file(self.lineEdit_old))
        self.pushButton_new.clicked.connect(lambda: self.open_file(self.lineEdit_new))
        self.pushButton_run.clicked.connect(self.run)

    # 槽函数-----------------------------------------------------------------------------------------------------------
    # 打开文件
    def open_file(self, lineEdit):
        try:
            filename = QFileDialog.getExistingDirectory(self, '选择文件夹', './')
            lineEdit.setText(filename)
        except Exception as e:
            self.log.logger.warning(str(e))

    def update_label(self, msg):
        self.label.setText(msg)

    # 生成主逻辑
    def run(self):

        try:
            old_path = self.lineEdit_old.text()
            new_path = self.lineEdit_new.text()
            if not all([old_path, new_path]): return
            self.t = Thread(self, old_path, new_path)
            self.t.sig_msg.connect(self.update_label)
            self.t.finished.connect(self.t.deleteLater)
            self.t.start()
            QMessageBox.information(self, '提示', '运行完成')
        except Exception as e:
            QMessageBox.warning(self, '错误', str(e))
Example #16
0
def Start():

    Sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    Sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    Sock.bind((SERVER_HOST, SERVER_PORT))
    Sock.listen(Max)

    print(f"[*] Listening as {SERVER_HOST}:{SERVER_PORT}")
    while True:
        client, address = Sock.accept()
        data = client.recv(BUFFER_SIZE).decode()
        if data == "code":
            ClientFile = open('__Client.py', 'r', encoding='utf-8')
            while True:
                Byte = ClientFile.read(BUFFER_SIZE)
                if not Byte:
                    ClientFile.close()
                    break

                client.send(Byte.encode())
            client.send("--||--".encode())
        print(f"[+] {address} is connecting.")
        t = Thread(target=Command, args=(client, address), daemon=True)
        t.start()
        t.join()
Example #17
0
    def startThread(self):

        if self.__thread is None:

            thread = Thread(self.__trackers)
            self.__thread = thread

            self.__thread.start()

            print("Thread enabled")

        else:

            print("Thread already enabled")
Example #18
0
    def init(self):
        Logger.debug("SlaveServer init")

        if not self.communication.initialize():
            Logger.error(
                "SlaveServer: unable to initialize communication class")
            return False

        self.communication.ovd_thread = Thread(name="Communication",
                                               target=self.communication.run)
        self.threads.append(self.communication.ovd_thread)

        for role in self.roles:
            try:
                if not role.init():
                    raise Exception()
            except Exception, e:
                Logger.error("SlaveServer: unable to initialize role '%s' %s" %
                             (role.getName(), str(e)))
                return False

            role.thread = Thread(name="role_%s" % (role.getName()),
                                 target=role.run)
            self.threads.append(role.thread)
Example #19
0
def parse_thread(thread_num, visualize):
    """
    Given a thread_num of a thread on /biz/ on 4chan, this function creates a Thread representation of that thread.
    Useful for revealing sub thread conversations on a given thread. If visualize is enabled, creates a pdf file of the
    graph output, titled thread_thread_num.pdf.
    :param thread_num: the number of the thread to create
    :param visualize: boolean for visualization
    :return: the Thread object for future use
    """
    pg2 = requests.get('https://a.4cdn.org/biz/thread/{}.json'.format(thread_num)).json()


    # Maps all of the post JSON into threads
    posts = list(map(make_post, pg2['posts']))

    # Updates the posts to have responses attached to them
    list(map(lambda x: x.add_responses(list(filter(lambda y: x.title in y.resto, posts))), posts))

    # If the visualize argument is true, then render a graphviz digraph of the Thread
    if visualize:
        graph = gv.Digraph()
        list(map(lambda x: graph.node(name=str(x.title), label=str(x.content)), posts))
        for post in posts:
            for res in post.resto:
                graph.edge(str(post.title), str(res))
        graph.render('thread_{}'.format(thread_num))

        with open("thread_{}.json".format(thread_num), 'w+') as f:
            f.write(str(pg2))

    # Create the thread object, and mark the OP as the post that is a resto 0
    print('======================================================================')
    for post in posts:
        print(post)
    t = Thread(start_date=pg2.get('time'), title=pg2.get('title'),
           op=head(list(filter(lambda x: x.resto == {'0'} or x.resto == {0}, posts))))

    return t
Example #20
0
class MainWindow(QMainWindow):

    geometry = QRect(700, 300, 400, 400)

    def __init__(self, app):
        super().__init__()
        self._app = app
        MainWindow.geometry = QRect(app.desktop().screenGeometry().width() - MENU_WIDTH, 300, MENU_WIDTH, MENU_HEIGHT)
        self._init_ui()
        self._started = False
        self._mesh = Mesh(DEF_POINTS_SIZE.width(), DEF_POINTS_SIZE.height(), PROB)
        self._canvas = Canvas(self.get_canvas__geometry(), self._mesh)
        self._nhood = NHOODS[0]
        self._periodic = False
        self._canvas.show()
        self._thread = None

    def _init_ui(self):
        self.setWindowTitle("Grain groth CA")
        self.setGeometry(MainWindow.geometry)
        self._create_widgets()
        self._create_menu()

    def get_canvas__geometry(self):
        geometry = QRect(MainWindow.geometry.topLeft().x() - CANVAS_WIDTH,
                         MainWindow.geometry.topLeft().y(),
                         CANVAS_WIDTH,
                         CANVAS_HEIGHT)
        return geometry

    def _create_menu(self):
        menu_bar = self.menuBar()
        file_menu = menu_bar.addMenu('File')
        clear = QAction("Clear", self)
        file_menu.addAction(clear)

        microstructure_submenu = QMenu("Microstructure", self)

        import_txt = QAction("Import from txt file", self)
        import_bmp = QAction("Import from bmp file", self)
        export_txt = QAction("export to txt file", self)
        export_bmp = QAction("export to bmp file", self)

        microstructure_submenu.addAction(import_txt)
        microstructure_submenu.addAction(export_txt)
        microstructure_submenu.addAction(import_bmp)
        microstructure_submenu.addAction(export_bmp)

        file_menu.addMenu(microstructure_submenu)

        import_txt.triggered.connect(self._import_txt_triggered)
        import_bmp.triggered.connect(self._import_bmp_triggered)
        export_txt.triggered.connect(self._export_txt_triggered)
        export_bmp.triggered.connect(self._export_bmp_triggered)

    def _create_widgets(self):

        main_layout = QGridLayout()

        main_layout.addWidget(QLabel('width:'), 1, 1)
        self._width = QLineEdit(str(DEF_POINTS_SIZE.width()))
        main_layout.addWidget(self._width, 1, 2)

        main_layout.addWidget(QLabel('height:'), 1, 3)
        self._height = QLineEdit(str(DEF_POINTS_SIZE.height()))
        main_layout.addWidget(self._height, 1, 4)

        gen_space_btn = QPushButton("change space")
        gen_space_btn.clicked.connect(self._gen_space_btn_clicked)
        main_layout.addWidget(gen_space_btn, 2, 1, 1, 4)

        main_layout.addWidget(QLabel('number of grains:'), 3, 1)
        self._grains = QLineEdit("10")
        main_layout.addWidget(self._grains, 3, 2)
        gen_grains_btn = QPushButton("generate grains")
        gen_grains_btn.clicked.connect(self._gen_grains_btn_clicked)
        main_layout.addWidget(gen_grains_btn, 3, 3, 1, 2)

        main_layout.addWidget(QLabel('number of inclusions:'), 4, 1)
        self._inclusions = QLineEdit("5")
        main_layout.addWidget(self._inclusions, 4, 2)
        main_layout.addWidget(QLabel('size of inclusion:'), 4, 3)
        self._inclusions_size = QLineEdit("1")
        main_layout.addWidget(self._inclusions_size, 4, 4)

        gen_inclusions_btn = QPushButton("generate square inclusions")
        gen_inclusions_btn.clicked.connect(self.gen_inclusions_btn_clicked)
        main_layout.addWidget(gen_inclusions_btn, 5, 1, 1, 4)

        gen_inclusions_circle_btn = QPushButton("generate circle inclusions")
        gen_inclusions_circle_btn.clicked.connect(self.gen_circle_inclusions_btn_clicked)
        main_layout.addWidget(gen_inclusions_circle_btn, 6, 1, 1, 4)

        main_layout.addWidget(QLabel('probability for rule 4:'), 7, 1)
        self._prob_rule4 = QLineEdit(str(PROB))
        main_layout.addWidget(self._prob_rule4, 7, 2)
        main_layout.addWidget(QLabel('%'), 7, 3)

        self._start_btn = QPushButton("START")
        self._start_btn.clicked.connect(self.start_btn_clicked)
        main_layout.addWidget(self._start_btn, 8, 1, 1, 4)

        clear_btn = QPushButton("CLEAR")
        clear_btn.clicked.connect(self.clear_btn_clicked)
        main_layout.addWidget(clear_btn, 9, 1, 1, 4)

        main_layout.addWidget(QLabel('number of grains'), 10, 1)
        self._nb_of_grains = QLineEdit("2")
        main_layout.addWidget(self._nb_of_grains, 10, 2)

        clear_rand_btn = QPushButton("SELECT GRAINS")
        clear_rand_btn.clicked.connect(self.clear_rand_btn_clicked)
        main_layout.addWidget(clear_rand_btn, 10, 3, 1, 4)

        clear_rand_dp_btn = QPushButton("SELECT GRAINS-DP")
        clear_rand_dp_btn.clicked.connect(self.clear_rand_dp_btn_clicked)
        main_layout.addWidget(clear_rand_dp_btn, 11, 3, 1, 4)


        main_layout.addWidget(QLabel('bound size'), 12, 1)
        self.bound_size = QLineEdit("1")
        main_layout.addWidget(self.bound_size, 12, 2)

        draw_bound_btn = QPushButton("DRAW BOUNDARIES")
        draw_bound_btn.clicked.connect(self.draw_bound_btn_clicked)
        main_layout.addWidget(draw_bound_btn, 12, 3, 1, 4)

        draw_rand_bound_btn = QPushButton("DRAW RAND BOUNDARIES")
        draw_rand_bound_btn.clicked.connect(self.draw_rand_bound_btn_clicked)
        main_layout.addWidget(draw_rand_bound_btn, 13, 3, 1, 4)

        clear_bound_btn = QPushButton("REMOVE GRAINS")
        clear_bound_btn.clicked.connect(self.clear_bound_btn_clicked)
        main_layout.addWidget(clear_bound_btn, 14, 3, 1, 4)

        remove_bound_lines_btn = QPushButton("REMOVE BOUND LINES")
        remove_bound_lines_btn.clicked.connect(self.remove_bound_lines_btn_clicked)
        main_layout.addWidget(remove_bound_lines_btn, 15, 3, 1, 4)

        central_w = QWidget()
        central_w.setLayout(main_layout)

        self.setCentralWidget(central_w)


    def _gen_space_btn_clicked(self):
        width = int(self._width.text())
        height = int(self._height.text())
        if self._canvas:
            self._canvas.close()
        self._mesh = Mesh(width, height, PROB)
        self._canvas = Canvas(self.get_canvas__geometry(), self._mesh)
        self._canvas.show()

    def _gen_grains_btn_clicked(self):
        nmb_grains = int(self._grains.text())
        self._mesh.generate_grains(nmb_grains)
        self._canvas.repaint()

    def gen_inclusions_btn_clicked(self):
        nmb_of_inc = int(self._inclusions.text())
        size = int(self._inclusions_size.text())
        self._mesh.generate_square_inclutions(nmb_of_inc, size)
        self._canvas.repaint()

    def gen_circle_inclusions_btn_clicked(self):
        nmb_of_inc = int(self._inclusions.text())
        size = int(self._inclusions_size.text())
        self._mesh.generate_circle_inclutions(nmb_of_inc, size)
        self._canvas.repaint()

    def start_btn_clicked(self):
        btn = self.sender()
        prob_rule4 = int(self._prob_rule4.text())
        self._mesh.set_prob_for_rule4(prob_rule4)
        if self._mesh.is_running():
            btn.setText("START")
        else:
            btn.setText("STOP")
            self._thread = Thread(self._mesh)
            self._thread.update_ui.connect(self._update_UI)
            self._thread.update_btn.connect(self._update_button)

            self._thread.start()
        self._mesh.change_started()

    def clear_btn_clicked(self):
        width = int(self._width.text())
        height = int(self._height.text())
        prob_rule4 = int(self._prob_rule4.text())
        self._mesh = Mesh(width, height, prob_rule4)
        self._canvas.close()
        self._canvas = Canvas(self.get_canvas__geometry(), self._mesh)
        self._canvas.show()
        self._canvas.repaint()

    def clear_rand_btn_clicked(self):
        nb_of_grains = int(self._nb_of_grains.text())
        self._mesh.clear_rand(nb_of_grains)
        self._canvas.repaint()

    def clear_rand_dp_btn_clicked(self):
        nb_of_grains = int(self._nb_of_grains.text())
        self._mesh.clear_rand(nb_of_grains, dual_phase=True)
        self._canvas.repaint()

    def _export_txt_triggered(self):
        path = QFileDialog.getSaveFileName(self)[0]
        FileHandler.save_mesh(path, self._mesh)

    def _import_bmp_triggered(self):
        file_name = QFileDialog.getOpenFileName(self)[0]
        self._canvas.build_from_screenshot(file_name)

    def _import_txt_triggered(self):
        path = QFileDialog.getOpenFileName(self)[0]
        self._mesh = FileHandler.load_mesh(path)
        self._width.setText(str(self._mesh.get_size().width()))
        self._height.setText(str(self._mesh.get_size().height()))
        self._canvas = Canvas(self.get_canvas__geometry(), self._mesh)
        self._canvas.show()


    def _export_bmp_triggered(self):
        file_name = QFileDialog.getSaveFileName(self)[0]
        img = self._canvas.take_screenshot()
        img.save(file_name, 'bmp')

    def _update_UI(self):
        self._canvas.repaint()

    def _update_button(self):
        if self._mesh.is_running():
            self._start_btn.setText("STOP")
        else:
            self._start_btn.setText("START")

    def draw_bound_btn_clicked(self):
        line_size = int(self.bound_size.text())
        self._mesh.gen_boundary_lines(line_size)
        self._canvas.repaint()

    def clear_bound_btn_clicked(self):
        self._mesh.remove_grains()
        self._canvas.repaint()

    def draw_rand_bound_btn_clicked(self):
        line_size = int(self.bound_size.text())
        nb_of_grains = int(self._nb_of_grains.text())
        self._mesh.generate_rand_boundary(line_size, nb_of_grains)
        self._canvas.repaint()

    def remove_bound_lines_btn_clicked(self):
        self._mesh.remove_boundaries()
        self._canvas.repaint()
Example #21
0
class Tictactoe(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.setGeometry(250, 250, 600, 300)
        self.setWindowTitle("TenElevenGames OXO")
        self.setWindowIcon(QIcon("icon.jpg"))
        self.show()

        # NERDZONE
        # implement a simple help menu
        # create QAction buttons for the menu
        Instructions = QAction("How to play", self)
        AboutGame = QAction("About", self)
        More = QAction("More", self)

        # add the buttons to the menu
        menu = QMenuBar()
        menu.addAction(Instructions)
        menu.addAction(AboutGame)
        menu.addAction(More)

        # connect the buttons to their respective methods
        # when clicked, each button is supposed to show a popup dialogue
        # with the relevant information as per the name of the button suggests
        Instructions.triggered.connect(self.instructions)
        AboutGame.triggered.connect(self.about)
        More.triggered.connect(self.more)

        # images
        self.cross = QPixmap("cross.gif")
        self.nought = QPixmap("nought.gif")
        self.blank = QtGui.QIcon("blank.gif")

        # create a thread to run parallel to the gui
        self.messageThread = Thread()
        self.messageThread.signalLine.connect(self.threadLine)

        # Game board
        # create game buttons and set their sizes when window changes size
        # connect each button to it's OWN method
        self.buttonArray = []
        # first row
        self.button1 = QPushButton()
        self.button1.setIcon(QtGui.QIcon('blank.gif'))
        self.button1.setIconSize(QtCore.QSize(60, 85))
        self.buttonArray.append(self.button1)
        self.button1.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        self.button1.clicked.connect(self.button1Event)

        self.button2 = QPushButton()
        self.button2.setIcon(QtGui.QIcon('blank.gif'))
        self.button2.setIconSize(QtCore.QSize(60, 85))
        self.buttonArray.append(self.button2)
        self.button2.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        self.button2.clicked.connect(self.button2Event)

        self.button3 = QPushButton()
        self.button3.setIcon(QtGui.QIcon('blank.gif'))
        self.button3.setIconSize(QtCore.QSize(60, 85))
        self.buttonArray.append(self.button3)
        self.button3.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        self.button3.clicked.connect(self.button3Event)
        #
        # second row
        self.button4 = QPushButton()
        self.button4.setIcon(QtGui.QIcon('blank.gif'))
        self.button4.setIconSize(QtCore.QSize(60, 85))
        self.buttonArray.append(self.button4)
        self.button4.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        self.button4.clicked.connect(self.button4Event)

        self.button5 = QPushButton()
        self.button5.setIcon(QtGui.QIcon('blank.gif'))
        self.button5.setIconSize(QtCore.QSize(60, 85))
        self.buttonArray.append(self.button5)
        self.button5.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        self.button5.clicked.connect(self.button5Event)

        self.button6 = QPushButton()
        self.button6.setIcon(QtGui.QIcon('blank.gif'))
        self.button6.setIconSize(QtCore.QSize(60, 85))
        self.buttonArray.append(self.button6)
        self.button6.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        self.button6.clicked.connect(self.button6Event)
        #
        # third row
        self.button7 = QPushButton()
        self.button7.setIcon(QtGui.QIcon('blank.gif'))
        self.button7.setIconSize(QtCore.QSize(60, 85))
        self.buttonArray.append(self.button7)
        self.button7.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        self.button7.clicked.connect(self.button7Event)

        self.button8 = QPushButton()
        self.button8.setIcon(QtGui.QIcon('blank.gif'))
        self.button8.setIconSize(QtCore.QSize(60, 85))
        self.buttonArray.append(self.button8)
        self.button8.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        self.button8.clicked.connect(self.button8Event)

        self.button9 = QPushButton()
        self.button9.setIcon(QtGui.QIcon('blank.gif'))
        self.button9.setIconSize(QtCore.QSize(60, 85))
        self.buttonArray.append(self.button9)
        self.button9.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        self.button9.clicked.connect(self.button9Event)
        #
        self.Quit = QPushButton("Quit")
        self.Quit.setShortcut("ctrl+v")
        self.Quit.setToolTip("Exit the game: ctrl+v")
        self.Quit.resize(10, 10)
        # self.Quit.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.Quit.clicked.connect(self.quit)
        self.connectServer = QPushButton("Connect")
        self.connectServer.setShortcut("ctrl+e")
        self.connectServer.setToolTip("Connect to the server: ctrl+e")
        self.connectServer.clicked.connect(self.connectEvent)

        self.messageBox = QTextEdit()
        self.messageBox.setSizePolicy(QSizePolicy.Expanding,
                                      QSizePolicy.Expanding)
        # ensure that the QTextEdit allows for reading messages only, no typing/editing. "lock" the QTextEdit.
        self.messageBox.setReadOnly(True)

        # server entry
        self.label = QLabel("Enter server: ")
        self.label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.getServer = QLineEdit('127.0.0.1')

        # player character display
        self.character = QLabel("Game Character: ")
        self.pixmap = QPixmap('cross.gif')
        self.pixmap2 = QPixmap("nought.gif")
        self.picLabel = QLabel()
        self.picLabel.setSizePolicy(QSizePolicy.Expanding,
                                    QSizePolicy.Expanding)

        # enhancement
        # will most probably remove this later on
        self.comboBox = QComboBox()
        self.comboBox.addItems(
            ['Pink', 'Grey', 'Red', 'Orange', 'Yellow', 'Purple'])
        self.comboBox.activated.connect(self.setColour)
        self.setStyleSheet("background-color: pink")
        self.messageBox.setStyleSheet('background-color: white')
        self.getServer.setStyleSheet('background-color: white')
        # self.comboBox.setStyleSheet('background-color: white')

        hbox = QHBoxLayout()
        hbox.addWidget(menu)
        hbox2 = QWidget()
        hbox2.setLayout(hbox)

        # present everything in a Gridlayout
        # making sure to set span width and length (rows, columns) to avoid overlapping
        grid = QGridLayout()
        grid.addWidget(hbox2, 0, 4, 1, 3)
        grid.addWidget(self.label, 1, 0, 1, 1)
        grid.addWidget(self.getServer, 1, 1, 1, 1)
        grid.addWidget(self.connectServer, 1, 2, 1, 1)
        grid.addWidget(self.comboBox, 1, 3, 1, 1)
        #
        grid.addWidget(self.button1, 2, 0, 1, 1)
        grid.addWidget(self.button2, 2, 1, 1, 1)
        grid.addWidget(self.button3, 2, 2, 1, 1)
        #
        grid.addWidget(self.button4, 3, 0, 1, 1)
        grid.addWidget(self.button5, 3, 1, 1, 1)
        grid.addWidget(self.button6, 3, 2, 1, 1)
        #
        grid.addWidget(self.button7, 4, 0, 1, 1)
        grid.addWidget(self.button8, 4, 1, 1, 1)
        grid.addWidget(self.button9, 4, 2, 1, 1)
        #
        grid.addWidget(self.messageBox, 2, 3, 3, 4)
        grid.addWidget(self.character, 5, 1, 1, 1)
        grid.addWidget(self.picLabel, 5, 2, 1, 1)
        grid.addWidget(self.Quit, 5, 5, 1, 1)
        #
        self.setLayout(grid)

    # event handlers for all buttons
    def connectEvent(self):
        self.messageThread.Connect(self.getServer.displayText(
        ))  # connect to server currently entered in the QLineEdit
        self.messageThread.start(
        )  # call the QThread class start() method in order to call the run() method
        self.messageBox.append("Connected to server.")
        self.connectServer.setEnabled(
            False)  # disable the connect button when it's clicked

    # methods for the game board buttons
    # write to the messageBox when a button is clicked
    # this on happens if it's a player's turn to play
    # A player will not be able to click any of the buttons if it's not their turn to play
    def button1Event(self):
        self.messageThread.send_message(str(0))
        self.messageBox.append("Button 1 clicked")

    def button2Event(self):
        self.messageThread.send_message(str(1))
        self.messageBox.append("Button 2 clicked")

    def button3Event(self):
        self.messageThread.send_message(str(2))
        self.messageBox.append("Button 3 clicked")

    def button4Event(self):
        self.messageThread.send_message(str(3))
        self.messageBox.append("Button 4 clicked")

    def button5Event(self):
        self.messageThread.send_message(str(4))
        self.messageBox.append("Button 5 clicked")

    def button6Event(self):
        self.messageThread.send_message(str(5))
        self.messageBox.append("Button 6 clicked")

    def button7Event(self):
        self.messageThread.send_message(str(6))
        self.messageBox.append("Button 7 clicked")

    def button8Event(self):
        self.messageThread.send_message(str(7))
        self.messageBox.append("Button 8 clicked")

    def button9Event(self):
        self.messageThread.send_message(str(8))
        self.messageBox.append("Button 9 clicked")

    def quit(self):
        exitTheGame = QMessageBox.question(
            self, "Exit the game?", "Do you really want to exit the game.",
            QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if (exitTheGame == QMessageBox.Yes):
            sys.exit()
        else:
            pass

    def handle_message(self, msg):
        # the message might/will be comma separated(multiple components)
        # split it into an array so as to individualise each component for later use----.split(",")
        # remove any trailing or leading white space
        message = msg.lower().strip().split(",")
        # lengthOfMessage = len(message)
        # print(message)

        if (message[0] == "new game"):
            shape = message[1]
            if (shape == "x"):
                self.pixmap2 = QPixmap("cross.gif")
            elif (shape == "o"):
                self.pixmap2 = QPixmap("nought.gif")
            self.picLabel.setPixmap(self.pixmap2)
            self.messageBox.append("The game has started, your character is " +
                                   message[1])

        elif (message[0] == "your move"):
            self.messageBox.append(message[0])
            for i in range(len(self.buttonArray)):
                self.buttonArray[i].setEnabled(
                    True
                )  # enable all buttons when it's a player's turn to play

        # disable all buttons when it's not a player's turn to play
        elif (message[0] == "opponents move"):
            self.messageBox.append(message[0])
            for i in range(len(self.buttonArray)):
                self.buttonArray[i].setEnabled(False)
            # print(message[0])

        # when a player makes a valid move at position n, their given character should
        # be added to the board array at index n
        elif (message[0] == "valid move"):
            shape = message[1]
            chosenPosition = message[2]
            if (shape == "x"):
                self.pixmap = QtGui.QIcon("cross.gif")
            elif (shape == "o"):
                self.pixmap = QtGui.QIcon("nought.gif")
            # found that short way I mentioned in assignment 7 :-)
            # rather than have if-else statements for all the buttons
            # I added them to an array then i just iterate over the array and change
            # the icon for the clicked button
            for i in range(9):
                if (chosenPosition == str(i)):
                    self.buttonArray[i].setIcon(QIcon(self.pixmap))
                else:
                    pass

        elif (message[0] == "invalid move"):
            self.messageBox.append(message[0])

        elif (message[0] == "game over"):
            if (message[1].upper() == "T"):
                self.messageBox.append("<strong>Game over, it's a Tie<strong>")
            else:
                self.messageBox.append(
                    "<strong>Game over, the winner is player {}</strong>".
                    format(message[1].upper()))

        # we shouldn't have a new game button
        # a popup made sense
        # if a player chooses to play again:
        # clear the board
        # send word to the server
        # else:......
        elif (message[0] == "play again"):
            endGame = QMessageBox.question(
                self, 'Play Again?', "Game over. Do you want to play again?",
                QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            if endGame == QMessageBox.Yes:
                self.messageBox.clear()
                self.messageThread.send_message("y")
                for i in range(len(self.buttonArray)):
                    self.buttonArray[i].setIcon(QtGui.QIcon('blank.gif'))
            else:
                self.messageThread.send_message("n")

        elif (message[0] == "exit game"):
            self.messageBox.append("Game ended\nG.G")  # "Good Game"

    def setColour(self):
        self.setStyleSheet('background-color:' +
                           str(self.comboBox.currentText()))
        # set the background colour of the messageBox and getServer box explicitly
        # so that it is not affected(coloured in) by the color of the window
        # i.e: remains white at all times
        self.messageBox.setStyleSheet('background-color: white')
        self.getServer.setStyleSheet('background-color: white')

    def instructions(self):
        QMessageBox.information(
            self, self.tr("How to play"),
            self.
            tr("The goal of the game is to get three of your given character\n"
               "symbol into a row, column or diagonal of three before your opponent does so."
               ), QMessageBox.Ok)

    def about(self):
        QMessageBox.information(
            self, self.tr("About"),
            self.
            tr("TenElevenGames OXO\n"
               "Project Leader   : Bhekanani Cele\n"
               "Developers         : Yolisa Pingilili\n\t\t    Jane Doe\n\t\t    John Doe\n"
               "Release date       : 15 June 2020\n"
               "Contact info       : [email protected]"), QMessageBox.Ok)

    def more(self):
        QMessageBox.information(
            self, self.tr("More"),
            self.tr("Keep an eye out\nmore games coming soon!"),
            QMessageBox.Ok)

    # handle messages via thread
    def threadLine(self, msg):
        self.handle_message(msg)
Example #22
0
class SimulationWindow():
    def __init__(self, root):

        # Définition de la fenêtre Parent
        self.root = root

        # Création de la frame qui contient la page
        self.masterFrame = tk.Frame(self.root, bg=self.root.defaultbg)

        # Création des cadres
        self.titleFrame = tk.Frame(self.masterFrame, bg=self.root.defaultbg)
        self.centerSubFrame = tk.Frame(self.masterFrame,
                                       relief='ridge',
                                       bd=3,
                                       bg=self.root.defaultbg)
        self.sensorFrame = tk.Frame(self.centerSubFrame,
                                    relief='ridge',
                                    bd=1,
                                    bg=self.root.defaultbg)
        self.buttonFrame = tk.Frame(self.centerSubFrame,
                                    bg=self.root.defaultbg)
        self.shifterFrame = tk.Frame(self.centerSubFrame,
                                     bg=self.root.defaultbg)

        # Placement des cadres
        self.titleFrame.pack(side='top')
        self.centerSubFrame.pack(expand='true')
        self.sensorFrame.pack(side='left', fill='y')
        self.buttonFrame.pack(side='right', pady=15, padx=15)
        self.shifterFrame.pack(side='left', expand=True, padx=15)

        # Définition des variables
        self.robotSelected = tk.StringVar()
        self.refreshingThread = None
        self.robotAttributes = None
        self.titre = tk.StringVar()
        self.selectedGearLabel = tk.StringVar()
        self.selectedGearLabel.set('N')
        self.sensorGearLabelList = []
        self.sensorRobotLabelList = []
        self.sensorLabelList = []
        self.sensorLabel = {}
        self.shifterButtonList = []
        self.sensorRobotLabelListVarDict = {}
        self.selectedGear = 0

        # Création des paramètres
        self.shifterButtonFont = font.Font(size=22, weight='bold')
        self.shifterButtonHeight = 1
        self.shifterButtonWidth = 2
        self.fontGearButton = font.Font(size=40, weight='bold')
        self.fontGear = font.Font(size=40, weight='bold')
        self.fontSensorTitle = font.Font(size=20, weight='bold')
        self.fontSensor = font.Font(size=19, weight='bold')

    def Setup(self):

        # Récupération de la robot sélectionnée pour le diagnostic
        self.robotSelected = self.root.mainMenuWindow.robotSelected
        self.titre.set("Diagnostic manuel du robot " +
                       str(self.robotSelected.get()))
        self.robotAttributes = self.root.dB.GetRobotAttributes(
            self.robotSelected.get())

        # Création des boutons et labels fixes
        self.label = tk.Label(self.titleFrame, textvariable=self.titre)
        self.label.config(font=self.root.fontTitle, bg=self.root.defaultbg)
        self.label.pack(pady=self.root.titlePadY)

        self.label = tk.Label(self.buttonFrame,
                              textvariable=self.selectedGearLabel)
        self.label.config(font=self.fontGear,
                          bg='white',
                          borderwidth=3,
                          relief="groove",
                          width=2,
                          height=1)
        self.label.pack()

        self.button = tk.Button(self.buttonFrame,
                                text="▲",
                                command=self.Upshift)
        self.button.config(font=self.fontGearButton,
                           borderwidth=3,
                           width=5,
                           height=3,
                           bg='lightgrey')
        self.button.pack()

        self.button = tk.Button(self.buttonFrame,
                                text="▼",
                                command=self.Downshift)
        self.button.config(font=self.fontGearButton,
                           borderwidth=3,
                           width=5,
                           height=3,
                           bg='lightgrey')
        self.button.pack()

        self.label = tk.Label(self.sensorFrame, text="Capteur")
        self.label.config(font=self.fontSensorTitle, bg=self.root.defaultbg)
        self.label.grid(column=1, row=1, sticky='w')

        self.label = tk.Label(self.sensorFrame, text="Robot")
        self.label.config(font=self.fontSensorTitle, bg=self.root.defaultbg)
        self.label.grid(column=2, row=1, sticky='w')

        self.label = tk.Label(self.sensorFrame, text="Nominal")
        self.label.config(font=self.fontSensorTitle, bg=self.root.defaultbg)
        self.label.grid(column=3, row=1, sticky='w')

        # Ajout de l'image du levier de vitesse pour le nombre de vitesse du robot
        self.image = Image.open(
            self.root.imageDict['Shifter'][self.robotAttributes['Gears']])
        self.render = ImageTk.PhotoImage(self.image)
        self.imgLabel = tk.Label(self.shifterFrame,
                                 image=self.render,
                                 bg=self.root.defaultbg)
        self.imgLabel.grid(column=0,
                           columnspan=str(self.robotAttributes['Gears'] // 2 +
                                          1),
                           row=2)

        # Création des boutons de sélection des vitesses
        self.shifterButtonList.append(
            tk.Button(self.shifterFrame,
                      text='R',
                      command=lambda: self.SelectGear('R')))
        self.shifterButtonList[0].config(font=self.shifterButtonFont,
                                         width=self.shifterButtonWidth,
                                         height=self.shifterButtonHeight)
        self.shifterButtonList[0].grid(column=0, row=1)
        self.shifterButtonList.append(
            tk.Button(self.shifterFrame,
                      text='N',
                      command=lambda: self.SelectGear('N')))
        self.shifterButtonList[1].config(font=self.shifterButtonFont,
                                         width=self.shifterButtonWidth,
                                         height=self.shifterButtonHeight)
        self.shifterButtonList[1].grid(column=2, row=2)

        self.button = tk.Button(self.masterFrame,
                                text="Retour",
                                command=self.Retour)
        self.button.config(font=self.root.fontButton, bg='lightgrey')
        self.button.place(relx=self.root.retourRelX, rely=self.root.retourRelY)

    # Fonction pour ouvrir la fenêtre
    def Open(self):
        SwitchWindow(self.masterFrame, self.root)
        self.Refresh()
        if self.refreshingThread == None:
            self.refreshingThread = Thread('refreshingThread',
                                           self.SensorRefresh, 0.5)
            self.refreshingThread.start()

    def Retour(self):
        self.root.interface.GPIOReset()
        self.root.mainMenuWindow.Open()

    # Fonction pour monter un rapport
    def Upshift(self):
        if self.selectedGearLabel.get() == 'R':
            self.selectedGearLabel.set('N')
            self.selectedGear = 0
        elif self.selectedGearLabel.get() == 'N':
            self.selectedGearLabel.set('1')
            self.selectedGear = 1
        elif int(self.selectedGearLabel.get()) < (
                self.robotAttributes['Gears'] - 1):
            self.selectedGear += 1
            self.selectedGearLabel.set(self.selectedGear)
        self.Refresh()

    # Fonction pour changer le rapport
    def SelectGear(self, gear):
        if gear == 'R':
            self.selectedGearLabel.set('R')
            self.selectedGear = -1
        elif gear == -1:
            self.selectedGearLabel.set('R')
            self.selectedGear = -1
        elif gear == 'N':
            self.selectedGearLabel.set('N')
            self.selectedGear = 0
        elif gear == 0:
            self.selectedGearLabel.set('N')
            self.selectedGear = 0
        elif gear < (self.robotAttributes['Gears'] - 1):
            self.selectedGear = gear
            self.selectedGearLabel.set(gear)
        else:
            self.selectedGear = self.robotAttributes['Gears'] - 1
            self.selectedGearLabel.set(self.robotAttributes['Gears'] - 1)
        self.Refresh()

    # Fonction pour descendre un rapport
    def Downshift(self):
        if self.selectedGearLabel.get() == 'N':
            self.selectedGearLabel.set('R')
            self.selectedGear = -1
        elif self.selectedGearLabel.get() == '1':
            self.selectedGearLabel.set('N')
            self.selectedGear = 0
        elif self.selectedGearLabel.get() != 'R':
            self.selectedGear -= 1
            self.selectedGearLabel.set(self.selectedGear)
        self.Refresh()

    def Refresh(self):

        # Rafraichissement du robot sélectionné
        self.robotSelected = self.root.mainMenuWindow.robotSelected
        self.titre.set("Diagnostic manuel du robot " +
                       str(self.robotSelected.get()))
        self.robotAttributes = self.root.dB.GetRobotAttributes(
            self.robotSelected.get())

        # Changement de l'image
        self.image = Image.open(
            self.root.imageDict['Shifter'][self.robotAttributes['Gears']])
        self.render = ImageTk.PhotoImage(self.image)
        self.imgLabel.config(image=self.render, bg=self.root.defaultbg)
        self.imgLabel.grid(column=0,
                           columnspan=str(self.robotAttributes['Gears'] // 2 +
                                          1),
                           row=2)

        # Suppression des anciens capteurs
        for i in range(len(self.sensorLabelList)):
            self.sensorLabelList[-1].destroy()
            self.sensorLabelList.pop()
            self.sensorRobotLabelList[-1].destroy()
            self.sensorRobotLabelList.pop()
            self.sensorGearLabelList[-1].destroy()
            self.sensorGearLabelList.pop()
        for key in self.sensorRobotLabelListVarDict:
            for subKey in self.sensorRobotLabelListVarDict[key]:
                self.sensorRobotLabelListVarDict[key][subKey].set(None)
            self.sensorRobotLabelListVarDict[key] = {}
        self.sensorRobotLabelListVarDict = {}

        # Création des nouveaux labels
        sensors = self.robotAttributes['Sensors']
        for category in sensors:
            for subCategory in sensors[category]:
                self.sensorLabelList.append(
                    tk.Label(self.sensorFrame,
                             text=category + ' ' + subCategory + ":"))
                self.sensorLabelList[-1].config(font=self.root.fontSensor,
                                                bg=self.root.defaultbg)
                self.sensorLabelList[-1].grid(row=i + 2, column=1, sticky='w')
                try:
                    self.sensorRobotLabelListVarDict[category][
                        subCategory] = tk.StringVar()
                except:
                    self.sensorRobotLabelListVarDict[category] = {}
                    self.sensorRobotLabelListVarDict[category][
                        subCategory] = tk.StringVar()
                self.sensorRobotLabelListVarDict[category][subCategory].set(0)
                self.sensorRobotLabelList.append(
                    tk.Label(
                        self.sensorFrame,
                        textvariable=self.sensorRobotLabelListVarDict[category]
                        [subCategory]))
                self.sensorRobotLabelList[-1].config(font=self.root.fontValues,
                                                     bg='white',
                                                     borderwidth=2,
                                                     relief="groove",
                                                     width=10)
                self.sensorRobotLabelList[-1].grid(row=i + 2, column=2)
                if self.root.interface.sensorClass[category][
                        subCategory].GetNominalValue(sensor) != None:
                    self.sensorGearLabelList.append(
                        tk.Label(self.sensorFrame,
                                 text=self.root.interface.sensorClass[category]
                                 [subCategory].GetNominalValue(
                                     sensor, self.selectedGear)))
                    self.sensorGearLabelList[-1].config(
                        font=self.root.fontValues,
                        bg='white',
                        borderwidth=2,
                        relief="groove",
                        width=10)
                else:
                    self.sensorGearLabelList.append(
                        tk.Label(self.sensorFrame, text=''))
                    self.sensorGearLabelList[-1].config(
                        font=self.root.fontValues,
                        borderwidth=2,
                        relief="groove",
                        width=10,
                        bg=self.root.defaultbg)
                self.sensorGearLabelList[-1].grid(row=i + 2, column=3)

        # Destruction des anciens bouttons jusqu'au neutre
        while len(self.shifterButtonList) != 1:
            button = self.shifterButtonList[-1]
            button.destroy()
            self.shifterButtonList.pop()

        # Création du nombre de boutons nécessaires
        for i in range(self.robotAttributes['Gears']):
            gear = i
            if gear == 0:
                button = tk.Button(self.shifterFrame,
                                   text='N',
                                   command=partial(self.SelectGear, 0))
                if self.robotAttributes['Gears'] < 4:
                    button.grid(row=2, column=1)
                elif self.robotAttributes['Gears'] < 6:
                    button.grid(row=2, column=1, columnspan=2)
                else:
                    button.grid(row=2, column=2)
            else:
                button = tk.Button(self.shifterFrame,
                                   text=gear,
                                   command=partial(self.SelectGear, gear))
                if gear % 2 == 1:
                    button.grid(row=1, column=(gear + 1) // 2)
                if gear % 2 == 0:
                    button.grid(row=3, column=(gear + 1) // 2)
            button.config(font=self.shifterButtonFont,
                          width=self.shifterButtonWidth,
                          height=self.shifterButtonHeight)
            self.shifterButtonList.append(button)

        # Coloration des boutons de sélection du rapport
        for i in range(len(self.shifterButtonList)):
            button = self.shifterButtonList[i]
            if (i - 1) == self.selectedGear:
                button.config(bg='green')
            else:
                button.config(bg='lightgrey')

    def SensorRefresh(self):
        if self.root.activeFrame == self.masterFrame:
            try:
                for key in self.sensorRobotLabelListVarDict:
                    for subKey in self.sensorRobotLabelListVarDict[key]:
                        self.sensorRobotLabelListVarDict[key][subKey].set(
                            self.root.interface.sensorValue[key + ' ' +
                                                            subKey])
            except:
                None
Example #23
0
                servo_index_x += (servo_target - servo_index_x) * 0.005
            LOCK.release()

            SERVO.set(0, servo_index_x)
            time.sleep(0.001)

    except KeyboardInterrupt:
        print("Control thread ended!")


# Init script
STEPPER.start()
STEPPER.enable(False)

LOCK = threading.Lock()
CONTROL_THREAD = Thread()
CONTROL_THREAD.setRunFunction(control_loop)
CONTROL_THREAD.start()

# Global variables
CURRENT_TIME = time.time()
DELAY_IMAGES = 5
NEXT_TIME = CURRENT_TIME + DELAY_IMAGES

# Camera
IMAGE = None
DEFINITION_MULTIPLIER = 1
CAMERA = PiCamera()
CAMERA.resolution = (int(1024 * 1.5), int(768 * 1.5))
CAMERA.framerate = 32
TRACKING_SCREEN = [
Example #24
0
class ManualDiagnosisWindow():
    def __init__(self, root):

        # Définition de la fenêtre Parent
        self.root = root

        # Création de la frame qui contient la page
        self.masterFrame = tk.Frame(self.root, bg=self.root.defaultbg)

        # Création des cadres
        self.titleFrame = tk.Frame(self.masterFrame, bg=self.root.defaultbg)
        self.centerFrame = tk.Frame(self.masterFrame,
                                    relief='groove',
                                    bd=3,
                                    bg=self.root.defaultbg)

        # Placement des cadres
        self.titleFrame.pack(side='top')
        self.centerFrame.pack(side='top', pady=115)

        # Déclaration des variables
        self.titre = tk.StringVar()
        self.robotSelected = tk.StringVar()
        self.activationTime = 0.5
        self.robotAttributes = None
        self.refreshingThread = None
        self.sensorMinMaxDict = {}
        self.actuatorButtonDict = {}
        self.animatedLabelDict = {}
        self.sensorLabelDict = {}
        self.sensorLabelVarDict = {}
        self.motorState = False

        # Paramètres
        self.fontTitleSensor = font.Font(size=20, weight='bold')
        self.fontSensor = font.Font(size=19, weight='bold')

    def Setup(self):

        # Création des boutons et labels fixes
        label = tk.Label(self.titleFrame,
                         textvariable=self.titre,
                         bg=self.root.defaultbg)
        label.config(font=self.root.fontTitle)
        label.pack(pady=self.root.titlePadY)

        button = tk.Button(self.masterFrame, text="Retour", command=self.Close)
        button.config(font=self.root.fontButton)
        button.place(relx=self.root.retourRelX, rely=self.root.retourRelY)

    def Open(self):
        #retour = Popup(self, 2, texte= "ATTENTION: Ce menu est reservé au personnel habilité", valider= "Continuer", fermer= "Retour")
        #if retour == False:
        #    return
        SwitchWindow(self.masterFrame, self.root)
        self.Refresh()
        if self.refreshingThread == None:
            self.refreshingThread = Thread('refreshingThread',
                                           self.SensorRefresh, 0.1)
            self.refreshingThread.start()

    def Close(self):
        self.root.interface.GPIOReset()
        self.root.mainMenuWindow.Open()

    def Refresh(self):

        # Rafraichissement du robot sélectionné
        self.robotSelected = self.root.mainMenuWindow.robotSelected
        self.titre.set("Diagnostic manuel du robot " +
                       str(self.robotSelected.get()))
        self.robotAttributes = self.root.dB.GetRobotAttributes(
            self.robotSelected.get())

        # Destruction de l'ancienne interface
        self.centerFrame.destroy()
        for key in self.sensorLabelDict:
            for i in range(len(self.sensorLabelDict[key])):
                j = len(self.sensorLabelDict[key]) - 1 - i
                self.sensorLabelDict[key][j][0].destroy()
                self.sensorLabelDict[key][j][1].destroy()
                self.sensorLabelDict[key].pop()
        self.sensorLabelDict = {}
        for key in self.sensorLabelVarDict:
            self.sensorLabelVarDict[key].set(None)
        self.sensorLabelVarDict = {}
        for key in self.actuatorButtonDict:
            self.actuatorButtonDict[key].destroy()
        self.actuatorButtonDict = {}
        for key in self.animatedLabelDict:
            self.animatedLabelDict[key]['Label'].destroy()
        self.animatedLabelDict = {}

        # Création d'un nouveau cadre
        self.centerFrame = tk.Frame(self.masterFrame,
                                    relief='groove',
                                    bd=3,
                                    bg=self.root.defaultbg)
        self.centerFrame.pack(side='top', pady=115)

        # Création des nouveaux labels
        label = tk.Label(self.centerFrame,
                         text="Capteur",
                         bg=self.root.defaultbg)
        label.config(font=self.fontTitleSensor)
        label.grid(column=1, row=0)

        label = tk.Label(self.centerFrame,
                         text="Actionneur",
                         bg=self.root.defaultbg)
        label.config(font=self.fontTitleSensor, width=13)
        label.grid(column=4, row=0)

        for category in self.robotAttributes['Sensors']:
            for subCategory in self.robotAttributes['Sensors'][category]:
                key = category + ' ' + subCategory.rstrip(' 0123456789')
                try:
                    type(self.sensorLabelDict[key]) == list()
                except:
                    self.sensorLabelDict[key] = []
                self.sensorLabelVarDict[category + ' ' +
                                        subCategory] = tk.StringVar()
                self.sensorLabelVarDict[category + ' ' + subCategory].set(0)
                self.sensorLabelDict[key].append(
                    (tk.Label(self.centerFrame,
                              text=category + ' ' + subCategory + ':',
                              bg=self.root.defaultbg),
                     tk.Label(
                         self.centerFrame,
                         textvariable=self.sensorLabelVarDict[category + ' ' +
                                                              subCategory],
                         bg=self.root.defaultbg)))
                self.sensorLabelDict[key][-1][0].config(
                    font=self.root.fontSensor)
                self.sensorLabelDict[key][-1][1].config(
                    font=self.root.fontValues,
                    borderwidth=2,
                    bg='white',
                    relief="groove",
                    width=10)

        rowCount = 1
        for key in self.sensorLabelDict:
            rowActuator = rowCount
            for widgets in self.sensorLabelDict[key]:
                if (widgets == self.sensorLabelDict[key][0]) and (len(
                        self.sensorLabelDict[key]) > 1):
                    widgets[0].grid(column=1, row=rowCount, sticky='sw')
                    widgets[1].grid(column=2, row=rowCount, sticky='s')
                elif (widgets == self.sensorLabelDict[key][-1]) and (len(
                        self.sensorLabelDict[key]) > 1):
                    widgets[0].grid(column=1, row=rowCount, sticky='nw')
                    widgets[1].grid(column=2, row=rowCount, sticky='n')
                else:
                    widgets[0].grid(column=1, row=rowCount, sticky='w')
                    widgets[1].grid(column=2, row=rowCount)
                #DEBUT AJOUT
                if 'Vitesse' in key:
                    self.motorButton = tk.Button(self.centerFrame,
                                                 text='▶',
                                                 command=self.SetMotor)
                    self.motorButton.config(
                        width=6,
                        height=3,
                        bg='lightgrey',
                        activebackground=self.root.defaultbg)
                    self.motorButton.grid(column=3, row=rowCount)
                    imageSpeed = Image.open(
                        self.root.imageDict['SpeedBench']['Off'])
                    self.animatedLabelDict[key] = {}
                    self.animatedLabelDict[key][
                        'subType'] = "Boîte de vitesses"
                    self.animatedLabelDict[key]['PrevState'] = "Off"
                    self.animatedLabelDict[key]['ImageNumber'] = 0
                    self.animatedLabelDict[key][
                        'Filepath'] = self.root.imageDict['SpeedBench']
                    self.animatedLabelDict[key]['Image'] = ImageTk.PhotoImage(
                        imageSpeed)
                    self.animatedLabelDict[key]['Label'] = tk.Label(
                        self.centerFrame,
                        image=self.animatedLabelDict[key]['Image'])
                    self.animatedLabelDict[key]['Row'] = rowCount
                    self.animatedLabelDict[key]['Rowspan'] = 1
                    self.animatedLabelDict[key]['Label'].grid(
                        column=4,
                        row=self.animatedLabelDict[key]['Row'],
                        rowspan=self.animatedLabelDict[key]['Rowspan'],
                        sticky='w')
                if 'Pression' in key:
                    self.pressureButton = tk.Button(self.centerFrame,
                                                    text='▼',
                                                    command=self.LowerPressure)
                    self.pressureButton.config(
                        width=6,
                        height=3,
                        bg='lightgrey',
                        activebackground=self.root.defaultbg)
                    self.pressureButton.grid(column=5, row=rowCount)
                #FIN AJOUT
                rowCount += 1
            for category in self.robotAttributes['Actuators']:
                for subCategory in self.robotAttributes['Actuators'][category]:
                    subType = subCategory.rstrip(' +-')
                    if subType in key:
                        if self.root.interface.actuatorClass[category][
                                subCategory].GetOverrideData() != None:
                            column, text = self.root.interface.actuatorClass[
                                category][subCategory].GetOverrideData()
                            try:
                                sensor = self.robotAttributes['Sensors'][
                                    'Position'][subCategory.rstrip('+-') + '1']
                                if sensor['ActuatorType'] == 'S-Cam':
                                    sCat = category
                                    sSubCat = subCategory
                                    self.actuatorButtonDict[
                                        category + ' ' +
                                        subCategory] = tk.Button(
                                            self.centerFrame,
                                            text=text,
                                            command=lambda: self.root.interface
                                            .actuatorClass[sCat][sSubCat].Set(
                                                actuatorType='S-Cam'))
                                else:
                                    self.actuatorButtonDict[
                                        category + ' ' +
                                        subCategory] = tk.Button(
                                            self.centerFrame,
                                            text=text,
                                            command=self.root.interface.
                                            actuatorClass[category]
                                            [subCategory].Set)
                            except:
                                self.actuatorButtonDict[
                                    category + ' ' + subCategory] = tk.Button(
                                        self.centerFrame,
                                        text=text,
                                        command=self.root.interface.
                                        actuatorClass[category]
                                        [subCategory].Set)
                            self.actuatorButtonDict[category + ' ' +
                                                    subCategory].config(
                                                        width=6,
                                                        height=3,
                                                        bg='lightgrey')
                            self.actuatorButtonDict[
                                category + ' ' + subCategory].grid(
                                    column=column,
                                    row=rowActuator,
                                    rowspan=len(self.sensorLabelDict[key]))

                        try:
                            imageActuator = Image.open(
                                self.root.imageDict[category][0])
                            self.animatedLabelDict[category + ' ' +
                                                   subType] = {}
                            self.animatedLabelDict[
                                category + ' ' + subType]['subType'] = subType
                            self.animatedLabelDict[
                                category + ' ' + subType]['ImageNumber'] = None
                            self.animatedLabelDict[category + ' ' + subType][
                                'Filepath'] = self.root.imageDict[category]
                            self.animatedLabelDict[category + ' ' + subType][
                                'Image'] = ImageTk.PhotoImage(imageActuator)
                            self.animatedLabelDict[
                                category + ' ' + subType]['Label'] = tk.Label(
                                    self.centerFrame,
                                    image=self.animatedLabelDict[
                                        category + ' ' + subType]['Image'])
                            self.animatedLabelDict[
                                category + ' ' + subType]['Row'] = rowActuator
                            self.animatedLabelDict[
                                category + ' ' + subType]['Rowspan'] = len(
                                    self.sensorLabelDict[key])
                            self.animatedLabelDict[
                                category + ' ' + subType]['Label'].grid(
                                    column=4,
                                    row=self.animatedLabelDict[category + ' ' +
                                                               subType]['Row'],
                                    rowspan=self.animatedLabelDict[
                                        category + ' ' + subType]['Rowspan'],
                                    sticky='w')
                        except:
                            None

        # Rafraichissement des valeurs min max capteurs
        for category in self.robotAttributes['Sensors']:
            for subCategory in self.robotAttributes['Sensors'][category]:
                sensor = self.robotAttributes['Sensors'][category][subCategory]
                self.sensorMinMaxDict[category + ' ' +
                                      subCategory] = (sensor['Min'],
                                                      sensor['Max'])

        #Remise à zéro du moteur
        self.motorState = False
        self.root.interface.SetMotor(self.motorState)

    def SetAnimationPos(self, label, pos, key):
        key = key.rstrip(" 0123456789")
        pos = pos * label['Filepath']['Nominale']
        pos = trunc(pos)
        if label['ImageNumber'] != None:
            if label['ImageNumber'] == pos:
                return
            elif label['ImageNumber'] > 10 and pos > 10:
                return
            elif label['ImageNumber'] < 0 and pos < 0:
                return
        label['ImageNumber'] = pos
        if pos > 10:
            imageActuator = Image.open(label['Filepath']["ErrHigh"])
            for labelSensor in self.sensorLabelDict[key]:
                labelSensor[1].config(fg='red')
        elif pos < 0:
            imageActuator = Image.open(label['Filepath']["ErrLow"])
            for labelSensor in self.sensorLabelDict[key]:
                labelSensor[1].config(fg='red')
        else:
            imageActuator = Image.open(label['Filepath'][pos])
            for labelSensor in self.sensorLabelDict[key]:
                labelSensor[1].config(fg='black')
        label['Image'] = ImageTk.PhotoImage(imageActuator)
        label['Label'].config(image=label['Image'], bg=self.root.defaultbg)
        label['Label'].grid(column=4,
                            row=label['Row'],
                            rowspan=label['Rowspan'],
                            sticky='w')

    def SensorRefresh(self):

        # Vérification que le menu de diagnostique manuel est en cours d'utilisation
        if self.root.activeFrame == self.masterFrame:
            # L'ensemble est enclavé dans un try / except car il peut y avoir des erreurs non fatales qui stoppent l'affichage des animations (à enlever pour débugger)
            try:
                # Mise à jour des labels avec les valeurs capteur avec les valeurs de sensorValue qui sont mises à jour grâce au thread de RaspberryInterface
                for key in self.sensorLabelVarDict:
                    self.sensorLabelVarDict[key].set(
                        self.root.interface.sensorValue[key])

                # Rafraichissement des labels animés et coloration en rouge des valeurs capteurs si besoin
                for key in self.animatedLabelDict:
                    sensorType = self.animatedLabelDict[key]['subType']
                    for key2 in self.sensorLabelVarDict:
                        if sensorType in key2:
                            value = float(self.sensorLabelVarDict[key2].get())
                            break
                    minValue, maxValue = self.sensorMinMaxDict[key2]
                    minValue = float(minValue)
                    maxValue = float(maxValue)
                    if 'Vitesse' in key:
                        if self.motorState:
                            self.animatedLabelDict[key]['ImageNumber'] += 1
                            if self.animatedLabelDict[key]['ImageNumber'] == 4:
                                self.animatedLabelDict[key]['ImageNumber'] = 0
                            if value < maxValue - 10:
                                imageSpeed = Image.open(
                                    self.animatedLabelDict[key]['Filepath']
                                    ["TooFar"][self.animatedLabelDict[key]
                                               ['ImageNumber']])
                                self.sensorLabelDict[key2][0][1].config(
                                    fg='red')
                                self.animatedLabelDict[key][
                                    'PrevState'] = "TooFar"
                            elif value > maxValue + 10:
                                imageSpeed = Image.open(
                                    self.animatedLabelDict[key]['Filepath']
                                    ["TooClose"][self.animatedLabelDict[key]
                                                 ['ImageNumber']])
                                self.sensorLabelDict[key2][0][1].config(
                                    fg='red')
                                self.animatedLabelDict[key][
                                    'PrevState'] = "TooClose"
                            else:
                                imageSpeed = Image.open(
                                    self.animatedLabelDict[key]['Filepath']
                                    ["Nominal"][self.animatedLabelDict[key]
                                                ['ImageNumber']])
                                self.sensorLabelDict[key2][0][1].config(
                                    fg='black')
                            self.animatedLabelDict[key][
                                'PrevState'] = "Nominal"
                            self.animatedLabelDict[key][
                                'Image'] = ImageTk.PhotoImage(imageSpeed)
                            self.animatedLabelDict[key]['Label'].config(
                                image=self.animatedLabelDict[key]['Image'],
                                bg=self.root.defaultbg)
                            self.animatedLabelDict[key]['Label'].grid(
                                column=4,
                                row=self.animatedLabelDict[key]['Row'],
                                rowspan=self.animatedLabelDict[key]['Rowspan'],
                                sticky='w')
                        elif self.animatedLabelDict[key]['PrevState'] != "Off":
                            imageSpeed = Image.open(
                                self.animatedLabelDict[key]['Filepath']["Off"])
                            self.sensorLabelDict[key2][0][1].config(fg='black')
                            self.animatedLabelDict[key][
                                'Image'] = ImageTk.PhotoImage(imageSpeed)
                            self.animatedLabelDict[key]['Label'].config(
                                image=self.animatedLabelDict[key]['Image'],
                                bg=self.root.defaultbg)
                            self.animatedLabelDict[key]['Label'].grid(
                                column=4,
                                row=self.animatedLabelDict[key]['Row'],
                                rowspan=self.animatedLabelDict[key]['Rowspan'],
                                sticky='w')
                            self.animatedLabelDict[key]['PrevState'] = "Off"
                    else:
                        if (maxValue - minValue) == 0:
                            normValue = 0
                        else:
                            normValue = (value - minValue) / (maxValue -
                                                              minValue)
                        self.SetAnimationPos(self.animatedLabelDict[key],
                                             normValue, key2)

                # Actualisation de la couleur des boutons (vert activé, gris désactivé)
                for category in self.robotAttributes['Actuators']:
                    for subCategory in self.robotAttributes['Actuators'][
                            category]:
                        if self.root.interface.actuatorClass[category][
                                subCategory].position == 1:
                            self.actuatorButtonDict[
                                category + ' ' + subCategory].config(
                                    bg='green', activebackground='lightgreen')
                        else:
                            self.actuatorButtonDict[
                                category + ' ' + subCategory].config(
                                    bg='lightgrey',
                                    activebackground=self.root.defaultbg)
            except:
                None

    def SetMotor(self):
        if self.motorState:
            self.motorState = False
            self.motorButton.config(bg='lightgrey',
                                    activebackground=self.root.defaultbg,
                                    text='▶')
        else:
            self.motorState = True
            self.motorButton.config(bg='green',
                                    activebackground='lightgreen',
                                    text='❚❚')
        self.root.interface.SetMotor(self.motorState)

    def LowerPressure(self):
        self.pressureButton.config(bg='green',
                                   activebackground='lightgreen',
                                   state='disabled')
        self.root.update()
        LowerPressure(self, True)
        self.pressureButton.config(bg='lightgrey',
                                   activebackground=self.root.defaultbg,
                                   state='normal')
Example #25
0
def main():

    global FACE_DETECTOR, stepper_index, CURRENT_FACE, DELAY_IMAGES, NEXT_TIME, IMAGE, DEFINITION_MULTIPLIER, TRACKING_SCREEN, CAPTURE, DELAY_DELETE_IMAGES, LOW_RES_STREAM, index, servo_index_x, gray
    # Init script
    STEPPER.start()
    STEPPER.enable(False)

    # LOCK = threading.Lock()
    # CONTROL_THREAD = Thread()
    # CONTROL_THREAD.setRunFunction(control_loop)
    # CONTROL_THREAD.start()

    # Global variables
    CURRENT_TIME = time.time()
    DELAY_IMAGES = 5
    NEXT_TIME = CURRENT_TIME + DELAY_IMAGES

    # Camera
    IMAGE = None
    DEFINITION_MULTIPLIER = 1
    CAMERA = PiCamera()
    CAMERA.resolution = (int(1024 * 1.5), int(768 * 1.5))
    CAMERA.framerate = 32
    TRACKING_SCREEN = [
        int(160 * DEFINITION_MULTIPLIER),
        int(120 * DEFINITION_MULTIPLIER)
    ]
    CAPTURE = PiRGBArray(CAMERA,
                         size=(int(160 * DEFINITION_MULTIPLIER),
                               int(120 * DEFINITION_MULTIPLIER)))
    DELAY_DELETE_IMAGES = 60  # seconds -> 2min
    LOW_RES_STREAM = CAMERA.capture_continuous(
        CAPTURE,
        format="bgr",
        use_video_port=True,
        splitter_port=2,
        resize=(int(160 * DEFINITION_MULTIPLIER),
                int(120 * DEFINITION_MULTIPLIER)))

    time.sleep(2.0)
    print("done warming up")

    # Remove all old images
    CAN_TAKE_A_PHOTO = False
    SYNC_FOLDER_PATH = "/home/pi/Desktop/RPI_3_sync/"
    file_list = glob.glob(SYNC_FOLDER_PATH + "*.jpg")
    for image in file_list:
        os.remove(image)

    # Run the min loop
    run = True
    try:
        while run:
            # Update current time
            CURRENT_TIME = time.time()

            if FACES is not None:
                if len(FACES) > 0:
                    #print("photo")
                    CAN_TAKE_A_PHOTO = True

            # Take pictures every DELAY_IMAGES
            if CURRENT_TIME >= NEXT_TIME and CAN_TAKE_A_PHOTO:
                CAMERA.capture(SYNC_FOLDER_PATH +
                               str(int(math.floor(time.time() * 1000))) +
                               '.jpg')
                file_list = glob.glob(SYNC_FOLDER_PATH + "*.jpg")
                #print("Image taken: " + str(len(file_list)))
                for image in file_list:
                    name = float(
                        image.split("/")[len(image.split("/")) - 1].replace(
                            ' ', '')[:-4].upper())
                    # Delete images that are older than the DELAY_DELETE_IMAGES
                    if name < CURRENT_TIME - DELAY_DELETE_IMAGES:
                        os.remove(image)

                for i in range(len(file_list), 0):
                    if len(file_list) - i > 20:
                        os.remove(file_list[i])

                NEXT_TIME += DELAY_IMAGES
                CAN_TAKE_A_PHOTO = False

            low_res = LOW_RES_STREAM.next()
            IMAGE = low_res.array
            gray = cv2.cvtColor(IMAGE, cv2.COLOR_BGR2GRAY)

            # Run face detection as soon as one has ended
            if FACE_DETECTOR is None:
                FACE_DETECTOR = Thread()
                FACE_DETECTOR.setRunFunction(face_detection)
                FACE_DETECTOR.start()
            else:
                if FACE_DETECTOR.isAlive() is not True:
                    FACE_DETECTOR = None

            if FACES is not None:
                if len(FACES) > 0:
                    if CURRENT_FACE is None:
                        CURRENT_FACE = FACES[0]

                    # Always check for the closer face to the last one
                    # in order not to jump from a face to another
                    min_distance = float("inf")
                    for face in FACES:
                        distance = math.sqrt(
                            math.pow(CURRENT_FACE[0] - face[0], 2) +
                            math.pow(CURRENT_FACE[1] - face[1], 2))
                        if distance < min_distance:
                            min_distance = distance
                            CURRENT_FACE = face

                    #print(CURRENT_FACE)
                    cv2.circle(IMAGE, (CURRENT_FACE[0] + CURRENT_FACE[2] / 2,
                                       CURRENT_FACE[1] + CURRENT_FACE[3] / 2),
                               int(CURRENT_FACE[2] / 3), (255, 255, 255), 1)
                else:
                    CURRENT_FACE = None

            # Motors control

            #SERVO.set(0, 0.5 - math.sin(index) * 0.1)
            #SERVO.set(0, 0.5)
            stepper_index += 0.001

            # Check if there is a current face to track
            if CURRENT_FACE is not None:
                # print("face")
                face_pos_x = CURRENT_FACE[0] + CURRENT_FACE[2] / 2
                delta_x = (face_pos_x - TRACKING_SCREEN[0] * 0.5) / (
                    TRACKING_SCREEN[0] * 0.5)
                servo_index_x += delta_x * -0.02

                STEPPER.enable(True)

                face_pos_y = CURRENT_FACE[1] + CURRENT_FACE[3] / 2
                delta_y = (face_pos_y - TRACKING_SCREEN[1] * 0.5) / (
                    TRACKING_SCREEN[1] * 0.5)
                STEPPER.setVelocity(delta_y * 2)
            else:
                STEPPER.enable(False)
                index += 0.03
                servo_target = 0.5 - math.sin(index) * 0.3
                servo_index_x += (servo_target - servo_index_x) * 0.1

            SERVO.set(0, servo_index_x)
            time.sleep(0.001)

            CAPTURE.truncate(0)
            # cv2.imshow("Frame", IMAGE)

            key = cv2.waitKey(1) & 0xFF
            if key == ord("q"):
                STEPPER.stop()
                STEPPER.enable(False)
                CONTROL_THREAD.stop()
                run = False
                break
            elif key == ord("r"):
                servo_index_x = 0.45

    except KeyboardInterrupt:
        STEPPER.stop()
        STEPPER.enable(False)
        CONTROL_THREAD.stop()
        run = False
Example #26
0
            CAPTURE.truncate(0)
            # cv2.imshow("Frame", IMAGE)

            key = cv2.waitKey(1) & 0xFF
            if key == ord("q"):
                STEPPER.stop()
                STEPPER.enable(False)
                CONTROL_THREAD.stop()
                run = False
                break
            elif key == ord("r"):
                servo_index_x = 0.45

    except KeyboardInterrupt:
        STEPPER.stop()
        STEPPER.enable(False)
        CONTROL_THREAD.stop()
        run = False


def waitUntilBoot():
    print("Waiting 20 sec")
    time.sleep(20)
    print("Start")
    main()


waitThread = Thread()
waitThread.setRunFunction(waitUntilBoot)
waitThread.start()
Example #27
0
class LogTabWidget(QtWidgets.QWidget):
    def __init__(self, case_name, case_dir, folder_name, rpms, save_data, plot_defaultPostProcess_after_run):
        QtWidgets.QWidget.__init__(self)
        self.ui_tab_widget = Ui_LogTabWidget()
        self.ui_tab_widget.setupUi(self)
        self.set_palette()
        self.case_name          = case_name   # Nombre del caso (permanente)
        self.case_dir           = case_dir    # Directorio donde se ubica el .py del caso (variable)
        self.current_run_dir    = os.path.join(RUNS_PATH,folder_name) # Directorio donde se guarda la corrida (variable)
        self.rpms               = rpms # RPMS a correr (variable)
        self.save_data_f = save_data
        self.plot_defaultPostProcess_after_run_f = plot_defaultPostProcess_after_run
        self.current_log = ''
        self.lastPos = 0
        self.lastlastPos = -1
        self.timer = QtCore.QTimer(self)
        self.timer.setInterval(50)
        self.timer.timeout.connect(self.file_changed)
        self.thread_runSimulation = None
        self.process_killed = False
        return

    def change_attributes(self, folder_name, rpms):
        """
        On saving the case, change the attributes used to simulate (important
        if any of them has changed)
        """
        self.rpms = rpms
        self.current_run_dir = os.path.join(RUNS_PATH,folder_name)
        return

    def set_palette(self):
        """
        Setear el formato del QTextEdit.
        """
        palette = QtGui.QPalette()
        bgc = QtGui.QColor(0, 0, 0)
        palette.setColor(QtGui.QPalette.Base, bgc)
        textc = QtGui.QColor(255, 255, 255)
        palette.setColor(QtGui.QPalette.Text, textc)
        self.setPalette(palette)
        self.ui_tab_widget.logPlainTextEdit.setPalette(palette)
        return

    def load_log(self):
        """
        Cargar un log y mostrarlo en el QTextEdit.
        """
        self.ui_tab_widget.logPlainTextEdit.clear()
        dialog = QtWidgets.QFileDialog(self)
        dialog.setWindowTitle('Select Log')
        if dialog.exec_():
            filename = dialog.selectedFiles()[0]
            with  open(filename) as open_log:
                all_text = open_log.readlines()
                all_text = remove_values_from_list(all_text, '\n')
                for line in all_text:
                    self.ui_tab_widget.logPlainTextEdit.appendPlainText(line)
        return

    def file_changed(self):
        if self.current_log == '':
            return

        if self.lastPos == self.lastlastPos:
            return

        with open(self.current_log, 'r') as openFile:
            openFile.seek(self.lastPos)
            newTexto = openFile.read()
            if(len(newTexto)>1):
                self.ui_tab_widget.logPlainTextEdit.appendPlainText(newTexto)
                QtWidgets.QApplication.processEvents()
                self.lastlastPos = self.lastPos
                self.lastPos = self.lastPos + len(newTexto)
        return            
    
    def init_log(self,path):
        self.current_log = path
        self.timer.start()
        return
    
    def reset_log(self):
        self.file_changed()
        self.current_log = ''
        self.lastPos = 0
        self.lastlastPos = -1
        self.timer.stop()
        return
    
    def kill_process(self):
        """
        Verifica si existe una simulacion corriendo y termina el proceso
        """
        if self.thread_runSimulation:
            self.current_pid = self.thread_runSimulation.get_pid() + 2
            if self.current_pid != -1:
                self.process_killed = True
                errorlog_path = os.path.join(SIMULATOR_PATH,"error.log")
                if 'linux' in platform:
                    command = "kill -KILL %s 2> %s"%(self.current_pid,errorlog_path)
                elif 'win' in platform:
                    command_kill = "taskkill /F /IM exec.exe"
                    execwfile = os.path.join(SIMULATOR_PATH,"execw_k.bat")
                    command = "echo %s > %s"%(command_kill,execwfile)
                    os.system(command)
                    command = os.path.join(SIMULATOR_PATH,"execw_k.bat")
                p = subprocess.Popen([command],shell=True)
                p.wait()
                if not show_errors(SIMULATOR_PATH):
                    show_message('Process Killed', 1)
                    QtWidgets.QApplication.processEvents()
                    self.reset_pid()
            else:
                show_message('Cannot find the pid simulation. Please report this bug to the developer.')
        else:
            show_message('There is no simulation running now')
        return

    def reset_pid(self):
        self.current_pid = -1
        self.thread_runSimulation = None
        return

    def success_simulation(self):
        if not show_errors(SIMULATOR_PATH) and not self.process_killed:
            show_message('Simulation Finished', 1)
            msg = "Do you want to generate the default Post Process?"
            reply = show_message(msg,4,QtWidgets.QMessageBox.Yes|QtWidgets.QMessageBox.No)
            if reply == QtWidgets.QMessageBox.Yes:
                self.plot_defaultPostProcess_after_run_f()
        self.process_killed = False
        return
    
    def show_info(self):
        """
        Shows the current rpm folder located and the ones to calculate
        """
        # Folders located
        msg = 'RPM(s) already simulated: \n'
        if os.path.isdir(self.current_run_dir):
            rpm_folders = [f.replace('RPM_','') for f in os.listdir(self.current_run_dir) if 'RPM_' in f]
            for irpm in rpm_folders:
                msg += '- %s \n'%irpm
        else:
            msg += '- None \n'
        msg += '\n RPM(s) to simulate: \n'
        for irpm in self.rpms:
            msg += '- %s \n'%irpm
        show_message(msg,1)
        return

    def run_simulation(self):
        """
        Iniciar el simulador de ICESym
        """

        # TODO: Verificar si hay componentes desconectados
        
        simulator = None
        if 'linux' in platform:
            simulator = os.path.join(SIMULATOR_PATH,"exec")
        elif 'win' in platform:
            simulator = os.path.join(SIMULATOR_PATH,"exec.exe")
        if not simulator or not os.path.isfile(simulator):
            show_message('Cannot find exec file. Please, create this file to run the simulator')
            return

        # Salvar el caso
        self.save_data_f(None,True)

        logfile = os.path.join(SIMULATOR_PATH,'run.log')
        errorlogfile = os.path.join(SIMULATOR_PATH,'error.log')
        if 'linux' in platform:
            command = "%s %s %s 1> %s 2> %s"%(simulator,self.case_dir,self.case_name,logfile,errorlogfile)
        elif 'win' in platform:
            command = "echo.> %s"%logfile
            os.system(command)
            while not os.path.isfile(logfile):
                None
            command_ex = "%s %s %s 1^> %s 2^> %s"%(simulator,self.case_dir,self.case_name,logfile,errorlogfile)
            execwfile = os.path.join(SIMULATOR_PATH,'execw.bat')
            command = "echo %s > %s"%(command_ex,execwfile)
            os.system(command)
            while not os.path.isfile(execwfile):
                None
            command = os.path.join(SIMULATOR_PATH,'execw.bat')

        self.thread_runSimulation = Thread(command)
        # limpio el log y agrego el archivo al watcher
        self.ui_tab_widget.logPlainTextEdit.clear()
        self.thread_runSimulation.started.connect(lambda: self.init_log(logfile))
        self.thread_runSimulation.started.connect(self.show_info)
        self.thread_runSimulation.finished.connect(self.reset_log)
        self.thread_runSimulation.finished.connect(self.reset_pid)
        self.thread_runSimulation.finished.connect(self.success_simulation)
        # inicio el thread
        self.thread_runSimulation.start()
        return
Example #28
0
class Change_UI(Ui_MainWindow):
    def __init__(self, MainWindow):
        self.setupUi(MainWindow)
        self.ExecuteObject = [
            self.vc2015to19x86, self.vc2015to19x64, self.vc2013x86,
            self.vc2013x64, self.vc2012x86, self.vc2012x64, self.vc2010x86,
            self.vc2010x64, self.vc2008x86, self.vc2008x64
        ]
        self.SelectAll.stateChanged.connect(self.SelectAllOption)
        self.Install.clicked.connect(self.InstallAllOptioned)

    def InstallAllOptioned(self):
        self.Install.setDisabled(True)
        self.InstallThread = Thread({
            'vc2015-2019_x86.exe':
            self.vc2015to19x86.isChecked(),
            'vc2015-2019_x64.exe':
            self.vc2015to19x64.isChecked(),
            'vc2013_x86.exe':
            self.vc2013x86.isChecked(),
            'vc2013_x64.exe':
            self.vc2013x64.isChecked(),
            'vc2012_x86.exe':
            self.vc2012x86.isChecked(),
            'vc2012_x64.exe':
            self.vc2012x64.isChecked(),
            'vc2010_x86.exe':
            self.vc2010x86.isChecked(),
            'vc2010_x64.exe':
            self.vc2010x64.isChecked(),
            'vc2008_x86.exe':
            self.vc2008x86.isChecked(),
            'vc2008_x64.exe':
            self.vc2008x64.isChecked()
        })
        self.InstallThread.EmptyOption.connect(self.EmptyOptionTip)
        self.InstallThread.UnzipFile.connect(self.UnzipFileTip)
        self.InstallThread.Installing.connect(self.InstallingTip)
        self.InstallThread.InstallFinish.connect(self.InstallFinishTip)
        self.InstallThread.start()

    def EmptyOptionTip(self):
        self.InstallTip.setText("你还未选择组件...")
        self.Install.setDisabled(False)

    def UnzipFileTip(self):
        self.InstallTip.setText("正在解压文件...")

    def InstallingTip(self):
        self.InstallTip.setText("正在安装程序,请耐心等待...")

    def InstallFinishTip(self):
        self.InstallTip.setText("安装完成...")
        self.Install.setDisabled(False)

    def SelectAllOption(self):
        if self.SelectAll.isChecked():
            for i in self.ExecuteObject:
                i.setChecked(True)
        else:
            for i in self.ExecuteObject:
                i.setChecked(False)
Example #29
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.setGeometry(250, 250, 600, 300)
        self.setWindowTitle("TenElevenGames OXO")
        self.setWindowIcon(QIcon("icon.jpg"))
        self.show()

        # NERDZONE
        # implement a simple help menu
        # create QAction buttons for the menu
        Instructions = QAction("How to play", self)
        AboutGame = QAction("About", self)
        More = QAction("More", self)

        # add the buttons to the menu
        menu = QMenuBar()
        menu.addAction(Instructions)
        menu.addAction(AboutGame)
        menu.addAction(More)

        # connect the buttons to their respective methods
        # when clicked, each button is supposed to show a popup dialogue
        # with the relevant information as per the name of the button suggests
        Instructions.triggered.connect(self.instructions)
        AboutGame.triggered.connect(self.about)
        More.triggered.connect(self.more)

        # images
        self.cross = QPixmap("cross.gif")
        self.nought = QPixmap("nought.gif")
        self.blank = QtGui.QIcon("blank.gif")

        # create a thread to run parallel to the gui
        self.messageThread = Thread()
        self.messageThread.signalLine.connect(self.threadLine)

        # Game board
        # create game buttons and set their sizes when window changes size
        # connect each button to it's OWN method
        self.buttonArray = []
        # first row
        self.button1 = QPushButton()
        self.button1.setIcon(QtGui.QIcon('blank.gif'))
        self.button1.setIconSize(QtCore.QSize(60, 85))
        self.buttonArray.append(self.button1)
        self.button1.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        self.button1.clicked.connect(self.button1Event)

        self.button2 = QPushButton()
        self.button2.setIcon(QtGui.QIcon('blank.gif'))
        self.button2.setIconSize(QtCore.QSize(60, 85))
        self.buttonArray.append(self.button2)
        self.button2.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        self.button2.clicked.connect(self.button2Event)

        self.button3 = QPushButton()
        self.button3.setIcon(QtGui.QIcon('blank.gif'))
        self.button3.setIconSize(QtCore.QSize(60, 85))
        self.buttonArray.append(self.button3)
        self.button3.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        self.button3.clicked.connect(self.button3Event)
        #
        # second row
        self.button4 = QPushButton()
        self.button4.setIcon(QtGui.QIcon('blank.gif'))
        self.button4.setIconSize(QtCore.QSize(60, 85))
        self.buttonArray.append(self.button4)
        self.button4.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        self.button4.clicked.connect(self.button4Event)

        self.button5 = QPushButton()
        self.button5.setIcon(QtGui.QIcon('blank.gif'))
        self.button5.setIconSize(QtCore.QSize(60, 85))
        self.buttonArray.append(self.button5)
        self.button5.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        self.button5.clicked.connect(self.button5Event)

        self.button6 = QPushButton()
        self.button6.setIcon(QtGui.QIcon('blank.gif'))
        self.button6.setIconSize(QtCore.QSize(60, 85))
        self.buttonArray.append(self.button6)
        self.button6.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        self.button6.clicked.connect(self.button6Event)
        #
        # third row
        self.button7 = QPushButton()
        self.button7.setIcon(QtGui.QIcon('blank.gif'))
        self.button7.setIconSize(QtCore.QSize(60, 85))
        self.buttonArray.append(self.button7)
        self.button7.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        self.button7.clicked.connect(self.button7Event)

        self.button8 = QPushButton()
        self.button8.setIcon(QtGui.QIcon('blank.gif'))
        self.button8.setIconSize(QtCore.QSize(60, 85))
        self.buttonArray.append(self.button8)
        self.button8.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        self.button8.clicked.connect(self.button8Event)

        self.button9 = QPushButton()
        self.button9.setIcon(QtGui.QIcon('blank.gif'))
        self.button9.setIconSize(QtCore.QSize(60, 85))
        self.buttonArray.append(self.button9)
        self.button9.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        self.button9.clicked.connect(self.button9Event)
        #
        self.Quit = QPushButton("Quit")
        self.Quit.setShortcut("ctrl+v")
        self.Quit.setToolTip("Exit the game: ctrl+v")
        self.Quit.resize(10, 10)
        # self.Quit.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.Quit.clicked.connect(self.quit)
        self.connectServer = QPushButton("Connect")
        self.connectServer.setShortcut("ctrl+e")
        self.connectServer.setToolTip("Connect to the server: ctrl+e")
        self.connectServer.clicked.connect(self.connectEvent)

        self.messageBox = QTextEdit()
        self.messageBox.setSizePolicy(QSizePolicy.Expanding,
                                      QSizePolicy.Expanding)
        # ensure that the QTextEdit allows for reading messages only, no typing/editing. "lock" the QTextEdit.
        self.messageBox.setReadOnly(True)

        # server entry
        self.label = QLabel("Enter server: ")
        self.label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.getServer = QLineEdit('127.0.0.1')

        # player character display
        self.character = QLabel("Game Character: ")
        self.pixmap = QPixmap('cross.gif')
        self.pixmap2 = QPixmap("nought.gif")
        self.picLabel = QLabel()
        self.picLabel.setSizePolicy(QSizePolicy.Expanding,
                                    QSizePolicy.Expanding)

        # enhancement
        # will most probably remove this later on
        self.comboBox = QComboBox()
        self.comboBox.addItems(
            ['Pink', 'Grey', 'Red', 'Orange', 'Yellow', 'Purple'])
        self.comboBox.activated.connect(self.setColour)
        self.setStyleSheet("background-color: pink")
        self.messageBox.setStyleSheet('background-color: white')
        self.getServer.setStyleSheet('background-color: white')
        # self.comboBox.setStyleSheet('background-color: white')

        hbox = QHBoxLayout()
        hbox.addWidget(menu)
        hbox2 = QWidget()
        hbox2.setLayout(hbox)

        # present everything in a Gridlayout
        # making sure to set span width and length (rows, columns) to avoid overlapping
        grid = QGridLayout()
        grid.addWidget(hbox2, 0, 4, 1, 3)
        grid.addWidget(self.label, 1, 0, 1, 1)
        grid.addWidget(self.getServer, 1, 1, 1, 1)
        grid.addWidget(self.connectServer, 1, 2, 1, 1)
        grid.addWidget(self.comboBox, 1, 3, 1, 1)
        #
        grid.addWidget(self.button1, 2, 0, 1, 1)
        grid.addWidget(self.button2, 2, 1, 1, 1)
        grid.addWidget(self.button3, 2, 2, 1, 1)
        #
        grid.addWidget(self.button4, 3, 0, 1, 1)
        grid.addWidget(self.button5, 3, 1, 1, 1)
        grid.addWidget(self.button6, 3, 2, 1, 1)
        #
        grid.addWidget(self.button7, 4, 0, 1, 1)
        grid.addWidget(self.button8, 4, 1, 1, 1)
        grid.addWidget(self.button9, 4, 2, 1, 1)
        #
        grid.addWidget(self.messageBox, 2, 3, 3, 4)
        grid.addWidget(self.character, 5, 1, 1, 1)
        grid.addWidget(self.picLabel, 5, 2, 1, 1)
        grid.addWidget(self.Quit, 5, 5, 1, 1)
        #
        self.setLayout(grid)
Example #30
0
def main():

    my_tread = Thread()
    my_tread.run()