def groupPlayInd_Handler(ui, rcvData):
    log = datetime.datetime.now().strftime("[%H:%M:%S]")
    cmd = []
    if rcvData[1] == 0x00:  # Pause triggered by Slave device
        log += "Group Play Ind received - Pause"
        ui_context.update_play_status(0)
        cmd = 'stop'
        ui.WoWIF.SPK_UI.Update_Comment('Pause')
    elif rcvData[1] == 0x01:  # Play triggered by Slave device
        log += "Group Play Ind received - Play"
        ui_context.update_play_status(1)
        cmd = 'start'
        ui.WoWIF.SPK_UI.Update_Comment('Play')
    else:
        log += "Group Play Ind received - Unknown Command"
        log += str(rcvData[1])

    ui.log_TextBrowser.append(log)

    # Update GUI - EQ Mark
    if cmd is not None:
        gr_context = ui_context.Get_active_group_info(getActivateIdx())
        if ui.WoWIF.SPK_UI.Slaves.isEnabled() is True:
            for dev in gr_context['dev_info'].values():
                for ch in dev['ch']:
                    ui.WoWIF.SPK_UI.Update_Group_EQ(ch, cmd)
def groupPlayRsp_Handler(ui, rcvData):
    if rcvData[1] == 0x00:
        log = datetime.datetime.now().strftime("[%H:%M:%S]")
        log += " Group Play/Pause done"
        ui.log_TextBrowser.append(log)

        PlayPause = getPlayPauseInfo()
        print(PlayPause)
        ui_context.update_play_status(PlayPause)
        if PlayPause >= 1:
            ui.WoWIF.TBL_UI.Update_WoWPlay(state="Play")
        else:
            ui.WoWIF.TBL_UI.Update_WoWPlay(state="Pause")
            ui.WoWIF.SPK_UI.Update_Comment("Pause")
            # Update GUI - EQ Mark
            gr_context = ui_context.Get_active_group_info(getActivateIdx())
            if ui.WoWIF.SPK_UI.Slaves.isEnabled() is True:
                for dev in gr_context['dev_info'].values():
                    if dev['role'] == '0':
                        ui.WoWIF.SPK_UI.Update_Group_EQ('Master', 'stop')
                    else:
                        for ch in dev['ch']:
                            ui.WoWIF.SPK_UI.Update_Group_EQ(ch, 'stop')

    else:
        log = datetime.datetime.now().strftime("[%H:%M:%S]")
        log += " Group Play/Pause failed. Reason: "
        log += str(rcvData[1])
        ui.log_TextBrowser.append(log)
def volumeChangeInd_Handler(ui, rcvData):
    activateInfo = S_GROUP_ACTIVATE_INFO()

    log = datetime.datetime.now().strftime("[%H:%M:%S]")
    log += " Group Volume Changed by speaker index "
    log += str(rcvData[1])
    log += ". Volume is "
    log += str(rcvData[2])
    ui.log_TextBrowser.append(log)

    vol = int.from_bytes(rcvData[2], 'little')
    dev_id = int.from_bytes(rcvData[1], 'little')

    exec("ui.group%d_Device%d_Vol_LineEdit.setText(\"%s\")" %
         (activateInfo.groupIdx, dev_id, str(vol)))
    # Update ui_context
    ui_context.Update_dev_info_in_group(vol=vol,
                                        gr_id=activateInfo.groupIdx,
                                        dev_id=dev_id)

    # Update GUI
    gr_context = ui_context.Get_active_group_info(getActivateIdx())
    row_idx = 0
    for dev_id in gr_context['dev_info']:
        # Update Table
        gr_context['dev_info'][dev_id][
            'ch']  # need to convert bitmap to channel info
        ui.WoWIF.TBL_UI.Update_AudioPlay_Speaker(row=row_idx,
                                                 id=dev_id,
                                                 str_ch=None,
                                                 bit=None,
                                                 samp=None,
                                                 str_vol=None)
        row_idx += 1
