#!/usr/bin/env python3

"""
    lldpmgrd

    LLDP manager daemon for SONiC

    Daemon which listens for changes in the PORT table of the State DB
    and updates LLDP configuration accordingly for that port by calling
    lldpcli.

    TODO: Also listen for changes in DEVICE_NEIGHBOR and PORT tables in
          Config DB and update LLDP config upon changes.
"""


try:
    import os
    import subprocess
    import sys
    import time
    import ctypes

    from sonic_py_common import daemon_base
    from swsscommon import swsscommon
    from sonic_py_common.interface import inband_prefix, recirc_prefix
    from sonic_py_common import device_info
    
    import stdout_read

except ImportError as err:
    raise ImportError("%s - required module not found" % str(err))

# Load the shared library
twamp_lib = ctypes.CDLL('/twampd/libtwamp_SONiC.01.01.so')  # For Linux/macOS

# Load cmshShowFunc on shared library
twamp_lib.cmshShowFunc.argtypes = []
twamp_lib.cmshShowFunc.restype = ctypes.c_char_p

# Load cmd on shared library
twamp_lib.cmdFuncEnterTwampLight.argtypes = []
twamp_lib.cmdFuncNoTwampLightDisable.argtypes = []
twamp_lib.cmdFuncTwampLightUdpPort.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampLightDelUdpPort.argtypes = []
twamp_lib.cmdFuncEnterTwampServer.argtypes = []
twamp_lib.cmdFuncNoTwampSvrEnable.argtypes = []
twamp_lib.cmdFuncEnterTwampServerKeychain.argtypes = []
twamp_lib.cmdFuncNoTwampServerKeychain.argtypes = []
twamp_lib.cmdFuncTwampServerKeyChainAdd.argtypes = [ctypes.c_char_p, ctypes.c_char_p]
twamp_lib.cmdFuncTwampServerKeyChainDel.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampSvrDscp.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncNoTwampSvrDscp.argtypes = []
twamp_lib.cmdFuncTwampSvrMaxConns.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampNoSvrMaxConns.argtypes = []
twamp_lib.cmdFuncTwampSvrMaxSessPerConns.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampNoSvrMaxSessPerConns.argtypes = []
twamp_lib.cmdFuncTwampSvrMode.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncNoTwampSvrMode.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampSvrTcpPort.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampNoSvrTcpPort.argtypes = []
twamp_lib.cmdFuncTwampSvrKeyCount.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampNoSvrKeyCount.argtypes = []
twamp_lib.cmdFuncTwampSvrMaxKeyCount.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampNoSvrMaxKeyCount.argtypes = []
twamp_lib.cmdFuncTwampBaseTestUdpPort.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampNoBaseTestUdpPort.argtypes = []
twamp_lib.cmdFuncTwampSvrControlTimeout.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampNoSvrControlTimeout.argtypes = []
twamp_lib.cmdFuncTwampShowServerStatus.argtypes = []
twamp_lib.cmdFuncTwampShowServerSessionAll.argtypes = []
twamp_lib.cmdFuncTwampShowServerSessionAllDetail.argtypes = []
twamp_lib.cmdFuncEnterTwampClient.argtypes = []
twamp_lib.cmdFuncNoTwampClient.argtypes = []
twamp_lib.cmdFuncEnterTwampClientMonitor.argtypes = []
twamp_lib.cmdFuncNoTwampClienMonitor.argtypes = []
twamp_lib.cmdFuncTwampClientMonitorMaxConnection.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientMonitorDelMaxConnection.argtypes = []
twamp_lib.cmdFuncTwampClientMonitorListenPort.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientMonitorDelListenPort.argtypes = []
twamp_lib.cmdFuncTwampClientMonitorSetClientIp.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientMonitorDelClientIp.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientMonitorNotifyInterval.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientMonitorDelNotifyInterval.argtypes = []
twamp_lib.cmdFuncEnterTwampClientModePreference.argtypes = []
twamp_lib.cmdFuncNoTwampClientModePreference.argtypes = []
twamp_lib.cmdFuncTwampClientModePreferenceChainAdd.argtypes = [ctypes.c_char_p, ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientModePreferenceChainDel.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncEnterTwampClientKeychain.argtypes = []
twamp_lib.cmdFuncNoTwampClientKeychain.argtypes = []
twamp_lib.cmdFuncTwampClientKeyChainAdd.argtypes = [ctypes.c_char_p, ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientKeyChainDel.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncEnterTwampClientControlConnection.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncNoTwampClientControlConnection.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientCtrlConnSetClientIp.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientCtrlConnDelClientIp.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientCtrlConnSetServerIp.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientCtrlConnDelServerIp.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientCtrlConnSetServerTcpPort.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientCtrlConnDelServerTcpPort.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientCtrlConnSetCtrlPktDscp.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientCtrlConnDelCtrlPktDscp.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientCtrlConnSetKeyId.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientCtrlConnDelKeyId.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientCtrlConnSetMaxCount.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientCtrlConnDelMaxCount.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncEnterTwampClientSessionRequest.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncNoTwampClientSessionRequest.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientSessReqSetSenderIp.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientSessReqDelSenderIp.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientSessReqSetSenderUdpPort.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientSessReqDelSenderUdpPort.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientSessReqSetReflectorIp.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientSessReqDelReflectorIp.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientSessReqSetReflectorUdpPort.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientSessReqDelReflectorUdpPort.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientSessReqSetTimeout.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientSessReqDelTimeout.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientSessReqTestPktDscp.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientSessReqDelTestPktDscp.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientSessReqRepeat.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientSessReqDelRepeat.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientSessReqRepeatInterval.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampClientSessReqDelRepeatInterval.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampShowClientStatus.argtypes = []
twamp_lib.cmdFuncTwampShowClientStatusDetail.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampShowClientSessions.argtypes = []
twamp_lib.cmdFuncTwampShowClientSessionsDetail.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncEnterTwampSender.argtypes = []
twamp_lib.cmdFuncNoTwampSender.argtypes = []
twamp_lib.cmdFuncEnterTwampSenderTestSession.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncNoTwampSenderTestSession.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampSenderTestSessionSetCtrlConnName.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampSenderTestSessionDelCtrlConnName.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampSenderTestSessionSetNumberOfPacket.argtypes = [ctypes.c_char_p, ctypes.c_char_p]
twamp_lib.cmdFuncTwampSenderTestSessionNoSetNumberOfPacket.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampSenderTestSessionSetInterval.argtypes = [ctypes.c_char_p, ctypes.c_char_p]
twamp_lib.cmdFuncTwampSenderTestSessionNoSetInterval.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampStartSenderSession.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampNoStartSenderSession.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampStartSenderLight.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p]
twamp_lib.cmdFuncTwampStartSenderLightInterval.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p]
twamp_lib.cmdFuncTwampStartSenderLightPort.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p]
twamp_lib.cmdFuncTwampStartSenderLightIntervalPort.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p]
twamp_lib.cmdFuncTwampNoStartSenderLight.argtypes = [ctypes.c_char_p, ctypes.c_char_p]
twamp_lib.cmdFuncTwampShowSenderStatus.argtypes = []
twamp_lib.cmdFuncTwampShowSenderSessions.argtypes = []
twamp_lib.cmdFuncTwampShowSenderSessionDetail.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampShowSenderLightAll.argtypes = []
twamp_lib.cmdFuncTwampShowSenderLightDetail.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampLightPing.argtypes = [ctypes.c_char_p]
twamp_lib.cmdFuncTwampLightPortPing.argtypes = [ctypes.c_char_p, ctypes.c_char_p]
twamp_lib.cmdFuncTwampLightCountPing.argtypes = [ctypes.c_char_p, ctypes.c_char_p]
twamp_lib.cmdFuncTwampLightCountPortPing.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p]

