Ejemplo n.º 1
0
def music_play():
    global outMessage
    pygame.mixer.init()

    # Judge the music playing style
    if events.get_value("Warming_up"):
        music_location, music_name = musicDB.select_music(
            random.randint(90, 109))
        events.set_value("Music_location", str(music_location))
        events.set_value("Music_name", str(music_name))
    else:
        music_location, music_name = musicDB.select_music(
            get_highest_averange_hbr_data())
        events.set_value("Music_location", str(music_location))
        events.set_value("Music_name", str(music_name))

    # Send the name of playing music
    outMessage["command"] = "Music name"
    outMessage["data"] = music_name
    send_event.set()
    print("\033[36mSEND MESSAGE:\033[0m", outMessage["command"],
          outMessage["data"])

    pygame.mixer.music.load(music_location)
    pygame.mixer.music.play()

    events.set_value("Music player running", True)
    music_start_event.set()
Ejemplo n.º 2
0
    def run(self):
        print("Start music module!")

        music_play()
        events.set_value("Music player running", True)

        while events.get_value("Music player running"):
            # Wait for command.
            command_event.wait()

            # Get command and perform operation.
            current_state = events.get_value("Music_player_state")
            if current_state == "PAUSE":
                music_pause()

            if current_state == "PLAYING":
                music_unpause()

            if current_state == "CHANGE":
                music_stop()

            if current_state == "QUIT":
                # Stop the player.
                events.set_value("Music player running", False)
                music_stop()

            command_event.clear()
        print("Music module stopped!")
Ejemplo n.º 3
0
def music_play():
    pygame.mixer.init()

    # TODO: get implementation of select new song.
    events.set_value("Music_location", str(random.choice(playlist)))

    # events.to_string()

    music_location = events.get_value("Music_location")
    pygame.mixer.music.load(music_location)
    pygame.mixer.music.play()
    music_start_event.set()
Ejemplo n.º 4
0
    def run(self):
        print("\033[33mStart music module!\033[0m")
        music_play()

        while events.get_value("Music player running"):
            # Wait for command.
            command_event.wait()
            music = pygame.mixer.music

            # Get command and perform operation.
            current_state = events.get_value("Music_player_state")
            if current_state == "PAUSE":
                music.pause()

            elif current_state == "PLAYING":
                music.unpause()

            elif current_state == "CHANGE-PLAYING":
                music.fadeout(1000)

            elif current_state == "CHANGE-PAUSE":
                music.unpause()
                music.stop()

            elif current_state == "QUIT-PLAYING":
                # Stop the player.
                events.set_value("Music player running", False)
                music.fadeout(1000)

            elif current_state == "QUIT-PAUSE":
                events.set_value("Music player running", False)
                music.unpause()
                music.stop()

            command_event.clear()
        print("\033[31mMusic module stopped!\033[0m")
Ejemplo n.º 5
0
music = mp3_player.MusicModule("Music model")
detection = mp3_player.MusicPlaying("Music playing")

music.start()
detection.start()

running = True

command_event = mp3_player.command_event

while running:
    time.sleep(0.2)
    number = input("input:")
    if number == "1":
        events.set_value("Music_player_state", "CHANGE")
        command_event.set()
        print("Changing song......")

    elif number == "2":
        events.set_value("Music_player_state", "PAUSE")
        command_event.set()
        print("Music paused......")

    elif number == "3":
        events.set_value("Music_player_state", "PLAYING")
        command_event.set()
        print("Music continued......")

    elif number == "4":
        events.set_value("Music_player_state", "QUIT")
Ejemplo n.º 6
0
def start_music_module():
    events.set_value("Music_player_state", "PLAYING")
    events.set_value("Music_location", random.choice(playlist))

    music_thread = mp3_player.MusicModule("Music_Thread")
    music_thread.start()
Ejemplo n.º 7
0
    time.sleep(0.01)
    while True:
        if events.get_value("Music_player_state") == "STOP":
            print("Music ending")
            start_music_module()
            events.to_string()


if __name__ == "__main__":

    music_select_thread = MusicSelectModule("Music_Select_Thread")
    music_select_thread.start()

    number = input("input:")

    running = True

    while running:
        if number == "1":
            events.set_value("Music_player_state", "STOP")
            break

        elif number == "2":
            events.set_value("Music_player_state", "PAUSE")
            events.to_string()
            number = input("input:")

        elif number == "3":
            events.set_value("Music_player_state", "PLAYING")
            number = input("input:")
