def _start_the_worker(worker: Thread) -> None:
     """
         We want only 1 thread running per service
         at a time
     """
     if not worker.alive():
         worker.start()
Example #2
0
def main():
    # Spawn a new thread that runs sleepy
    t = Thread(target=sleepy, args=(0, ))
    try:
        # Start the thread
        t.start()
        # If the child thread is still running
        while t.is_alive():
            # Try to join the child thread back to parent for 0.5 seconds
            t.join(0.5)
    # When ctrl+c is received
    except KeyboardInterrupt as e:
        # Try to exit FIRST
        sys.exit()
        # Set the alive attribute to false
        t.alive = False
        # Block until child thread is joined back to the parent
        t.join()
def main():
	# Spawn a new thread that runs sleepy
	t = Thread(target=sleepy, args=(0,))
	try:
		# Start the thread
		t.start()
		# If the child thread is still running
		while t.is_alive():
			# Try to join the child thread back to parent for 0.5 seconds
			t.join(0.5)
	# When ctrl+c is received
	except KeyboardInterrupt as e:
		# Set the alive attribute to false
		t.alive = False
		# Block until child thread is joined back to the parent
		t.join()
		# Exit with error code
		sys.exit(e)
Example #4
0

def _process_async_queue():
    t = _current_thread()
    t.alive = True
    while t.alive:
        function, args, kwargs = _task_queue.get()
        if function:
            function(*args, **kwargs)
    if _log.isEnabledFor(_DEBUG):
        _log.debug("stopped")


_queue_processor = Thread(name='AsyncUI', target=_process_async_queue)
_queue_processor.daemon = True
_queue_processor.alive = False
_queue_processor.start()

del Thread


def async (function, *args, **kwargs):
    task = (function, args, kwargs)
    _task_queue.put(task)


#
#
#

from . import notify, tray, window
Example #5
0
def doNd(param_set, 
         spaces, 
         settle_times, 
         param_meas, 
         name='', 
         comment='', 
         meander=False, 
         extra_cmd=None, 
         extra_cmd_val=None,
         wait_first_datapoint=1,
         checkstepinterdelay=True,
         manualsetpoints=False):
    if manualsetpoints == False:
        if len(param_set) is not len(spaces):
            errstr = 'Error: number of param_set is ' + str(len(param_set)) + ', while number of spaces is ' + str(len(spaces)) + '.'
            sys.exit(errstr)
    if manualsetpoints == True:
        if isinstance(spaces,np.ndarray) == False:
            errstr = 'Error: spaces is of type '+ str(type(spaces)) +' not a numpy error as required when manualsetpoints=True.'    
            sys.exit(errstr)
        elif len(param_set) is not spaces.shape[1]:
            errstr = 'Error: number of param_set is ' + str(len(param_set)) + ', while dimension of spaces array is ' + str(spaces.shape[1]) + '.'
            sys.exit(errstr)
    
    if len(param_set) is not len(settle_times):
        errstr = 'Error: number of param_set is ' + str(len(param_set)) + ', while number of settle_times is ' + str(len(settle_times)) + '.' 
        sys.exit(errstr)
    # Register measid as global parameter
    global measid
    measid = None

    # Useless if statement, because why not        
    if __name__ != '__main__':
        #Create Event
        event = Event() # Create event shared by threads
        
        # Define p1 (run_measurement) and p2 (run_dbextractor) as two function to thread
        if param_set:
            p1 = Thread(target = run_measurement, args=(event, 
                                                        param_set, 
                                                        param_meas, 
                                                        spaces, 
                                                        settle_times, 
                                                        name, 
                                                        comment, 
                                                        meander, 
                                                        extra_cmd, 
                                                        extra_cmd_val, 
                                                        wait_first_datapoint,
                                                        checkstepinterdelay,
                                                        manualsetpoints))
        else:
            p1 = Thread(target = run_zerodim, args=(event, 
                                                    param_meas, 
                                                    name, 
                                                    comment,
                                                    wait_first_datapoint))
        # Set writeinterval db_extractor
        dbextractor_write_interval = 30 #sec
        p2 = Thread(target = run_dbextractor, args=(event,dbextractor_write_interval))
        
        # Kill main thread is subthreads are killed, not necessary here I think..
        #p1.daemon = True
        #p2.daemon = True
        
        #Starting the threads in a try except to catch kernel interrupts
        try:
            # Start the threads
            p1.start()
            p2.start()
            # If the child thread is still running
            while p1.is_alive():
                # Try to join the child thread back to parent for 0.5 seconds
                p1.join(0.5)
                p2.join(0.5)
        # When kernel interrupt is received (as keyboardinterrupt)
        except KeyboardInterrupt as e:
            # Set the alive attribute to false
            p1.alive = False
            p2.alive = False
            # Block until child thread is joined back to the parent
            p1.join()
            p2.join(5)
            # Exit with error code
            sys.exit(e)
    qctools.db_extraction.db_extractor(dbloc = qc.dataset.sqlite.database.get_DB_location(), 
                                       ids=[measid], 
                                       overwrite=True,
                                       newline_slowaxes=True,
                                       no_folders=False,
                                       suppress_output=True,
                                       useopendbconnection = True)
    if len(param_set) > 2:
        print('QCoDeS currently does not support plotting of higher dimensional data, plotting skipped.')
    else:
        plot_by_id(measid)