###
### twping
###
import threading
# Function to run C code in a thread
def run_twamd():
    print("Starting C function in a thread...")
    twamp_lib.start_twampd_so()
    print("twampd finished.")

thread = threading.Thread(target=run_twamd)
# Start the thread
thread.start()

##### init twamp ####
twamp_lib.twampInit.argtypes = []
#twamp_lib.twampInit.restype = None

# Call the C function from Python
#twamp_lib.start_twampd_so()  # Pass a byte string (C string)
#####################


VERSION = "1.0"

SYSLOG_IDENTIFIER = "twampd"
PORT_INIT_TIMEOUT = 300
FAILED_CMD_TIMEOUT = 6
RETRY_LIMIT = 5

CFG_TWAMP_LIGHT = "TWAMP_LIGHT"
CFG_TWAMP_SERVER = "TWAMP_SERVER"
CFG_TWAMP_CLIENT = "TWAMP_CLIENT"
CFG_TWAMP_SENDER = "TWAMP_SENDER"

SHOW_TWAMP_N2OS = "TWAMP_SHOW"


class TwampManager(daemon_base.DaemonBase):
    """
    Class which subscribes to notifications of changes in the PORT table of
    the Redis State database and updates TWAMP configuration accordingly for
    that port by calling lib_twamp.so.
    Attributes:
        state_db: Handle to Redis State database via swsscommon lib
        config_db: Handle to Redis Config database via swsscommon lib
        pending_cmds: Dictionary where key is port name, value is pending
                      LLDP configuration command to run 
                      and the last timestamp that this command was failed (used for retry mechanism)
    """
    REDIS_TIMEOUT_MS = 0

    def __init__(self, log_identifier):
        super(TwampManager, self).__init__(log_identifier)

        self.monitor_client_ip = []
        # Open a handle to the Config database
        self.config_db = swsscommon.DBConnector("CONFIG_DB",
                                                self.REDIS_TIMEOUT_MS,
                                                False)
                                                
        self.state_db = swsscommon.DBConnector("STATE_DB",
                                                self.REDIS_TIMEOUT_MS,
                                                False)
                                                
        self.twamp_state_table = swsscommon.Table(self.state_db, 'TWAMP')
        #self.twamp_cmsh_print = stdout_read.STDOUTCapture()

        
        #self.state_db = swsscommon.SonicV2Connector()
        #self.state_db.connect(state_db.STATE_DB)
       
            
            
    def twamp_process_light_table_event(self, key, op, fvp):
        print("twamp_process_light_table_event {}".format((key, op, fvp)))
        
        if key == 'server' and op == 'SET':
            ##############################################################
            ### config twamp light
            ##############################################################
            state = dict(fvp).get("state")
            if state == 'None': state = None
            if state == "on":
                twamp_lib.cmdFuncEnterTwampLight()
                print('Enter light server success')
            ##############################################################
            ### config twamp no light
            ##############################################################
            if state == "off":
                twamp_lib.cmdFuncNoTwampLightDisable()
                print('Set light server disable')
                
            ### config twamp (no) reflector-port <port>
            port = dict(fvp).get("reflector-port")
            if port == 'None': port = None
            if port:
                twamp_lib.cmdFuncTwampLightUdpPort(port.encode('utf-8'))
                print('set reflector-port command success {}'.format(port))
                
        elif '|' in key and op == 'SET':
            sender_ip = dict(fvp).get("sender-ip")
            reflector_ip = dict(fvp).get("reflector-ip")
            if key.split('|') == [sender_ip, reflector_ip]:
                reflector_port = dict(fvp).get("reflector-port")
                count = dict(fvp).get("count")
                interval = dict(fvp).get("interval")
                
                if reflector_port == 'None': reflector_port = None
                if count == 'None': count = None
                if interval == 'None': interval = None

                if sender_ip and reflector_ip and count and not reflector_port and not interval:
                    twamp_lib.cmdFuncTwampStartSenderLight(sender_ip.encode('utf-8'), reflector_ip.encode('utf-8'), count.encode('utf-8'))
                    print('RUN CMD config twamp start light sender A.B.C.D reflector A.B.C.D count <2-4294967295>')
                elif sender_ip and reflector_ip and count and interval and not reflector_port:
                    twamp_lib.cmdFuncTwampStartSenderLightInterval(sender_ip.encode('utf-8'), reflector_ip.encode('utf-8'), count.encode('utf-8'), interval.encode('utf-8'))
                    print('RUN CMD config twamp start light sender A.B.C.D reflector A.B.C.D count <2-4294967295> interval <1-4294967295>')
                elif sender_ip and reflector_ip and count and reflector_port and not interval:
                    twamp_lib.cmdFuncTwampStartSenderLightPort(sender_ip.encode('utf-8'), reflector_ip.encode('utf-8'), count.encode('utf-8'), reflector_port.encode('utf-8'))
                    print('RUN CMD config twamp start light sender {} reflector {} {} {}'.format(sender_ip, reflector_ip, reflector_port, count))
                
                elif sender_ip and reflector_ip and count and reflector_port and interval:
                    twamp_lib.cmdFuncTwampStartSenderLightIntervalPort(sender_ip.encode('utf-8'), reflector_ip.encode('utf-8'), count.encode('utf-8'), interval.encode('utf-8'), reflector_port.encode('utf-8'))
                    print('RUN CMD config twamp start light sender {} reflector {} {} {} interval {}'.format(sender_ip, reflector_ip, reflector_port, count, interval))
            elif not sender_ip and not reflector_ip:
                sender_ip = key.split('|')[0]
                reflector_ip = key.split('|')[1] 
                twamp_lib.cmdFuncTwampNoStartSenderLight(sender_ip.encode('utf-8'), reflector_ip.encode('utf-8'))
                print('RUN CMD config twamp no start light sender A.B.C.D reflector A.B.C.D')
                
        elif '|' in key and op == 'DEL':
            sender_ip = dict(fvp).get("sender-ip")
            reflector_ip = dict(fvp).get("reflector-ip")
            if not sender_ip and not reflector_ip:
                sender_ip = key.split('|')[0]
                reflector_ip = key.split('|')[1]
                twamp_lib.cmdFuncTwampNoStartSenderLight(sender_ip.encode('utf-8'), reflector_ip.encode('utf-8'))
                print('RUN CMD config twamp no start light sender A.B.C.D reflector A.B.C.D')
                
        data = '"""\n{}\n"""'.format(twamp_lib.cmshShowFunc().decode('utf-8'))
        print('cmd status:\n{}'.format(data))
            
            
    def twamp_process_server_table_event(self, key, op, fvp):
        print("twamp_process_server_table_event {}".format((key, op, fvp)))
        if key and op == 'SET':
        
            ### config twamp server
            state = dict(fvp).get("state")
            if state == 'None': state = None
            if state == 'on':
                twamp_lib.cmdFuncEnterTwampServer()
                print('Enter server command success')
                
            ### config twamp no server
            if state == "off":
                twamp_lib.cmdFuncNoTwampSvrEnable()
                print('Set server disable')
                
            ### config twamp server control-packet-dscp 0..255
            dscp = dict(fvp).get("control-packet-dscp")
            if dscp == 'None': dscp = None
            if not dscp:
                twamp_lib.cmdFuncNoTwampSvrDscp()
                print('Set dscp field as default')
            elif dscp:
                twamp_lib.cmdFuncTwampSvrDscp(dscp.encode('utf-8'))
                print('Set dscp field')
                
            ### config twamp server maximum-connections 1..100
            max_conn = dict(fvp).get("maximum-connections")
            if max_conn == 'None': max_conn = None
            if not max_conn:
                twamp_lib.cmdFuncTwampNoSvrMaxConns()
                print('Set maximum-connections field as default')
            elif max_conn:
                twamp_lib.cmdFuncTwampSvrMaxConns(max_conn.encode('utf-8'))
                print('Set maximum-connections field')
                
            ### config twamp server maximum-sessions-per-connection 1..100
            max_session = dict(fvp).get("maximum-sessions-per-connection")
            if max_session == 'None': max_session = None
            if not max_session:
                twamp_lib.cmdFuncTwampNoSvrMaxSessPerConns()
                print('Set maximum-sessions-per-connection field as default')
            elif max_session:
                twamp_lib.cmdFuncTwampSvrMaxSessPerConns(max_session.encode('utf-8'))
                print('Set maximum-sessions-per-connection field')
                
            ### config twamp server (no) mode (unauthenticated | authenticated | encrypted | mixed)
            mode = dict(fvp).get("mode")
            if mode == 'None': mode = None
            if not mode:
                twamp_lib.cmdFuncNoTwampSvrMode('unauthenticated'.encode('utf-8'))
                twamp_lib.cmdFuncNoTwampSvrMode('authenticated'.encode('utf-8'))
                twamp_lib.cmdFuncNoTwampSvrMode('encrypted'.encode('utf-8'))
                twamp_lib.cmdFuncNoTwampSvrMode('mixed'.encode('utf-8'))
                print('Set security-mode field as default')
            elif mode:
                twamp_lib.cmdFuncTwampSvrMode(mode.encode('utf-8'))
                print('Set security-mode field')
        
            ### config twamp server (no) server-tcp-port <port>
            port = dict(fvp).get("server-tcp-port")
            if port == 'None': port = None
            if not port:
                twamp_lib.cmdFuncTwampNoSvrTcpPort()
                print('Set server-tcp-port field as default')
            elif port:
                twamp_lib.cmdFuncTwampSvrTcpPort(port.encode('utf-8'))
                print('Set server-tcp-port field')
                
            ### config twamp server (no) max-count <count>
            max_count = dict(fvp).get("max-count")
            if max_count == 'None': max_count = None
            if not max_count:
                twamp_lib.cmdFuncTwampNoSvrMaxKeyCount()
                print('Set max-count field as default')
            elif max_count:
                twamp_lib.cmdFuncTwampSvrMaxKeyCount(max_count.encode('utf-8'))
                print('Set max-count field')
                
            ### config twamp server (no) count <count>
            count = dict(fvp).get("count")
            if count == 'None': count = None
            if not count:
                twamp_lib.cmdFuncTwampNoSvrKeyCount()
                print('Set count field as default')
            elif count:
                twamp_lib.cmdFuncTwampSvrKeyCount(count.encode('utf-8'))
                print('Set count field')
                
            ### config twamp server (no) base-test-port <port>
            port = dict(fvp).get("base-test-port")
            if port == 'None': port = None
            if not port:
                twamp_lib.cmdFuncTwampNoBaseTestUdpPort()
                print('Set base-test-port field as default')
            elif port:
                twamp_lib.cmdFuncTwampBaseTestUdpPort(port.encode('utf-8'))
                print('Set base-test-port field')
                
            ### config twamp server (no) serv-ref-wait <timeout>
            timeout = dict(fvp).get("serv-ref-wait")
            if timeout == 'None': timeout = None
            if not timeout:
                twamp_lib.cmdFuncTwampNoSvrControlTimeout()
                print('Set serv-ref-wait field as default')
            elif timeout:
                twamp_lib.cmdFuncTwampSvrControlTimeout(timeout.encode('utf-8'))
                print('Set serv-ref-wait field')
                
                
            ### config twamp server (no) key-chain key-id <> secret-key <>
            key_id = dict(fvp).get("key-chain-id")
            secret = dict(fvp).get("key-chain-secret")
            if key_id == 'None': key_id = None
            if secret == 'None': secret = None
            if not key_id and not secret:
                twamp_lib.cmdFuncEnterTwampServerKeychain()
                twamp_lib.cmdFuncNoTwampServerKeychain()
                print('Cleanup KeyChainList')
            elif not secret:
                twamp_lib.cmdFuncEnterTwampServerKeychain()
                twamp_lib.cmdFuncTwampServerKeyChainDel(key_id.encode('utf-8'))
                print('Delete key')
            elif key_id and secret:
                twamp_lib.cmdFuncEnterTwampServerKeychain()
                twamp_lib.cmdFuncTwampServerKeyChainAdd(key_id.encode('utf-8'), secret.encode('utf-8'))
                print('Initialize KeyChainList')
                
        data = '"""\n{}\n"""'.format(twamp_lib.cmshShowFunc().decode('utf-8'))
        print('cmd status:\n{}'.format(data))

    def twamp_process_client_table_event(self, key, op, fvp):
        print("twamp_process_client_table_event {}".format((key, op, fvp)))
        twamp_lib.cmdFuncEnterTwampClient()
        print('RUN CMD config twamp client')
        if key != 'monitor' :
            '''
            twamp client
            config twamp client mode-preference priority 1..3 mode <>
            '''
            if 'priority' in dict(fvp) and 'mode' in dict(fvp):
                priority = dict(fvp).get("priority")
                mode = dict(fvp).get("mode")
                if priority == 'None': priority = None
                if mode == 'None': mode = None
                if not priority and not mode:
                    ### config twamp client mode-preference no priority 1..3
                    twamp_lib.cmdFuncEnterTwampClientModePreference()
                    twamp_lib.cmdFuncTwampClientModePreferenceChainDel(key.encode('utf-8'))
                    print('RUN CMD config twamp client mode-preference no priority {}'.format(key))
                    
                elif priority and mode:
                    ### config twamp client mode-preference priority 1..3 node 
                    twamp_lib.cmdFuncEnterTwampClientModePreference()
                    twamp_lib.cmdFuncTwampClientModePreferenceChainAdd(priority.encode('utf-8'), mode.encode('utf-8'))
                    print('RUN CMD config twamp client mode-preference priority {} mode {}'.format(priority, mode))
            '''
            config twamp client key-chain (no) key-id <> secure-id <>
            '''
            if 'key-id' in dict(fvp) and 'secure-id' in dict(fvp):
                key_id = dict(fvp).get("key-id")
                secure_id = dict(fvp).get("secure-id")
                if key_id == 'None': key_id = None
                if secure_id == 'None': secure_id = None
                if not secure_id:
                    ### config twamp client key-chain no key-id <>
                    twamp_lib.cmdFuncEnterTwampClientKeychain()
                    twamp_lib.cmdFuncTwampClientModePreferenceChainDel(key.encode('utf-8'))
                    print('RUN CMD config twamp client key-chain no key-id {}'.format(key_id))
                    
                elif key_id and secure_id:
                    ### config twamp client key-chain key-id <> secure-id <>
                    twamp_lib.cmdFuncEnterTwampClientKeychain()
                    twamp_lib.cmdFuncTwampClientKeyChainAdd(key_id.encode('utf-8'), secure_id.encode('utf-8'))
                    print('RUN CMD config twamp client key-chain key-id {} secure-id {}'.format(key_id, secure_id))
                

            '''
            config twamp client (no) control-connection <>
            '''
            if 'connection-server' in dict(fvp):
                connection_server = dict(fvp).get("connection-server")
                if connection_server == 'None': connection_server = None

                if not connection_server:
                    ### config twamp client no control-connection <>
                    twamp_lib.cmdFuncNoTwampClientControlConnection(key.encode('utf-8'))
                    print('RUN CMD config twamp client no control-connection {}'.format(connection_server))
                    return

                elif connection_server:
                    ### config twamp client control-connection CONN-01
                    twamp_lib.cmdFuncEnterTwampClientControlConnection(connection_server.encode('utf-8'))
                    print('RUN CMD config twamp client control-connection {}'.format(connection_server))
                    
                '''
                config twamp client control-connection <> (no) client-ip <>
                '''
                if 'client-ip' in dict(fvp):
                    client_ip = dict(fvp).get("client-ip")
                    print('client_ip {}'.format(client_ip))
                    if client_ip == 'None': client_ip = None
                    if not client_ip:
                        ### config twamp client control-connection <> no client-ip
                        twamp_lib.cmdFuncTwampClientCtrlConnDelClientIp(key.encode('utf-8'))
                        print('RUN CMD config twamp client control-connection {} no client-ip {}'.format(connection_server))

                    elif client_ip and connection_server:
                        ### config twamp client control-connection <> client-ip <>
                        twamp_lib.cmdFuncTwampClientCtrlConnSetClientIp(client_ip.encode('utf-8'))
                        print('RUN CMD config twamp client control-connection {} client-ip {}'.format(connection_server, client_ip))
                    
                ''' 
                config twamp client control-connection <> (no) server-ip <>
                '''
                if 'server-ip' in dict(fvp):
                    server_ip = dict(fvp).get("server-ip")
                    print('server_ip {}'.format(server_ip))
                    if server_ip == 'None': server_ip = None
                    if not server_ip:
                        ### config twamp client control-connection <> no server-ip
                        twamp_lib.cmdFuncTwampClientCtrlConnDelServerIp(key.encode('utf-8'))
                        print('RUN CMD config twamp client control-connection {} no server-ip'.format(connection_server))

                        
                    elif server_ip and connection_server:
                        ### config twamp client control-connection <> server-ip <>
                        twamp_lib.cmdFuncTwampClientCtrlConnSetServerIp(server_ip.encode('utf-8'))
                        print('RUN CMD config twamp client control-connection {} server-ip {}'.format(connection_server, server_ip))
                    
                '''
                config twamp client control-connection <> (no) server-tcp-port <>
                '''
                if 'server-tcp-port' in dict(fvp):
                    port = dict(fvp).get("server-tcp-port")
                    if port == 'None': port = None
                    if not port:
                        ### config twamp client control-connection <> no server-tcp-port
                        twamp_lib.cmdFuncTwampClientCtrlConnDelServerTcpPort(key.encode('utf-8'))
                        print('RUN CMD config twamp client control-connection {} no server-tcp-port'.format(connection_server))
                        return
                        
                    elif port and connection_server:
                    
                        ### config twamp client control-connection <> server-tcp-port <>
                        twamp_lib.cmdFuncTwampClientCtrlConnSetServerTcpPort(port.encode('utf-8'))
                        print('RUN CMD config twamp client control-connection {} server-tcp-port {}'.format(connection_server, port))
                    
                '''
                config twamp client control-connection <> (no) control-packet-dscp <>
                '''
                if 'control-packet-dscp' in dict(fvp):
                    dscp = dict(fvp).get("control-packet-dscp")
                    if dscp == 'None': dscp = None
                    if not dscp:
                        ### config twamp client control-connection <> no control-packet-dscp
                        twamp_lib.cmdFuncTwampClientCtrlConnDelCtrlPktDscp(key.encode('utf-8'))
                        print('RUN CMD config twamp client control-connection {} no control-packet-dscp'.format(connection_server))
                        
                    elif dscp and connection_server:
                        ### config twamp client control-connection <> control-packet-dscp <>
                        twamp_lib.cmdFuncTwampClientCtrlConnSetCtrlPktDscp(dscp.encode('utf-8'))
                        print('RUN CMD config twamp client control-connection {} control-packet-dscp {}'.format(connection_server, dscp))
                    
                '''
                config twamp client control-connection <> (no) key-id <>
                '''
                if 'key-id' in dict(fvp):
                    key_id = dict(fvp).get("key-id")
                    if key_id == 'None': key_id = None
                    if not key_id:
                        ### config twamp client control-connection <> no key-id
                        twamp_lib.cmdFuncTwampClientCtrlConnDelKeyId(key.encode('utf-8'))
                        print('RUN CMD config twamp client control-connection {} no key-id'.format(connection_server))

                        
                    elif key_id and connection_server:
                        ### config twamp client control-connection <> key-id <>
                        twamp_lib.cmdFuncTwampClientCtrlConnSetKeyId(key_id.encode('utf-8'))
                        print('RUN CMD config twamp client control-connection {} key-id {}'.format(connection_server, key_id))
                    
                '''
                config twamp client control-connection <> (no) max-count <>
                '''
                if 'max-count' in dict(fvp):
                    max_count = dict(fvp).get("max-count")
                    if max_count == 'None': max_count = None
                    if not max_count:
                        ### config twamp client control-connection <> no max-count
                        twamp_lib.cmdFuncTwampClientCtrlConnDelMaxCount(key.encode('utf-8'))
                        print('RUN CMD config twamp client control-connection {} no max-count'.format(connection_server))

                        
                    elif max_count and connection_server:
                        ### config twamp client control-connection <> max-count <>
                        twamp_lib.cmdFuncTwampClientCtrlConnSetMaxCount(max_count.encode('utf-8'))
                        print('RUN CMD config twamp client control-connection {} max-count'.format(connection_server, max_count))

                '''
                ### config twamp client control-connection <> (no) session-request <>
                '''
                session_name = None
                if 'session-request-name' in dict(fvp):
                    session_name = dict(fvp).get("session-request-name")
                    if session_name == 'None': session_name = None
                    if not session_name:
                        ### config twamp client control-connection <> no session-request
                        twamp_lib.cmdFuncNoTwampClientSessionRequest(key.encode('utf-8'))
                        print('RUN CMD config twamp client control-connection {} no session-request'.format(connection_server))
                        return

                    elif session_name:
                        ### config twamp client control-connection <> session-request <>
                        twamp_lib.cmdFuncEnterTwampClientSessionRequest(session_name.encode('utf-8'))
                        print('RUN CMD config twamp client control-connection {} session-request {}'.format(connection_server, session_name))

                
                ### config twamp client control-connection <> session-request <> (no) sender-ip <>
                if 'sender-ip' in dict(fvp):
                    sender_ip = dict(fvp).get("sender-ip")
                    if sender_ip == 'None': sender_ip = None
                    if not sender_ip:
                        ### config twamp client control-connection <> session-request <> no sender-ip
                        twamp_lib.cmdFuncTwampClientSessReqDelSenderIp(key.encode('utf-8'))
                        print('RUN CMD config twamp client control-connection {} session-request {} no sender-ip'.format(connection_server, session_name))

                        
                    elif sender_ip and session_name:
                        ### config twamp client control-connection <> session-request <> sender-ip <>
                        twamp_lib.cmdFuncTwampClientSessReqSetSenderIp(sender_ip.encode('utf-8'))
                        print('RUN CMD config twamp client control-connection {} session-request {} sender-ip {}'.format(connection_server, session_name, sender_ip))
                    
                if 'reflector-ip' in dict(fvp):
                    ### config twamp client control-connection <> session-request <> (no) reflector-ip <>
                    reflector_ip = dict(fvp).get("reflector-ip")
                    if reflector_ip == 'None': reflector_ip = None
                    if not reflector_ip:
                        ### config twamp client control-connection <> session-request <> no reflector-ip
                        twamp_lib.cmdFuncTwampClientSessReqDelReflectorIp(key.encode('utf-8'))
                        print('RUN CMD config twamp client control-connection {} session-request {} no reflector-ip'.format(connection_server, session_name))

                        
                    elif reflector_ip and session_name:
                        ### config twamp client control-connection <> session-request <> reflector-ip <>
                        twamp_lib.cmdFuncTwampClientSessReqSetReflectorIp(reflector_ip.encode('utf-8'))
                        print('RUN CMD config twamp client control-connection {} session-request {} reflector-ip {}'.format(connection_server, session_name, reflector_ip))
                    
                    
                ### config twamp client control-connection <> session-request <> sender-udp-port <>
                if 'sender-udp-port' in dict(fvp):
                    sender_port = dict(fvp).get("sender-udp-port")
                    if sender_port == 'None': sender_port = None
                    if not sender_port:
                        ### config twamp client control-connection <> session-request <> no sender-udp-port
                        twamp_lib.cmdFuncTwampClientSessReqDelSenderUdpPort(key.encode('utf-8'))
                        print('RUN CMD config twamp client control-connection {} session-request {} no sender-udp-port'.format(connection_server, session_name))

                        
                    elif sender_port and session_name:
                        ### config twamp client control-connection <> session-request <> sender-udp-port <>
                        twamp_lib.cmdFuncTwampClientSessReqSetSenderUdpPort(sender_port.encode('utf-8'))
                        print('RUN CMD config twamp client control-connection {} session-request {} sender-udp-port {}'.format(connection_server, session_name, sender_port))
                    
                ### config twamp client control-connection <> session-request <> reflector-udp-port <>
                if 'reflector-udp-port' in dict(fvp):
                    reflector_port = dict(fvp).get("reflector-udp-port")
                    if reflector_port == 'None': reflector_port = None
                    if not reflector_port:
                        ### config twamp client control-connection <> session-request <> no reflector-udp-port
                        twamp_lib.cmdFuncTwampClientSessReqDelReflectorUdpPort(key.encode('utf-8'))
                        print('RUN CMD config twamp client control-connection {} session-request {} no reflector-udp-port'.format(connection_server, session_name))

                        
                    elif reflector_port and session_name:
                        ### config twamp client control-connection <> session-request <> reflector-udp-port <> 
                        twamp_lib.cmdFuncTwampClientSessReqSetReflectorUdpPort(reflector_port.encode('utf-8'))
                        print('RUN CMD config twamp client control-connection {} session-request {} reflector-udp-port {}'.format(connection_server, session_name, reflector_port))
                    
                ### config twamp client control-connection <> session-request <> timeout <>
                if 'timeout' in dict(fvp):
                    timeout = dict(fvp).get("timeout")
                    if timeout == 'None': timeout = None
                    if not timeout:
                        ### config twamp client control-connection <> session-request <> no timeout
                        twamp_lib.cmdFuncTwampClientSessReqDelTimeout(key.encode('utf-8'))
                        print('RUN CMD config twamp client control-connection {} session-request {} no timeout'.format(connection_server, session_name))

                        
                    elif timeout and session_name:
                        ### config twamp client control-connection <> session-request <> timeout <>
                        twamp_lib.cmdFuncTwampClientSessReqSetTimeout(timeout.encode('utf-8'))
                        print('RUN CMD config twamp client control-connection {} session-request {} timeout {}'.format(connection_server, session_name, timeout))
                    
                ### config twamp client control-connection <> session-request <> test-packet-dscp <>
                if 'test-packet-dscp' in dict(fvp):
                    dscp = dict(fvp).get("test-packet-dscp")
                    if dscp == 'None': dscp = None
                    if not dscp:
                        ### config twamp client control-connection <> session-request <> no test-packet-dscp#
                        twamp_lib.cmdFuncTwampClientSessReqDelTestPktDscp(key.encode('utf-8'))
                        print('RUN CMD config twamp client control-connection {} session-request {} no test-packet-dscp'.format(connection_server, session_name))

                        
                    elif dscp and session_name:
                        ## config twamp client control-connection <> session-request <> test-packet-dscp <>
                        twamp_lib.cmdFuncTwampClientSessReqTestPktDscp(dscp.encode('utf-8'))
                        print('RUN CMD config twamp client control-connection {} session-request {} test-packet-dscp {}'.format(connection_server, session_name, dscp))
                    
                ### config twamp client control-connection <> session-request <> repeat-interval <>
                if 'repeat-interval' in dict(fvp):
                    interval = dict(fvp).get("repeat-interval")
                    if interval == 'None': interval = None
                    if not interval:
                        ### config twamp client control-connection <> session-request <> no repeat-interval
                        twamp_lib.cmdFuncTwampClientSessReqDelRepeatInterval(key.encode('utf-8'))
                        print('RUN CMD config twamp client control-connection {} session-request {} no repeat-interval'.format(connection_server, session_name))
                        
                    elif interval and session_name:
                        ### config twamp client control-connection <> session-request <> repeat-interval <>
                        twamp_lib.cmdFuncTwampClientSessReqRepeatInterval(interval.encode('utf-8')) 
                        print('RUN CMD config twamp client control-connection {} session-request {} repeat-interval {}'.format(connection_server, session_name, interval))
                    
                ### config twamp client control-connection <> session-request <> (no) repeat <>
                if 'repeat' in dict(fvp):
                    repeat = dict(fvp).get("repeat")
                    if repeat == 'None': repeat = None
                    if not repeat:
                        ### config twamp client control-connection <> session-request <> no repeat
                        twamp_lib.cmdFuncTwampClientSessReqDelRepeat(key.encode('utf-8'))
                        print('RUN CMD config twamp client control-connection {} session-request {} no repeat'.format(connection_server, session_name))
                        
                    elif repeat and session_name:
                        ### config twamp client control-connection <> session-request <> repeat <>
                        twamp_lib.cmdFuncTwampClientSessReqRepeat(repeat.encode('utf-8'))
                        print('RUN CMD config twamp client control-connection {} session-request {} repeat {}'.format(connection_server, session_name, repeat))
                
            ### config twamp client monitor
        elif key == 'monitor':
            if not dict(fvp) :
                return

            twamp_lib.cmdFuncEnterTwampClientMonitor()
            print('RUN CMD config twamp client monitor')
                
            ### config twamp client monitor max-connection <>
            if 'max-connection' in dict(fvp):
                max_conn = dict(fvp).get("max-connection")
                if max_conn == 'None': max_conn = None
                if not max_conn:
                    ### config twamp client monitor no max-connection
                    twamp_lib.cmdFuncTwampClientMonitorDelMaxConnection()
                    print('RUN CMD config twamp client monitor no max-connection')
                    
                elif max_conn:
                    ### config twamp client monitor max-connection <>
                    twamp_lib.cmdFuncTwampClientMonitorMaxConnection(max_conn.encode('utf-8')) 
                    print('RUN CMD config twamp client monitor max-connection {}'.format(max_conn))
                
            ### config twamp client monitor interval <>
            if 'interval' in dict(fvp):
                interval = dict(fvp).get("interval")
                if interval == 'None': interval = None
                if not interval:
                    ### config twamp client monitor no interval
                    twamp_lib.cmdFuncTwampClientMonitorDelNotifyInterval()
                    print('RUN CMD config twamp client monitor no interval')

                    
                elif interval:
                    ### config twamp client monitor interval <>
                    twamp_lib.cmdFuncTwampClientMonitorNotifyInterval(interval.encode('utf-8')) 
                    print('RUN CMD config twamp client monitor interval {}'.format(interval))
                

            ### config twamp client monitor listen-tcp-port <>
            if 'listen-tcp-port' in dict(fvp):
                port = dict(fvp).get("listen-tcp-port")
                if port == 'None': port = None
                if not port:
                    ### config twamp client monitor no listen-tcp-port
                    twamp_lib.cmdFuncTwampClientMonitorDelListenPort()
                    print('RUN CMD config twamp client monitor no listen-tcp-port')
                    
                elif port:
                    ### config twamp client monitor listen-tcp-port <>
                    twamp_lib.cmdFuncTwampClientMonitorListenPort(port.encode('utf-8')) 
                    print('RUN CMD config twamp client monitor listen-tcp-port {}'.format(port))
                
                
            ### config twamp client monitor client-ip <>
            if 'client-ip' in dict(fvp):
                ip = dict(fvp).get("client-ip")
                ip_add = None
                ip_del = None
                if ip == 'None':
                    ip = None
                elif ip:
                    if ',' in ip:
                        ip = ip.split(',')[1:]
                    else:
                        ip = [ip]
                    for element in ip:
                        if element not in self.monitor_client_ip:
                            ip_add = element
                    for element in self.monitor_client_ip:
                        if element not in ip:
                            ip_del = element
                    self.monitor_client_ip = ip

                print('ip_del {}'.format(ip_del))
                print('ip_add {}'.format(ip_add))
                print('ip {}'.format(ip))
                print('self.monitor_client_ip {}'.format(self.monitor_client_ip))
                if not ip_del and not ip_add and len(self.monitor_client_ip) == 1 and not ip:
                    ip_del = self.monitor_client_ip[0]
                    self.monitor_client_ip = []
                if not ip:
                    self.monitor_client_ip = []
                
                if key == 'monitor' and ip_del :
                    ### config twamp client monitor no client-ip
                    twamp_lib.cmdFuncTwampClientMonitorDelClientIp(ip_del.encode('utf-8'))
                    print('RUN CMD config twamp client monitor no client-ip {}'.format(ip_del))
                    
                    
                elif key == 'monitor' and ip_add:
                    ### config twamp client monitor client-ip <>
                    twamp_lib.cmdFuncTwampClientMonitorSetClientIp(ip_add.encode('utf-8')) 
                    print('RUN CMD config twamp client monitor client-ip {}'.format(ip_add))
                    
        data = '"""\n{}\n"""'.format(twamp_lib.cmshShowFunc().decode('utf-8'))
        print('cmd status:\n{}'.format(data))
                
                
    def twamp_process_sender_table_event(self, key, op, fvp):
        print("twamp_process_sender_table_event {}".format((key, op, fvp)))
        
        if op == 'SET' or op == 'DEL':  
            twamp_lib.cmdFuncEnterTwampSender()
            print('RUN CMD config twamp sender')
            ### config twamp start sender session <>

            status = dict(fvp).get("status")
            if status == 'None': status = None
            if status == 'running':
                twamp_lib.cmdFuncTwampStartSenderSession(key.encode('utf-8'))
                print('RUN CMD config twamp start sender session {}'.format(key))
                return
            elif status == 'stopped':
                twamp_lib.cmdFuncTwampNoStartSenderSession(key.encode('utf-8'))
                print('RUN CMD config twamp no start sender session {}'.format(key))
                return
                
            
            ### config twamp sender test-session <>
            if "session-name" in dict(fvp):
                test_session = dict(fvp).get("session-name")
                if test_session == 'None': test_session = None
                if not test_session:
                    ### config twamp sender no test-session <>
                    twamp_lib.cmdFuncNoTwampSenderTestSession(key.encode('utf-8')) 
                    print('RUN CMD config twamp sender no test-session')
                elif test_session:
                    twamp_lib.cmdFuncEnterTwampSenderTestSession(key.encode('utf-8')) 
                    print('RUN CMD config twamp sender test-session {}'.format(test_session))
                    
                ### config twamp sender test-session <> control-connection-name <>
                conn_name = dict(fvp).get("control-connection-name")
                if conn_name == 'None': conn_name = None
                if not conn_name:
                    ### config twamp sender test-session <> no control-connection-name <>
                    twamp_lib.cmdFuncTwampSenderTestSessionDelCtrlConnName(test_session.encode('utf-8'))
                    print('RUN CMD config twamp sender test-session {} no control-connection-name'.format(test_session))
                    
                elif conn_name:
                    twamp_lib.cmdFuncTwampSenderTestSessionSetCtrlConnName(test_session.encode('utf-8'), conn_name.encode('utf-8')) 
                    print('RUN CMD config twamp sender test-session {} control-connection-name {}'.format(test_session, conn_name))
                    
                ### config twamp sender test-session <> number-of-packet <>
                pack_num = dict(fvp).get("number-of-packet")
                if pack_num == 'None': pack_num = None
                if not pack_num:
                    ### config twamp sender test-session <> no number-of-packet <>
                    twamp_lib.cmdFuncTwampSenderTestSessionNoSetNumberOfPacket(test_session.encode('utf-8'))
                    print('RUN CMD config twamp sender test-session {} no number-of-packet'.format(test_session))
                    
                elif pack_num:
                    twamp_lib.cmdFuncTwampSenderTestSessionSetNumberOfPacket(test_session.encode('utf-8'), pack_num.encode('utf-8'))
                    print('RUN CMD config twamp sender test-session {} number-of-packet {}'.format(test_session, pack_num))
                    
            data = '"""\n{}\n"""'.format(twamp_lib.cmshShowFunc().decode('utf-8'))
            print('cmd status:\n{}'.format(data))

    def sst_twamp_show_n2os_event(self, key, op, fvp):
        print("sst_twamp_show_n2os_event_event {}".format((key, op, fvp)))
        command = dict(fvp).get("command")
        if key == 'light' and op == 'SET':
            if command == 'status':
                pass
        print('RUN CMD show twamp {} {}'.format(key, command))
        
        if key == 'server' and op == 'SET':
            
            if command == 'status':
                twamp_lib.cmdFuncTwampShowServerStatus()
                
            if command == 'session':
                twamp_lib.cmdFuncTwampShowServerSessionAll()
            if command == 'session-detail':
                twamp_lib.cmdFuncTwampShowServerSessionAllDetail()
                
            data = '"""\n{}\n"""'.format(twamp_lib.cmshShowFunc().decode('utf-8'))
            print('show str:\n{}'.format(data))
            fvs = swsscommon.FieldValuePairs([('json_str', data)])
            self.twamp_state_table.set('server', fvs)
        
        if key == 'client' and op == 'SET':
            if command == 'status':
                twamp_lib.cmdFuncTwampShowClientStatus()
            if 'status ' in command:
                twamp_lib.cmdFuncTwampShowClientStatusDetail(command.split(' ')[1].encode('utf-8'))
            if command == 'session':
                twamp_lib.cmdFuncTwampShowClientSessions()
            if 'session ' in command:
                twamp_lib.cmdFuncTwampShowClientSessionsDetail(command.split(' ')[1].encode('utf-8'))
        
            data = '"""\n{}\n"""'.format(twamp_lib.cmshShowFunc().decode('utf-8'))
            print('show str:\n{}'.format(data))
            fvs = swsscommon.FieldValuePairs([('json_str', data)])
            self.twamp_state_table.set('client', fvs)
            
        if key == 'sender' and op == 'SET':
            
            if command == 'status':
                twamp_lib.cmdFuncTwampShowSenderStatus()
            if command == 'session':
                twamp_lib.cmdFuncTwampShowSenderSessions()
            if 'session ' in command:
                twamp_lib.cmdFuncTwampShowSenderSessionDetail(command.split(' ')[1].encode('utf-8'))
                
            if command == 'light':
                twamp_lib.cmdFuncTwampShowSenderLightAll()
            if 'light ' in command:
                twamp_lib.cmdFuncTwampShowSenderLightDetail(command.split(' ')[1].encode('utf-8'))
                
            data = '"""\n{}\n"""'.format(twamp_lib.cmshShowFunc().decode('utf-8'))
            print('show str:\n{}'.format(data))
            #json_str = stdout_read.light_test_session_parse(data)
            fvs = swsscommon.FieldValuePairs([('json_str', data)])
            self.twamp_state_table.set('sender', fvs)
                
                
        if key == 'twping' and op == 'SET':
            count = 1
            state = 'PING'
            ip = None
            session = None
            if 'state' in dict(fvp):
                state = dict(fvp).get('state')
            if 'session-name' in dict(fvp):
                session = dict(fvp).get('session-name')
                
            if 'address' in dict(fvp):
                ip = dict(fvp).get('address')
            if 'count' in dict(fvp):
                count = dict(fvp).get('count')
            
            if state == 'PING' and ip and count:
                print('show twping {} count {}'.format(ip, count))
                #with self.twamp_cmsh_print:
                if count ==  '1':
                    twamp_lib.cmdFuncTwampLightPing(ip.encode('utf-8'))
                else:
                    twamp_lib.cmdFuncTwampLightCountPing(ip.encode('utf-8'), count.encode('utf-8'))

                data = '"""\n{}\n"""'.format(twamp_lib.cmshShowFunc().decode('utf-8'))
                print('show str:\n{}'.format(data))
                json_str = stdout_read.twping_parse(data)
                fvs = swsscommon.FieldValuePairs([('json_str', json_str)])
                self.twamp_state_table.set('twping', fvs)
                #print('show str:\n{}'.format(json_str))
                #print('show str:\n{}'.format(fvs))
            if state == 'START' and session:
                pass
            if state == 'STOP' and session:
                pass

            #if 'session-count' in dict(fvp): 
            #if 'server-tcp-port' in dict(fvp):
            #if 'mode' in dict(fvp):
            #if 'key-id' in dict(fvp):
            #if 'secret-key' in dict(fvp):


    def run(self):
        """
        Subscribes to notifications of changes in the PORT table
        of the Redis Config/Application database.
        Subscribe to APP_DB - get port oper status
        Subscribe to CONFIG_DB - get notified of port config changes
        Update LLDP configuration accordingly.
        """
        self.log_info("Starting up...")

        if not os.geteuid() == 0:
            self.log_error("Must be root to run this daemon")
            print("Error: Must be root to run this daemon")
            sys.exit(1)

        # Set select timeout to 10 seconds
        SELECT_TIMEOUT_MS = 1000 * 1

        # Daemon is paused on the configuration file to avoid lldp packets with wrong information
        # until all interfaces are well configured on lldpd
        resume_twamp_sent = False
        start_time = time.time()

        sel = swsscommon.Select()

        #define CFG_TWAMP_LIGHT                             "TWAMP_LIGHT"
        #define CFG_TWAMP_SERVER                            "TWAMP_SERVER"
        #define CFG_TWAMP_CLIENT                            "TWAMP_CLIENT"
        #define CFG_TWAMP_SENDER                            "TWAMP_SENDER"

        # Subscribe to TWAMP_LIGHT table notifications in the Config DB
        sst_twamp_light_confdb = swsscommon.SubscriberStateTable(self.config_db, CFG_TWAMP_LIGHT)
        sel.addSelectable(sst_twamp_light_confdb)
        
        # Subscribe to TWAMP_SERVER table notifications in the Config DB
        sst_twamp_server_confdb = swsscommon.SubscriberStateTable(self.config_db, CFG_TWAMP_SERVER)
        sel.addSelectable(sst_twamp_server_confdb)
        
        # Subscribe to TWAMP_CLIENT table notifications in the Config DB
        sst_twamp_client_confdb = swsscommon.SubscriberStateTable(self.config_db, CFG_TWAMP_CLIENT)
        sel.addSelectable(sst_twamp_client_confdb)
        
        # Subscribe to TWAMP_SENDER table notifications in the Config DB
        sst_twamp_sender_confdb = swsscommon.SubscriberStateTable(self.config_db, CFG_TWAMP_SENDER)
        sel.addSelectable(sst_twamp_sender_confdb)
        
        
        sst_twamp_show_n2os = swsscommon.SubscriberStateTable(self.config_db, SHOW_TWAMP_N2OS)
        sel.addSelectable(sst_twamp_show_n2os)

        # Listen for changes to the TWAMP table in the CONFIG_DB and APP_DB
        startup = True 
        while True:
            (state, selectableObj) = sel.select(SELECT_TIMEOUT_MS)

            if state == swsscommon.Select.OBJECT:
                if selectableObj.getFd() == sst_twamp_light_confdb.getFd():
                    (key, op, fvp) = sst_twamp_light_confdb.pop()
                    self.twamp_process_light_table_event(key, op, fvp)
                    
                elif selectableObj.getFd() == sst_twamp_server_confdb.getFd():
                    (key, op, fvp) = sst_twamp_server_confdb.pop()

                    self.twamp_process_server_table_event(key, op, fvp)
                    
                elif selectableObj.getFd() == sst_twamp_client_confdb.getFd():
                    (key, op, fvp) = sst_twamp_client_confdb.pop()

                    self.twamp_process_client_table_event(key, op, fvp)
                    
                elif selectableObj.getFd() == sst_twamp_sender_confdb.getFd():
                    (key, op, fvp) = sst_twamp_sender_confdb.pop()

                    self.twamp_process_sender_table_event(key, op, fvp)
                    
                elif selectableObj.getFd() == sst_twamp_show_n2os.getFd():
                    (key, op, fvp) = sst_twamp_show_n2os.pop()

                    self.sst_twamp_show_n2os_event(key, op, fvp)
                #self.log_error("Got unexpected selectable object")


# ============================= Functions =============================


def main():
    # Instantiate a TwampManager object
    
    twamp = TwampManager(SYSLOG_IDENTIFIER)

    # Log all messages from INFO level and higher
    twamp.set_min_log_priority_info()

    twamp.run()



def check_timeout(self, start_time):
    if time.time() - start_time > PORT_INIT_TIMEOUT:
        if device_info.is_frontend_port_present_in_host():
            self.log_error("Port init timeout reached ({} seconds), resuming lldpd...".format(PORT_INIT_TIMEOUT))
        return True
    return False


if __name__ == "__main__":
    main()