def groupDeactivateRsp_Handler(ui, rcvData):
    activateInfo = S_GROUP_ACTIVATE_INFO()

    if rcvData[1] == 0x00:
        activateInfo = S_GROUP_ACTIVATE_INFO()

        log = datetime.datetime.now().strftime("[%H:%M:%S]")
        log += " Group Deactivation done"
        ui.log_TextBrowser.append(log)

        # Update GUI
        gr_context = ui_context.Get_active_group_info(getActivateIdx())
        ui.WoWIF.SPK_UI.Update_Group_WiFi('Master', 'disable')
        for dev in gr_context['dev_info'].values():
            # Speaker Group Enable
            for ch in dev['ch']:
                ui.WoWIF.SPK_UI.Update_Group_Status(ch, 0)
                # Initialize Values
                # ui.WoWIF.SPK_UI.Update_Latency_Value(ch, '-')
                # ui.WoWIF.SPK_UI.Update_RSSI_Value(ch, '-')
                # ui.WoWIF.SPK_UI.Update_Loss_Value(ch, '-')
                # ui.WoWIF.SPK_UI.Update_Drop_Value(ch, '-')
                ui.WoWIF.SPK_UI.Update_Group_EQ(ch, 'disable')
                ui.WoWIF.SPK_UI.Update_Group_WiFi(ch, 'disable')
        ui.WoWIF.SPK_UI.Update_Slave_Status(0)
        ui.WoWIF.SPK_UI.Update_Comment("Deactivated")
        ui.WoWIF.SPK_UI.Master_Role.setText("Master")
        ui.WoWIF.SPK_UI.Update_Group_EQ('Master', 'disable')
        ui.WoWIF.TBL_UI.Update_WoWPlay(state="Deactivation")
    else:
        log = datetime.datetime.now().strftime("[%H:%M:%S]")
        log += " Group Deactivation failed. Reason: "
        log += str(rcvData[1])
        ui.log_TextBrowser.append(log)
def groupActivateRsp_Handler(ui, rcvData):
    if rcvData[1] == 0x00:
        log = datetime.datetime.now().strftime("[%H:%M:%S]")
        log += " Group Activation done "
        ui.log_TextBrowser.append(log)

        # Update GUI
        gr_context = ui_context.Get_active_group_info(getActivateIdx())
        ui.WoWIF.SPK_UI.Update_Slave_Status(True)
        for dev in gr_context['dev_info'].values():
            if dev['role'] == '0':
                txt = 'Master - '
                for ch in dev['ch']:
                    txt += ch
                    txt += '/'
                ui.WoWIF.SPK_UI.Master_Role.setText(txt[:-1])
                ui.WoWIF.SPK_UI.Update_Group_WiFi('Master', 'start')
                continue
            else:
                # Speaker Group Enable
                for ch in dev['ch']:
                    ui.WoWIF.SPK_UI.Update_Group_Status(ch, True)
                    # Initialize Values
                    ui.WoWIF.SPK_UI.Update_Latency_Value(ch, '-')
                    ui.WoWIF.SPK_UI.Update_RSSI_Value(ch, '-')
                    ui.WoWIF.SPK_UI.Update_Loss_Value(ch, '-')
                    ui.WoWIF.SPK_UI.Update_Group_WiFi(ch, 'start')
        ui.WoWIF.SPK_UI.Update_Comment('Activated')
        ui.WoWIF.TBL_UI.Update_WoWPlay(state='Activation')
        ui.Timer.start(Timeout_Time)
    else:
        log = datetime.datetime.now().strftime("[%H:%M:%S]")
        log += " Group Activation failed. Reason: "
        log += str(rcvData[1])
        ui.log_TextBrowser.append(log)
def get_GroupVolumeRet_Handler(ui, rcvData):
    groupVolumeInfo = getGroupVolumeInfo_from_Vector(rcvData[1:])
    activateIdx = getActivateIdx()

    log = datetime.datetime.now().strftime("[%H:%M:%S]")
    log += "Get Group Volume done"
    ui.log_TextBrowser.append(log)

    init_groupVolume(ui)
    exec("ui.group%d_groupVolume_LineEdit.setText(\"%s\")" %
         (activateIdx, str(groupVolumeInfo.groupVolume)))
    ui_context.update_group_info_group_vol(activateIdx,
                                           groupVolumeInfo.groupVolume)

    gr_context = ui_context.Get_active_group_info(getActivateIdx())

    row_idx = 0
    for devIdx in range(0, groupVolumeInfo.numSpeaker):
        exec("ui.group%d_Device%d_Vol_LineEdit.setText(\"%s\")" %
             (activateIdx, devIdx, str(groupVolumeInfo.volume[devIdx])))
        ui_context.Update_dev_info_in_group(gr_id=activateIdx,
                                            dev_id=devIdx,
                                            vol=groupVolumeInfo.volume[devIdx])
        # Update Table
        str_ch = ""
        for ch in gr_context['dev_info'][devIdx]['ch']:
            str_ch += ch.upper() + '/'
        ui.WoWIF.TBL_UI.Update_AudioPlay_Speaker(
            row=row_idx,
            id=devIdx,
            str_ch=str_ch[:-1],
            bit=None,
            samp=None,
            str_vol=str(groupVolumeInfo.volume[devIdx]))
        row_idx += 1