Example #6
0
def server_option() -> None:
    """
    "Server" main menu option.
    """

    # Instantiates a brand new server.
    server = Server(GREEN)

    try:
        while True:
            print(F().blue(title()))
            print(_l(F().blue('Configure the connection for this server.')))

            try:

                # Waits for the user to provide the server port number.
                port = input(
                    _lt('Port number [{}]: '.format(
                        F().bold().magenta(DEFAULT_PORT))))

                print()

                # Sets the feedback animation thread...
                thread = Thread(target=ellipsis,
                                args=(_l('Starting'), F().yellow()),
                                daemon=True)

                # ... and starts it.
                thread.start()

                try:

                    # Binds the port number to the server and tries to connect.
                    server.connect(port=port)

                # Ctrl+C pressed.
                except (EOFError, KeyboardInterrupt):

                    # Stops the feedback animation thread.
                    thread.alive = False

                    print(_lt(_lt(error('Operation canceled by the user!'))))
                    press_enter_to('try again', F().red(), F().white())

                    continue

                # Stops the feedback animation thread when the connection is established.
                thread.alive = False

                print(_lt(_lt(success('Server started successfully!'))))
                press_enter_to('continue', F().green(), F().white())

                break

            # Port is not valid.
            except InvalidPortError:
                err = 'The provided port number is invalid!'

            # Port is already in use.
            except PortAlreadyUsedError as _e:
                err = 'The port number {:d} is already in use!'.format(_e.port)

            # Port number out of range.
            except PortOutOfRangeError:
                err = 'The port number must be between 0 and 65535!'

            # Stops the feedback animation thread.
            thread.alive = False

            print(_lt(_lt(error(err))))
            press_enter_to('try again', F().red(), F().white())

        server.log(F().green(title(clear_screen=False)))

        # Gets the connection address.
        host, port = server.address()

        # Shows the address in the log.
        server.log(
            _lt(
                label(F().bold().green(
                    'Connection established at {}:{}!'.format(host, port)))))

        # Info message.
        server.log(_lt(label(F().cyan('Recording audio through microphone'))))
        server.log(_lt(label(F().bold().blue('Press Ctrl+C to shutdown'))))

        try:

            # Runs this until Ctrl+C is pressed.
            while True:

                # Accepts a new client.
                client = server.hello()

                # Starts the thread that handles this client.
                Thread(target=handle_client,
                       args=(
                           server,
                           client,
                       ),
                       daemon=True).start()

        # Ctrl+C pressed.
        except (EOFError, KeyboardInterrupt):
            server.log(_ltb(label(error('Closing connection...'))))

            # Shutdowns the server.
            server.disconnect()

            press_enter_to('back to main menu', F().red(), F().white())

    # Ctrl+C pressed.
    except (EOFError, KeyboardInterrupt):
        pass

    # Shutdowns the server.
    server.disconnect()

    del server