Ejemplo n.º 8
0
def server_receive(sock):
    global outMessage, inMessage,\
        command_event, music_start_event, send_event, color_lock
    global warm_up_time, rest_time, \
        default_color, anaerobic_color, maximum_color, aerobic_color_range, anaerobic_color_range, \
        aerobic_start, anaerobic_start, maximum_heart_beat, aerobic_range, anaerobic_range, \
        demo_mode

    print("\033[33mStart receive module!\033[0m")

    while True:
        inMessage = simplejson.loads(sock.recv(1024).decode())
        print("\033[34mRECEIVE MESSAGE:\033[0m", inMessage["command"])

        # 1. If client send "Quit client", server will reply to help client quit
        if inMessage["command"] == "Quit client":
            # Judge whether music is playing
            if events.get_value("Music_player_state") == "PAUSE":
                events.set_value("Music_player_state", "QUIT-PAUSE")
            else:
                events.set_value("Music_player_state", "QUIT-PLAYING")
            events.set_value("Detect_on", False)
            events.set_value("Lights_on", False)
            command_event.set()
            outMessage["command"] = "Quit client"
            send_event.set()
            break

        # 2. Client asks whether server is initialized
        elif inMessage["command"] == "isInitialized":
            # Read configurations
            config = configparser.ConfigParser()
            config.read('config.ini')

            # If it is, server will send "Server is initialized" after initialize
            if eval(config['SERVER']['is_initialized']):

                # Update fitbit account rest heartbeat rate from server
                if eval(config_read('FITBIT ACCOUNT',
                                    'fitbit_is_initialized')):

                    client_id = config_read('FITBIT ACCOUNT', 'fitbit_user_id')
                    client_secret = config_read('FITBIT ACCOUNT',
                                                'fitbit_user_secret')
                    rest_heartbeat_rate = get_averange_hbt_from_server(
                        client_id, client_secret, 7)

                    # Error occurred during fetch data from cloud, use the stored data
                    if not rest_heartbeat_rate:
                        rest_heartbeat_rate = eval(
                            config_read('BODY INFO', 'rest_heartbeat_rate'))
                # Use stored data
                else:
                    rest_heartbeat_rate = eval(
                        config_read('BODY INFO', 'rest_heartbeat_rate'))

                print('rest_heartbeat_rate:', rest_heartbeat_rate)

                # Load the saved information
                initialize_sport_settings(rest_heartbeat_rate)
                print("\033[36mSport settings loaded.\033[0m")

                outMessage["command"] = "Server is initialized"

                # Necessary data will be stored in outMessage["data"]
                outMessage["data"] = {
                    "warm_up_time": warm_up_time,
                    "default_color": default_color,
                    "anaerobic_color": anaerobic_color,
                    "maximum_color": maximum_color,
                }

            # If not, will send "Server isn't initialized"
            else:
                outMessage["command"] = "Server isn't initialized"

            send_event.set()
            print("\033[36mSEND MESSAGE:\033[0m", str(outMessage["command"]))

        # 3. Client sends initialize information
        elif inMessage["command"] == "Initialize":
            print("\033[35mInitialized with:\033[0m")

            initialize_data = inMessage["data"]

            # Print the client send data
            print(initialize_data)
            for (key, value) in initialize_data.items():
                print(key, ":", value)

            # Initialize and save fitbit user information
            client_secret = initialize_data['fitbit_user_secret']
            config_write('FITBIT ACCOUNT', 'fitbit_user_secret', client_secret)
            client_id = initialize_data['fitbit_user_id']
            config_write('FITBIT ACCOUNT', 'fitbit_user_id', client_id)
            fitbit_is_initialized = initialize_data['fitbit_user_id'] != ""
            config_write('FITBIT ACCOUNT', 'fitbit_is_initialized',
                         fitbit_is_initialized)

            # Initialize and save heart beat information
            if fitbit_is_initialized:
                rest_heartbeat_rate = get_averange_hbt_from_server(
                    client_id, client_secret, 7)
                config_write('BODY INFO', 'rest_heartbeat_rate',
                             rest_heartbeat_rate)

                # Error occurred during fetch data from cloud
                if not rest_heartbeat_rate:
                    rest_heartbeat_rate = initialize_data[
                        'rest_heartbeat_rate']
                    config_write('BODY INFO', 'rest_heartbeat_rate',
                                 rest_heartbeat_rate)
            else:
                rest_heartbeat_rate = initialize_data['rest_heartbeat_rate']
                config_write('BODY INFO', 'rest_heartbeat_rate',
                             rest_heartbeat_rate)

            maximum_heart_beat = 206.9 - (0.67 * initialize_data['age'])
            config_write('BODY INFO', 'maximum_heart_beat', maximum_heart_beat)

            aerobic_start = maximum_heart_beat * 0.6
            config_write('BODY INFO', 'aerobic_start', aerobic_start)

            heart_beat_storage = maximum_heart_beat - rest_heartbeat_rate
            anaerobic_start = rest_heartbeat_rate + 0.8 * heart_beat_storage

            aerobic_range = anaerobic_start - aerobic_start
            anaerobic_range = maximum_heart_beat - anaerobic_start

            # Initialize and save sport information
            warm_up_time = initialize_data['warm_up_time']
            config_write('SPORT INFO', 'warm_up_time', warm_up_time)
            rest_time = initialize_data['rest_time']
            config_write('SPORT INFO', 'rest_time', rest_time)
            rest_time += 10

            # Initialize and save light color
            default_color = initialize_data['default_color']
            config_write('LIGHT COLOR', 'default_color', default_color)
            anaerobic_color = initialize_data['anaerobic_color']
            config_write('LIGHT COLOR', 'anaerobic_color', anaerobic_color)
            maximum_color = initialize_data['maximum_color']
            config_write('LIGHT COLOR', 'maximum_color', maximum_color)

            aerobic_color_range = range_minus(default_color, anaerobic_color)
            config_write('LIGHT COLOR', 'aerobic_color_range',
                         aerobic_color_range)
            anaerobic_color_range = range_minus(anaerobic_color, maximum_color)
            config_write('LIGHT COLOR', 'anaerobic_color_range',
                         anaerobic_color_range)

            # Initialize demo settings
            demo_mode = False

            # Initialize music database
            musicDB.scan_music(config_read('SERVER', 'music_directory'))

            # After initialize will set is_initialized to True and send "Initialized successfully"
            config_write('SERVER', 'is_initialized', True)

            outMessage["command"] = "Initialized successfully"
            send_event.set()
            print("\033[36mSEND MESSAGE:\033[0m", outMessage["command"])

        # 4. Client asks rest heartbeat data
        elif inMessage["command"] == "Get rest heartbeat rate":
            # Server will send 15 valid heart beat data
            thread_detect_hbr_data = threading.Thread(target=detect_rest_hbr)
            thread_detect_hbr_data.start()

        # 5. Client asks server to start warm up music
        elif inMessage["command"] == "Start warm up music":
            music = MusicModule("Music model")
            detection = MusicPlaying("Music playing")
            events.set_value("Warming_up", True)

            music.start()
            detection.start()

        # 6. Client asks server to start sport music
        elif inMessage["command"] == "Start sport music":
            music = MusicModule("Music model")
            detection = MusicPlaying("Music playing")
            events.set_value("Warming_up", False)

            # Check whether the detection module is on
            if not events.get_value("Detect_on"):
                thread_detect_hbr_data = threading.Thread(
                    target=detect_hbr_data)
                thread_light = threading.Thread(
                    target=change_light_color_by_hbr)
                events.set_value("Detect_on", True)
                events.set_value("Lights_on", True)

                # Fill the queue with random aerobic sport heart rate
                for i in range(rest_time):
                    heart_beat_queue.append(
                        random.randint(round(aerobic_start),
                                       round(anaerobic_start)))

                thread_detect_hbr_data.start()
                thread_light.start()

            music.start()
            detection.start()

        # 7. Client asks server to change music
        elif inMessage["command"] == "Change music":
            if events.get_value("Music_player_state") == "PAUSE":
                events.set_value("Music_player_state", "CHANGE-PAUSE")
            else:
                events.set_value("Music_player_state", "CHANGE-PLAYING")
            command_event.set()
            print("\033[36mChanging song......\033[0m")

        # 8. Client asks server to pause music
        elif inMessage["command"] == "Pause":
            events.set_value("Music_player_state", "PAUSE")
            command_event.set()
            print("\033[36mMusic paused......\033[0m")

        # 9. Client asks server to continue music
        elif inMessage["command"] == "unPause":
            events.set_value("Music_player_state", "PLAYING")
            command_event.set()
            print("\033[36mMusic continued......\033[0m")

        # 10. Client asks server to stop music
        elif inMessage["command"] == "Stop music module":
            if events.get_value("Music_player_state") == "PAUSE":
                events.set_value("Music_player_state", "QUIT-PAUSE")
            else:
                events.set_value("Music_player_state", "QUIT-PLAYING")
            command_event.set()
            print("\033[36mMusic STOPPED.\033[0m")

        # 11. Client asks server to open lights
        elif inMessage["command"] == "Start light module":
            thread_light = threading.Thread(target=change_light_color_by_hbr)
            events.set_value("Lights_on", True)
            thread_light.start()

        # 12. Client asks server to close lights
        elif inMessage["command"] == "Stop light module":
            events.set_value("Lights_on", False)

        # 13. Client asks server to begin heartbeat rate detection
        elif inMessage["command"] == "Start heartbeat detection":
            # Filled the queue with random aerobic sport heart beat rate.
            for i in range(rest_time):
                heart_beat_queue.append(
                    random.randint(round(aerobic_start),
                                   round(anaerobic_start)))

            # Start detecting thread, server will send heartbeat data once per second
            thread_detect_hbr_data = threading.Thread(target=detect_hbr_data)
            events.set_value("Detect_on", True)
            thread_detect_hbr_data.start()

        # 14. Client asks server to turn off heartbeat rate detection
        elif inMessage["command"] == "Stop heartbeat detection":
            events.set_value("Detect_on", False)

        # 15. Client asks server to set demo module
        elif inMessage["command"] == "Set demo module":
            if not demo_mode:
                demo_mode = True
                print("\033[36mDemo mode enabled!\033[0m")
            else:
                demo_mode = False
                print("\033[36mDemo mode disabled!\033[0m")

        # 16. Client asks server to reset server
        elif inMessage["command"] == "Reset server":
            # Reset config.ini

            reset_config()
            print("\033[36mConfiguration file reset!\033[0m")

            # Truncate music database
            musicDB.truncate_music_db(config_read('SERVER', 'music_directory'))

            # Set server state to not initialized
            config_write('SERVER', 'is_initialized', False)

            # Server replies rest successfully
            outMessage["command"] = "Reset successfully"
            send_event.set()

            print("\033[36mSEND MESSAGE:\033[0m", outMessage["command"])

        # 17. Client asks server to update music database
        elif inMessage["command"] == "Update music database":
            # Scan the music directories
            musicDB.scan_music(config_read('SERVER', 'music_directory'))

            # Server replies success
            outMessage["command"] = "Update MDB successfully"
            send_event.set()

            print("\033[36mSEND MESSAGE:\033[0m", outMessage["command"])

        # 18. Client asks server to update light color
        elif inMessage["command"] == "Update light color":

            update_data = inMessage["data"]

            # Print the client sent colors
            for (key, value) in inMessage["data"].items():
                print(key, ":", value)

            # Lock color parameters
            color_lock.acquire()

            # Update and save light color
            default_color = update_data['default_color']
            config_write('LIGHT COLOR', 'default_color', default_color)
            anaerobic_color = update_data['anaerobic_color']
            config_write('LIGHT COLOR', 'anaerobic_color', anaerobic_color)
            maximum_color = update_data['maximum_color']
            config_write('LIGHT COLOR', 'maximum_color', maximum_color)

            aerobic_color_range = range_minus(default_color, anaerobic_color)
            config_write('LIGHT COLOR', 'aerobic_color_range',
                         aerobic_color_range)
            anaerobic_color_range = range_minus(anaerobic_color, maximum_color)
            config_write('LIGHT COLOR', 'anaerobic_color_range',
                         anaerobic_color_range)

            # Release color parameters
            color_lock.release()

            # Server reply update color successfully
            outMessage["command"] = "Update color successfully"
            send_event.set()

            print("\033[36mSEND MESSAGE:\033[0m", outMessage["command"])

    print("\033[31mReceive module stopped!\033[0m")