def audioPlaybackInfoInd_Handler(ui, rcvData):
    log = datetime.datetime.now().strftime("[%H:%M:%S]")
    log += "Audio Playback Info Ind received "
    ui.log_TextBrowser.append(log)

    # Update GUI - EQ Mark
    gr_context = ui_context.Get_active_group_info(getActivateIdx())
    if ui.WoWIF.SPK_UI.Slaves.isEnabled() is True:
        for dev in gr_context['dev_info'].values():
            if dev['role'] == '0':
                ui.WoWIF.SPK_UI.Update_Group_EQ('Master', 'start')
            else:
                for ch in dev['ch']:
                    ui.WoWIF.SPK_UI.Update_Group_EQ(ch, 'start')

    bitDepth = int.from_bytes(rcvData[1:5], 'little')
    enum_sampleRate = int.from_bytes(rcvData[5:9], 'little')
    totalAudioCh = int.from_bytes(rcvData[9:13], 'little')
    playbackLatency = int.from_bytes(rcvData[13:17], 'little')
    sampleRate = AUDIO_SAMPLE_ENUM_TO_KHZ[enum_sampleRate]

    ui.WoWIF.TBL_UI.Update_AudioSource(bitDepth, sampleRate,
                                       CH_CFG_TYPE_TO_STRING[totalAudioCh][1])
    ui.WoWIF.TBL_UI.Update_WoWPlay(state='Play', latency=playbackLatency)
    ui.WoWIF.SPK_UI.Update_Comment('Playback Latency\n%d ms' %
                                   (playbackLatency))

    # Update Channel Information in the Audio Play Information
    row = 0
    IDs = {"0": "", "1": ""}
    for devid in gr_context['dev_info']:
        IDs[gr_context['dev_info'][devid]['role']] += str(devid) + (" / ")
        str_ch = ""
        for ch in gr_context['dev_info'][devid]['ch']:
            str_ch += ch.upper() + '/'
        ui.WoWIF.TBL_UI.Update_AudioPlay_Speaker(
            row=row,
            id=devid,
            str_ch=str_ch[:-1],
            bit=bitDepth,
            samp=sampleRate,
            str_vol=str(gr_context['dev_info'][devid]['vol']))
        row += 1

    ui.WoWIF.TBL_UI.Update_AudioPlay_Config(
        CH_CFG=CH_CFG_TYPE_TO_STRING[totalAudioCh][1],
        Local_CH=IDs["0"][:-3],
        Wireless_CH=IDs["1"][:-3])
def set_GroupMuteRsp_Handler(ui, rcvData):
    mute_status = getMuteUnMuteInfo()
    if rcvData[1] == 0x00:
        log = datetime.datetime.now().strftime("[%H:%M:%S]")
        log += "Set Group Mute done" if mute_status is 0 else "Set Group Unmute done"
        ui.log_TextBrowser.append(log)

        ui_context.update_mute_status(mute_status)

        # Update GUI
        # Mute - Update Table - Volume = Mute , DB is not updated
        gr_context = ui_context.Get_active_group_info(getActivateIdx())
        row_idx = 0
        if mute_status is 0:
            # Update Table
            for devIdx in gr_context['dev_info']:
                str_ch = ""
                for ch in gr_context['dev_info'][devIdx]['ch']:
                    str_ch += ch.upper() + '/'
                ui.WoWIF.TBL_UI.Update_AudioPlay_Speaker(row=row_idx,
                                                         id=devIdx,
                                                         str_ch=str_ch[:-1],
                                                         bit=None,
                                                         samp=None,
                                                         str_vol='Mute')
                row_idx += 1
        else:
            # Unmute - Update Table - Volume is restored by DB
            # Update Table
            for devIdx in gr_context['dev_info']:
                str_ch = ""
                for ch in gr_context['dev_info'][devIdx]['ch']:
                    str_ch += ch.upper() + '/'
                ui.WoWIF.TBL_UI.Update_AudioPlay_Speaker(
                    row=row_idx,
                    id=devIdx,
                    str_ch=str_ch[:-1],
                    bit=None,
                    samp=None,
                    str_vol=str(gr_context['dev_info'][devIdx]['vol']))
                row_idx += 1
    else:
        log = datetime.datetime.now().strftime("[%H:%M:%S]")
        log += " Set Group Mute/Unmute failed. Reason: "
        log += str(rcvData[1])
        ui.log_TextBrowser.append(log)