Example #7
0
def connect(client: Client) -> None:
    """
    "Connect to a server" client menu option.

    ---
    Arguments
    ---

        client (Client)
    The client instance which wants to connect to a server.
    """

    # Asks the user for the modulation type until it is valid.
    while True:
        print(F().magenta(title()))
        print(_l(F().magenta('Choose a modulation type.\n')))

        # Sets the available modulation types.
        options = [
            [
                '{} - {}'.format(F().bold('AM'),
                                 F().italic('Amplitude Modulation')), AM
            ],
            [
                '{} - {}'.format(
                    F().bold('AM-SC'),
                    F().italic(
                        'Amplitude Modulation with Suppressed Carrier')), AM_SC
            ], [F().italic('No modulation'), NO_MOD]
        ]

        # Lists the options.
        for i, option in enumerate(options):
            print(_l(label(option[0], F().red(i + 1), F())))

        # Reads the chosen option.
        try:
            opt = int(input(_lt('Your option: ')))

            # Checks whether the option is avaliable.
            if opt not in range(1, len(options) + 1):
                raise ValueError()

        # Invalid or nonexisting option.
        except ValueError:
            print(_lt(error('Invalid option!')))
            press_enter_to('try again', F().red(), F().white())

            continue

        # If the option is 0, go back to client menu.
        if not opt:
            break

        # If no, saves the modulation type in a variable.
        modulation = options[opt - 1][1]

        # Goes to the next step.
        break

    # Asks the user for the connection settings until they are valid.
    while True:
        print(F().magenta(title()))
        print(_l(F().magenta('Configure the connection with the server.')))

        try:

            # Waits for the user to provide the hostname.
            host = input(
                _lt('Hostname [{}]: '.format(
                    F().bold().magenta(DEFAULT_HOST))))

            # Waits for the user to provide the port number.
            port = input(
                _l('Port number [{}]: '.format(
                    F().bold().magenta(DEFAULT_PORT))))

            print()

            # Sets the feedback animation thread...
            thread = Thread(target=ellipsis,
                            args=(_l('Connecting'), F().yellow()),
                            daemon=True)

            # ... and starts it.
            thread.start()

            try:

                # Tries to connect with the server.
                client.connect(modulation, host, port)

            # Ctrl+C pressed.
            except (EOFError, KeyboardInterrupt):

                # Stops the feedback animation thread.
                thread.alive = False

                print(_lt(_lt(error('Operation canceled by the user!'))))
                press_enter_to('try again', F().red(), F().white())

                continue

            # Stops the feedback animation thread when the connection is established.
            thread.alive = False

            print(_lt(_lt(success('Connection established!'))))
            press_enter_to('continue', F().green(), F().white())

            # Sends a confirmation of receiving to the server.
            client.send_str('OK')

            break

        # Connection with the server was refused.
        except ConnectionRefusedError:
            err = 'The connection with this server was refused!'

        # Connection timeout.
        except ConnectionTimeoutError:
            err = 'The connection attempt has timed out!'

        # Port is not valid.
        except InvalidPortError:
            err = 'Invalid port number!'

        # Unknown or nonexistent host.
        except UnknownHostError:
            err = 'Unknown host!'

        # Stops the feedback animation thread.
        thread.alive = False

        print(_lt(_lt(error(err))))
        press_enter_to('try again', F().red(), F().white())

    # Receives some informations and instructions from the server.
    client.log(client.recv_str())
    client.log(client.recv_str())

    # Opens a new speaker.
    with sd.OutputStream(blocksize=CHUNK_SIZE,
                         channels=CHANNELS,
                         dtype=np.int16,
                         samplerate=FRAME_RATE) as speaker:
        try:

            # Receives the first package.
            package = client.recv()

            # Wait for new packages from the server while they are not empty.
            while len(package) != 0:

                # Gets the audio from the package.
                received = M(modulation, package)

                # If the client chosen no modulated audio,...
                if modulation == NO_MOD:

                    # ... then just speaks the original package...
                    speaker.write(received.output())

                    # ... and receives the next one.
                    package = client.recv()

                    continue

                # Demodulates the received audio.
                demodulated = received.demodulate()

                # Filters the demodulated audio.
                filtered = demodulated.lowpass()

                # Outputs the filtered audio in the speaker.
                speaker.write(filtered.output())

                # Receives the next package.
                package = client.recv()

            # Logs the server shutdown.
            client.log(_ltb(label(error('The server has been shut down!'))))

        # The server has shut down.
        except ConnectionResetError:

            # Logs the server shutdown.
            client.log(_ltb(label(error('The server has been shut down!'))))

        # Ctrl+C pressed.
        except (EOFError, KeyboardInterrupt):

            # Logs the client disconnecting.
            client.log(_ltb(label(error('Disconnecting from the server...'))))

    # Disconnects from the server.
    client.disconnect()

    press_enter_to('back to the client menu', F().red(), F().white())
Example #8
0
        cv2.imwrite(
            '{}/{}_{}_{}_{:02d}_{:02d}_{:02d}_{:03d}.jpg'.format(
                output_dir,
                path.splitext(path.split(video_file)[1])[0], extracted_frames,
                frame_index, hours, minutes, seconds, milliseconds), frame)

        extracted_frames += 1

    # Final time.
    end_time = datetime.now()

    # If there was a thread running,...
    if thread is not None:

        # ... stop it.
        thread.alive = False

    # Calculates the total process time.
    total_time = end_time - start_time

    print(F().blue(header()))
    print_video_information()

    print(_lt(success('Success!')))

    print(_lt('{} {}'.format(info('Extracted frames:'), extracted_frames)))
    print(
        _l('{} {}\n'.format(info('Elapsed time:'),
                            humanize_duration(total_time.total_seconds()))))

# Ctrl+C pressed.