#!/usr/bin/env python3 #1
# encoding: utf-8 #2
# @Author: Aiden #3
# @Date: 2025/04/16 #4

import time #6
import rospy #7
import rosnode   #8
import threading #9
from config import *  #10
from speech import speech   #11
from std_msgs.msg import String, Bool #12
from std_srvs.srv import Trigger, TriggerResponse, SetBool, SetBoolResponse #13
    

class TTSNode(object): #16
    def __init__(self): #17
        rospy.init_node('tts_node', anonymous=False) #18
        
        self.text = None #20
        self.language = os.environ["ASR_LANGUAGE"] #21
        speech.set_volume(70) # Set volume （设置音量） #22
        if self.language == 'Chinese': #23
            self.tts = speech.RealTimeTTS() #24
        else: #25
            self.tts = speech.RealTimeOpenAITTS() #26

        # Create publisher （创建发布者） #28
        self.play_finish_pub = rospy.Publisher('~play_finish', Bool, queue_size=10) #29
        
        # Create subscriber （创建订阅者） #31
        rospy.Subscriber('~tts_text', String, self.tts_callback) #32
        
        # Create service （创建服务） #34
        rospy.Service('~init_finish', Trigger, self.get_node_state) #35
        
        # Start thread to process TTS （启动线程处理 TTS） #37
        threading.Thread(target=self.tts_process, daemon=True).start() #38
        
        rospy.loginfo('\033[1;32m%s\033[0m' % 'TTSNode 启动成功') #40

    def get_node_state(self, request): #42
        """ #43
        Handle '~init_finish' service request and return node status （处理 '~init_finish' 服务请求，返回节点状态） #44
        """ #45
        response = TriggerResponse() #46
        response.success = True #47
        response.message = "TTSNode 正在运行中。" #48
        return response #49

    def tts_callback(self, msg): #51
        """ #52
        Callback function for the '~tts_text' topic subscriber （订阅 '~tts_text' 主题的回调函数） #53
        Update the text to be processed （更新待处理的文本） #54
        """ #55
        rospy.logdebug("收到 TTS 文本: %s", msg.data) #56
        self.text = msg.data #57

    def tts_process(self): #59
        """ #60
        Continuously monitor and process TTS requests （持续监控并处理 TTS 请求） #61
        Convert text to speech and publish 'play_finish' message （将文本转换为语音并发布 'play_finish' 消息） #62
        """ #63
        while not rospy.is_shutdown(): #64
            if self.text is not None: #65
                if self.text == '': #66
                    # If the text is empty, play silent audio （如果文本为空，播放无声音频） #67
                    speech.play_audio(no_voice_audio_path) #68
                else: #69
                    rospy.logdebug("正在处理TTS文本: %s", self.text) #70
                    self.tts.tts(self.text, model=tts_model, voice=voice_model) #71
                
                # Reset the text （重置文本） #73
                self.text = None #74
                
                # Publish 'play_finish' message （发布 'play_finish' 消息） #76
                msg = Bool() #77
                msg.data = True #78
                self.play_finish_pub.publish(msg) #79
                rospy.logdebug("已发布 'play_finish' 消息。") #80
                
            else: #82
                time.sleep(0.01) #83

def main(): #85
    """ #86
    Main function, instantiate TTSNode and keep the node running （主函数，实例化 TTSNode 并保持节点运行） #87
    """ #88
    try: #89
        tts_node = TTSNode() #90
        rospy.spin() #91
    except rospy.ROSInterruptException: #92
        rospy.loginfo('TTSNode 已被中断，正在关闭。') #93
    except Exception as e: #94
        rospy.logerr('发生意外错误: %s', str(e)) #95
    finally: #96
        rospy.loginfo('TTSNode 已关闭。') #97

if __name__ == "__main__": #99
    main() #100