def get_WirelessInfoRet_Handler(ui, rcvData):
    log = datetime.datetime.now().strftime("[%H:%M:%S]")
    log += "Wireless Info Ret received"
    ui.log_TextBrowser.append(log)

    ui_context.Update_active_group_meas_info(clr_flag=True)
    gr_context = ui_context.Get_active_group_info(getActivateIdx())
    offset = 1
    totalRssi = []
    totalnPlayback = []
    totalnDrop = []
    totalnRcv = []
    totalnLoss = []
    totalsrtt = []
    totalLoss = []
    totalDrop = []
    print(rcvData)
    for dev_id in gr_context['dev_info']:
        rssi = int.from_bytes(rcvData[offset:offset + 4],
                              'little',
                              signed=True)
        offset += 4
        nPlayback = int.from_bytes(rcvData[offset:offset + 4], 'little')
        offset += 4
        nDrop = int.from_bytes(rcvData[offset:offset + 4], 'little')
        offset += 4
        nRcv = int.from_bytes(rcvData[offset:offset + 4], 'little')
        offset += 4
        nLoss = int.from_bytes(rcvData[offset:offset + 4], 'little')
        offset += 4
        srtt = int.from_bytes(rcvData[offset:offset + 4], 'little')
        offset += 4

        [dropPercent, lossPercent
         ] = ui_context.Update_active_group_meas_info(dev_id=dev_id,
                                                      rssi=rssi,
                                                      nPlayback=nPlayback,
                                                      nDrop=nDrop,
                                                      nRcv=nRcv,
                                                      nLoss=nLoss,
                                                      srtt=srtt)

        # Update SPK_UI for each speaker
        if gr_context['dev_info'][dev_id]['role'] != '0':
            for ch in gr_context['dev_info'][dev_id]['ch']:
                ui.WoWIF.SPK_UI.Update_Latency_Value(ch, srtt)
                ui.WoWIF.SPK_UI.Update_RSSI_Value(ch, rssi)
                ui.WoWIF.SPK_UI.Update_Loss_Value(ch, lossPercent)
                ui.WoWIF.SPK_UI.Update_Drop_Value(ch, dropPercent)

                totalRssi.append(rssi)
                totalnPlayback.append(nPlayback)
                totalnDrop.append(nDrop)
                totalnRcv.append(nRcv)
                totalnLoss.append(nLoss)
                totalsrtt.append(srtt)
                if lossPercent is not -1: totalLoss.append(lossPercent)
                if dropPercent is not -1: totalDrop.append(dropPercent)

    # print("[RSSI at Slaves]")
    # print(totalRssi)
    # print("[Number of Playback at Slaves]")
    # print(totalnPlayback)
    # print("[Number of Playback Drop at Slaves]")
    # print(totalnDrop)
    # print("[Number of Received Packet at Slaves]")
    # print(totalnRcv)
    # print("[Number of Loss Packet at Slaves]")
    # print(totalnLoss)
    # print("[SRTT at Slaves]")
    # print(totalsrtt)
    # print("[Percentage of packet loss at Slaves]")
    # print(totalLoss)
    # print("[Percentage of Playback drop at Slaves]")
    # print(totalDrop)

    # Update TBL_UI
    if len(totalRssi) > 0:
        ui.WoWIF.TBL_UI.Update_NetworkStat(
            RSSI=[min(totalRssi),
                  mean(totalRssi),
                  max(totalRssi)])
    if len(totalLoss) > 0:
        ui.WoWIF.TBL_UI.Update_NetworkStat(
            LossRate=[min(totalLoss),
                      mean(totalLoss),
                      max(totalLoss)])
    if len(totalDrop) > 0:
        ui.WoWIF.TBL_UI.Update_WoWPlay(
            Drop=[min(totalDrop),
                  mean(totalDrop),
                  max(totalDrop)])