import thread
import threading
import paho.mqtt.client as mqtt
from voiceid.sr import Voiceid
from voiceid.db import GMMVoiceDB

# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("ais/recognize/request/+")

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))
    thread.start_new_thread(recognize, (msg.payload, ))

def recognize(voice_path):
    # voice_db_lock.acquire()
    # db = GMMVoiceDB('voiceDB')
    print db.get_speakers()
    # assume only one speaker in one sample, To Do: multiple speakers in one sample
    # set to True to force to avoid diarization, in case a single speaker in the file
    try:
        voice = Voiceid(db, voice_path, single=True)
        # extract_speakers(interactive=False, quiet=False, thrd_n=1)
        voice.extract_speakers()
        clusters = voice.get_clusters()
        label = clusters.keys()[0]
        cluster = voice.get_cluster(label)
        speaker = cluster.get_best_speaker()
        if speaker == "unknown":
            print "need name"
        else:
            print speaker
    except IOError:
        print "voice file doesn't exist"
        # voice_db_lock.release()

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
# set_maxthreads(trd)
db = GMMVoiceDB("voiceDB")

voice_db_lock = threading.Lock()
# client.connect("127.0.0.1", 1883, 60)
client.connect("iot.eclipse.org", 1883, 60)

# https://eclipse.org/paho/clients/python/docs/#network-loop
client.loop_forever()

@@ -104,29 +104,143 @@
 eid.
-db import GMMVoiceDB%0A
+sr import Cluster%0Afrom voiceid.db import GMMVoiceDB%0A%0ANEW_VOICE_TOPIC = %22ais/recognize/voice%22%0ASET_NAME_TOPIC = %22ais/recognize/setname/+%22
 %0A# T
@@ -428,35 +428,61 @@
 ibe(
-%22ais/recognize/request/+%22)%0A
+NEW_VOICE_TOPIC)%0A    client.subscribe(SET_NAME_TOPIC)
 %0A# T
@@ -630,16 +630,57 @@
 yload))%0A
+    if msg.topic == NEW_VOICE_TOPIC:%0A    
     thre
@@ -726,16 +726,374 @@
 load, ))
+%0A    elif msg.topic.startswith(SET_NAME_TOPIC%5B0: -1%5D):%0A        cluster_label = msg.topic.split(%22/%22)%5B-1%5D%0A        thread.start_new_thread(set_name, (cluster_label, msg.payload))%0A%0Adef set_name(cluster_label, new_name):%0A    print %22set %22 + cluster_label + %22 to: %22 + new_name%0A    cluster = Cluster(cluster_label)%0A    print cluster%0A    cluster.set_speaker(new_name)
 %0A%0Adef re
@@ -1586,16 +1586,24 @@
         
+cluster_
 label = 
@@ -1657,16 +1657,24 @@
 cluster(
+cluster_
 label)%0A 
@@ -1780,16 +1780,156 @@
 d name%22%0A
+            cluster.set_speaker(%22unknown%22)%0A            voice.update_db()%0A            client.publish(%22ais/recognize/unknown%22, cluster_label)%0A
         

save work