def clickedConnect():
     try:
         if App.nodeId.get() == '':
             messagebox.showwarning("Warging", 'nodeId is necessary')
             return
         selectTab = tabControl.tab(tabControl.select(), 'text')
         edgeAgentOptions = EdgeAgentOptions(nodeId=App.nodeId.get())
         if selectTab == 'MQTT':
             edgeAgentOptions.connectType = constant.ConnectType['MQTT']
             mqttOptions = MQTTOptions(hostName=App.hostName.get(),
                                       port=App.port.get(),
                                       userName=App.userName.get(),
                                       password=App.password.get())
             edgeAgentOptions.MQTT = mqttOptions
         elif selectTab == 'DCCS':
             edgeAgentOptions.connectType = constant.ConnectType['DCCS']
             dccsOptions = DCCSOptions(
                 apiUrl=App.apiUrl.get(),
                 credentialKey=App.credentialKey.get())
             edgeAgentOptions.DCCS = dccsOptions
         if self._edgeAgent is None:
             self._edgeAgent = EdgeAgent(edgeAgentOptions)
             self._edgeAgent.on_connected = on_connected
             self._edgeAgent.on_disconnected = on_disconnected
             self._edgeAgent.on_message = on_message
         self._edgeAgent.connect()
     except ValueError as error:
         messagebox.showwarning("Warging", str(error))
Example #2
0
        def connect():
            edgeAgentOptions = EdgeAgentOptions(nodeId="04f2206c-a6d5-44d5-ae02-375fc29b8079")
            edgeAgentOptions.connectType = constant.ConnectType['DCCS']
            dccsOptions = DCCSOptions(apiUrl="https://api-dccs-ensaas.sa.wise-paas.com/", credentialKey="c7b005554b8d527a1fdf2137aea055l7")
            edgeAgentOptions.DCCS = dccsOptions

            if self.edgeAgent is None:
                self.edgeAgent = EdgeAgent(edgeAgentOptions)
                self.edgeAgent.on_connected = onConnected
                self.edgeAgent.on_disconnected = onDisconnected
                self.edgeAgent.on_message = onMessage

            self.edgeAgent.connect()
Example #3
0
    deviceConfig.discreteTagList.append(discrete)

    text = TextTagConfig(name='TTag1',
                         description='TTag1',
                         readOnly=False,
                         arraySize=0)
    deviceConfig.textTagList.append(text)

    config.node.deviceList.append(deviceConfig)
    return config


_edgeAgent = None
edgeAgentOptions = EdgeAgentOptions(
    nodeId='568173b8-638b-46d6-a58f-ae7c8056f003')
edgeAgentOptions.connectType = constant.ConnectType['DCCS']
dccsOptions = DCCSOptions(apiUrl='https://api-dccs-ensaas.sa.wise-paas.com/',
                          credentialKey='b37a19560cc7473403444507b500ef0k')
edgeAgentOptions.DCCS = dccsOptions
_edgeAgent = EdgeAgent(edgeAgentOptions)
_edgeAgent.on_connected = on_connected
_edgeAgent.on_disconnected = on_disconnected
_edgeAgent.on_message = edgeAgent_on_message

_edgeAgent.connect()

time.sleep(5)  # Waiting for connection to be established

for i in range(1, 60):
    __sendData()
    time.sleep(1)
    MQTT=MQTTOptions(                                   # If connectType is MQTT, must fill this options
        hostName="127.0.0.1",
        port=1883,
        userName="******",
        password="******",
        # MQTT protocal (TCP, Websocket), default is TCP
        protocalType=constant.Protocol['TCP']
    ),
    DCCS=DCCSOptions(
        apiUrl="https://api-dccs-ensaas.sa.wise-paas.com/",         # DCCS API Url
        # credentialKey="c49fe0af415c5b79d6ab10d1b13acfp1"  # Creadential key
        credentialKey="fce6538e82e18a85a0560315652e03ti"  # Creadential key
    )
)

edge_agent = EdgeAgent(options=options)


def generate_data(data, device_id, tag_name, value):
    tag = EdgeTag(device_id, tag_name, value)
    data.tagList.append(tag)


def send_data(data):
    edge_agent.sendData(data=data)


def handler_on_connected(agent, isConnected):
    # Connected: when EdgeAgent is connected to IoTHub.
    print("Connected successfully")
Example #5
0
class App():

    def __init__(self):
        self.edgeAgent = None
        self.timer = None

        # 정상 상태
        normalHeartRateStandard = 135  # 태아의 심박수 기준
        normalHeartRateDeviation = 10  # 태아가 정상 상태일 때 심박수 편차
        normalHeartRateMaxVariance = 2  # 태아가 정상 상태일 때 초당 심박수 최대 변화량
        probabilityToNormalStatus = 500  # 태아가 정상 상태로 돌아올 확률 (value / 10000)

        # 심박수 불규칙 상태
        irregularHeartRateDeviation = 20  # 태아의 심박수가 불규칙적일 때 심박수 편차
        irregularHeartRateMaxVariance = 6  # 태아의 심박수가 불규칙적일 때 초당 심박수 최대 변화량
        probabilityToIrregularHeartRateStatus = 5  # 태아의 심박수가 불규칙적으로 변하게 될 확률 (value / 10000)

        # 높은 심박수 상태
        highHeartRateIncrease = 25  # 태아의 심박수가 높은 상태일 때 심박수 기준 상승치
        highHeartRateDeviation = 15  # 태아의 심박수가 높은 상태일 때 심박수 편차
        highHeartRateMaxVariance = 2.8  # 태아의 심박수가 높은 상태일 때 초당 심박수 최대 변화량
        probabilityToHighHeartRateStatus = 5000  # 태아의 심박수가 높은 상태로 변하게 될 확률 (value / 10000)

        # 낮은 심박수 상태
        lowHeartRateDecrease = 20  # 태아의 심박수가 낮은 상태일 때 심박수 기준 하락치
        lowHeartRateDeviation = 6  # 태아의 심박수가 낮은 상태일 때 심박수 편차
        lowHeartRateMaxVariance = 1.2  # 태아의 심박수가 낮은 상태일 때 초당 심박수 최대 변화량
        probabilityToLowHeartRateStatus = 10  # 태아의 심박수가 낮은 상태로 변하게 될 확률 (value / 10000)

        # 상태 변화까지 최소 카운트 (value / 10)초
        minCountUntilStatusVariation = 900

        # 추세
        upDownMaxVariation = 15
        probabilityToUpDown = 100  # 추세가 바뀔 확률

        # 심박수 급락
        suddenDropAmount = 10  # 심박수가 급락할 때 그 정도
        probabilityOfSuddenDrop = 15  # 심박수가 급락할 확률 (value / 10000)

        # 태동 버튼
        probabilityToPressButton = 500  # 태아의 심박수가 높은 상태일 때 임산부가 버튼을 누를 확률 (value / 10000)
        minIntervalToPressButton = 150  # 임산부가 버튼을 누르는 최소 간격 (value / 10)초

        # 현재 수치
        self.fetalStatus = 'normal'
        self.heartRate = normalHeartRateStandard
        self.preHeartRate = self.heartRate
        self.count = 0
        self.trend = 0
        self.buttonCount = 0
        self.suddenDropCount = 21

        print("normal heart rate standard : " + str(normalHeartRateStandard))

        # function
        def connect():
            edgeAgentOptions = EdgeAgentOptions(nodeId="04f2206c-a6d5-44d5-ae02-375fc29b8079")
            edgeAgentOptions.connectType = constant.ConnectType['DCCS']
            dccsOptions = DCCSOptions(apiUrl="https://api-dccs-ensaas.sa.wise-paas.com/", credentialKey="c7b005554b8d527a1fdf2137aea055l7")
            edgeAgentOptions.DCCS = dccsOptions

            if self.edgeAgent is None:
                self.edgeAgent = EdgeAgent(edgeAgentOptions)
                self.edgeAgent.on_connected = onConnected
                self.edgeAgent.on_disconnected = onDisconnected
                self.edgeAgent.on_message = onMessage

            self.edgeAgent.connect()

        def onConnected(edgeAgent, isConnected):
            if isConnected:
                print("connected")

        def onDisconnected(edgeAgent, isDisconnected):
            if isDisconnected:
                self.edgeAgent = None
                self.timer = None
                print("disconnected")

        def onMessage(edgeAgent, message):
            if message.type == constant.MessageType['ConfigAck']:
                response = 'Upload Config Result: {0}'.format(str(message.message.result))
            elif message.type == constant.MessageType['WriteValue']:
                message = message.message
                for device in message.deviceList:
                    print("deviceId: {0}".format(device.id))
                    for tag in device.tagList:
                        print("tagName: {0}, Value: {1}".format(tag.name, str(tag.value)))

        def generateConfig():
            config = EdgeConfig()
            nodeConfig = NodeConfig(nodeType=constant.EdgeType['Gateway'])
            config.node = nodeConfig

            deviceConfig = DeviceConfig(id='Device', name='Device', description='Device', deviceType='Smart Device', retentionPolicyName='')
            heartRateAnalogConfig = AnalogTagConfig(name='heart rate', description='heart rate', readOnly=False, arraySize=0, spanHigh=1000, spanLow=0, engineerUnit='', integerDisplayFormat=4, fractionDisplayFormat=1)
            fetalMovementAnalogConfig = AnalogTagConfig(name='fetal movement', description='fetal movement', readOnly=False, arraySize=0, spanHigh=1000, spanLow=0, engineerUnit='', integerDisplayFormat=4, fractionDisplayFormat=1)
            uterineContractionAnalogConfig = AnalogTagConfig(name='uterine contraction', description='uterine contraction', readOnly=False, arraySize=0, spanHigh=1000, spanLow=0, engineerUnit='', integerDisplayFormat=4, fractionDisplayFormat=1)
            fetalMovementButtonPressedAnalogConfig = AnalogTagConfig(name='fetal movement pressed', description='fetal movement pressed', readOnly=False, arraySize=0, spanHigh=1000, spanLow=0, engineerUnit='', integerDisplayFormat=4, fractionDisplayFormat=1)

            deviceConfig.analogTagList.append(heartRateAnalogConfig)
            deviceConfig.analogTagList.append(fetalMovementAnalogConfig)
            deviceConfig.analogTagList.append(uterineContractionAnalogConfig)
            deviceConfig.discreteTagList.append(fetalMovementButtonPressedAnalogConfig)
            config.node.deviceList.append(deviceConfig)

            return config

        def generateData():
            edgeData = EdgeData()
            chance = random.randint(1, 10000)

            self.count += 1
            self.buttonCount += 1

            if self.count >= minCountUntilStatusVariation:
                if self.fetalStatus == 'normal':  # 태아가 정상 상태일 때
                    if chance <= probabilityToIrregularHeartRateStatus:
                        self.fetalStatus = 'irregular heart rate'
                        self.count = 0

                    elif self.heartRate > normalHeartRateStandard + normalHeartRateDeviation:  # 태아의 심박수가 높은 편일 때
                        if 2000 < chance <= probabilityToHighHeartRateStatus + 2000:
                            self.fetalStatus = 'high heart rate'
                            self.count = 0

                    elif self.heartRate < normalHeartRateStandard - normalHeartRateDeviation:  # 태아의 심박수가 낮은 편일 때
                        if 4000 < chance <= probabilityToLowHeartRateStatus + 4000:
                            self.fetalStatus = 'low heart rate'
                            self.count = 0

                else:  # 태아가 정상 상태가 아닐 때
                    if chance <= probabilityToNormalStatus:
                        if self.fetalStatus == 'irregular heart rate':  # 불규칙 상태에서 정상으로 돌아올 때 바로 정상 수치 주변으로 돌아오도록 함
                            self.heartRate = normalHeartRateStandard + self.trend

                        self.fetalStatus = 'normal'
                        self.count = 0

            chance = random.randint(1, 10000)

            if chance <= probabilityToUpDown and self.fetalStatus != 'irregular heart rate':
                self.trend += random.randint(-upDownMaxVariation / 3, upDownMaxVariation / 3)
                if self.trend > upDownMaxVariation:
                    self.trend = upDownMaxVariation
                elif self.trend < -upDownMaxVariation:
                    self.trend = -upDownMaxVariation

            def genHeartRateData():
                power = 8
                standard = self.trend;
                maxVariation = 0;
                deviation = self.trend;
                restorationProbabilityInRange = 0
                restorationProbabilityOutRange = 0
                decreaseBonus = 0
                increaseBonus = 0

                chance = random.randint(1, 10000)

                if self.fetalStatus == 'normal':
                    standard += normalHeartRateStandard
                    maxVariation = normalHeartRateMaxVariance
                    deviation += normalHeartRateDeviation
                    restorationProbabilityInRange = 5100
                    restorationProbabilityOutRange = 6000

                    if self.preHeartRate > self.heartRate:
                        increaseBonus = 2000
                    else:
                        decreaseBonus = 2000

                elif self.fetalStatus == 'irregular heart rate':
                    standard += normalHeartRateStandard
                    maxVariation = irregularHeartRateMaxVariance
                    deviation += irregularHeartRateDeviation
                    restorationProbabilityInRange = 7000
                    restorationProbabilityOutRange = 10000

                elif self.fetalStatus == 'high heart rate':
                    standard += normalHeartRateStandard + highHeartRateIncrease
                    maxVariation = highHeartRateMaxVariance
                    deviation += highHeartRateDeviation
                    restorationProbabilityInRange = 5100
                    restorationProbabilityOutRange = 6000

                elif self.fetalStatus == 'low heart rate':
                    standard += normalHeartRateStandard - lowHeartRateDecrease
                    maxVariation = lowHeartRateMaxVariance
                    deviation += lowHeartRateDeviation
                    restorationProbabilityInRange = 5100
                    restorationProbabilityOutRange = 6000

                # sudden drop인 경우 복원하기
                if self.suddenDropCount <= 20:
                    self.heartRate += (suddenDropAmount / 5) * pow(suddenDropAmount, (-self.suddenDropCount / 10))
                    self.suddenDropCount += 1

                # 범위에 있을 때 확률적으로 sudden drop
                if standard + deviation >= self.heartRate >= standard - deviation:
                    if chance <= probabilityOfSuddenDrop and self.suddenDropCount > 20:
                        self.heartRate -= suddenDropAmount
                        self.suddenDropCount = 0
                        # print("sudden drop!")

                    if standard > self.heartRate:
                        if chance <= restorationProbabilityInRange + increaseBonus:
                            self.heartRate += pow(random.uniform(0, 1), power) * maxVariation
                        else:
                            self.heartRate -= pow(random.uniform(0, 1), power) * maxVariation
                    else:
                        if chance <= restorationProbabilityInRange + decreaseBonus:
                            self.heartRate -= pow(random.uniform(0, 1), power) * maxVariation
                        else:
                            self.heartRate += pow(random.uniform(0, 1), power) * maxVariation
                elif self.heartRate > standard + deviation:
                    if chance <= restorationProbabilityOutRange + decreaseBonus:
                        self.heartRate -= pow(random.uniform(0, 1), power) * maxVariation
                    else:
                        self.heartRate += pow(random.uniform(0, 1), power) * maxVariation
                else:
                    if chance <= restorationProbabilityOutRange + increaseBonus:
                        self.heartRate += pow(random.uniform(0, 1), power) * maxVariation
                    else:
                        self.heartRate -= pow(random.uniform(0, 1), power) * maxVariation

                tag = EdgeTag('Device', 'heart rate', self.heartRate)
                edgeData.tagList.append(tag)
                print("generate heart rate data : " + str(self.heartRate) + " (" + self.fetalStatus + "), (" + str(standard) + ")")

            def genButtonPressedData():
                if chance <= probabilityToPressButton and self.fetalStatus != 'irregular heart rate' and self.heartRate > 160 and self.buttonCount > minIntervalToPressButton:
                    tag = EdgeTag('Device', 'fetal movement pressed', 100)
                    edgeData.tagList.append(tag)
                    print("generate button pressed data")
                    self.buttonCount = 0

            genHeartRateData()
            genButtonPressedData()

            return edgeData

        def sendData():
            data = generateData()
            self.edgeAgent.sendData(data)

        def start():
            connect()

            _config = generateConfig()
            self.edgeAgent.uploadConfig(action=constant.ActionType['Create'], edgeConfig=_config)

            frequency = 0.1

            if self.timer is None:
                self.timer = RepeatedTimer(frequency, sendData)
                sendData()

        t = threading.Thread(target=start)
        t.start()
class App():
    def __init__(self, master=None):
        self._edgeAgent = None
        self.timer = None
        self.master = master
        master.title('SDK Test')
        master.geometry('580x240')

        # create a tab control
        tabControl = ttk.Notebook(master)
        # create a tab
        dccsTab = ttk.Frame(tabControl, width=200, height=100)
        tabControl.add(dccsTab, text='DCCS')
        tabControl.grid(column=0,
                        row=0,
                        rowspan=2,
                        columnspan=2,
                        padx=8,
                        pady=4,
                        sticky='EWNS')
        # add tab content
        ttk.Label(dccsTab, text='API Url:').grid(column=0,
                                                 row=0,
                                                 sticky='EWNS')
        App.apiUrl = tkinter.StringVar()
        tkinter.Entry(dccsTab, textvariable=App.apiUrl,
                      width=10).grid(column=1, row=0, sticky='EWNS')
        ttk.Label(dccsTab, text='Credential Key:').grid(column=0,
                                                        row=1,
                                                        sticky='EWNS')
        App.credentialKey = tkinter.StringVar()
        tkinter.Entry(dccsTab, textvariable=App.credentialKey,
                      width=10).grid(column=1, row=1, sticky='EWNS')

        # create a tab
        mqttTab = ttk.Frame(tabControl, width=200, height=100)
        mqttTab.grid(column=0, row=0, padx=8, pady=4)
        tabControl.add(mqttTab, text='MQTT')
        tabControl.grid(column=0,
                        row=0,
                        rowspan=2,
                        columnspan=2,
                        padx=8,
                        pady=4)

        # add tab content
        ttk.Label(mqttTab, text='HostName:').grid(column=0,
                                                  row=0,
                                                  sticky='EWNS')
        App.hostName = tkinter.StringVar()
        App.hostName.set('127.0.0.1')
        tkinter.Entry(mqttTab, textvariable=App.hostName,
                      width=10).grid(column=1, row=0, sticky='EWNS')
        ttk.Label(mqttTab, text='Port:').grid(column=0, row=1, sticky='EWNS')
        App.port = tkinter.IntVar()
        App.port.set(1883)
        tkinter.Entry(mqttTab, textvariable=App.port,
                      width=10).grid(column=1, row=1, sticky='EWNS')
        ttk.Label(mqttTab, text='Username:'******'EWNS')
        App.userName = tkinter.StringVar()
        App.userName.set('')
        tkinter.Entry(mqttTab, textvariable=App.userName,
                      width=10).grid(column=1, row=2, sticky='EWNS')
        ttk.Label(mqttTab, text='Password:'******'EWNS')
        App.password = tkinter.StringVar()
        App.password.set('')
        tkinter.Entry(mqttTab, textvariable=App.password,
                      width=10).grid(column=1, row=3, sticky='EWNS')

        # connect status
        App.status = tkinter.StringVar()
        App.status.set('Disconnected')
        statusLabel = tkinter.Label(master,
                                    textvariable=App.status,
                                    bg='#C0C0C0')
        statusLabel.grid(column=2, row=0, columnspan=2, sticky='EWNS')

        # function
        def clickedConnect():
            try:
                if App.nodeId.get() == '':
                    messagebox.showwarning("Warging", 'nodeId is necessary')
                    return
                selectTab = tabControl.tab(tabControl.select(), 'text')
                edgeAgentOptions = EdgeAgentOptions(nodeId=App.nodeId.get())
                if selectTab == 'MQTT':
                    edgeAgentOptions.connectType = constant.ConnectType['MQTT']
                    mqttOptions = MQTTOptions(hostName=App.hostName.get(),
                                              port=App.port.get(),
                                              userName=App.userName.get(),
                                              password=App.password.get())
                    edgeAgentOptions.MQTT = mqttOptions
                elif selectTab == 'DCCS':
                    edgeAgentOptions.connectType = constant.ConnectType['DCCS']
                    dccsOptions = DCCSOptions(
                        apiUrl=App.apiUrl.get(),
                        credentialKey=App.credentialKey.get())
                    edgeAgentOptions.DCCS = dccsOptions
                if self._edgeAgent is None:
                    self._edgeAgent = EdgeAgent(edgeAgentOptions)
                    self._edgeAgent.on_connected = on_connected
                    self._edgeAgent.on_disconnected = on_disconnected
                    self._edgeAgent.on_message = on_message
                self._edgeAgent.connect()
            except ValueError as error:
                messagebox.showwarning("Warging", str(error))

        def on_connected(edgeAgent, isConnected):
            if isConnected:
                App.status.set('Connected')
                statusLabel.config(bg='#008000')

        def on_disconnected(edgeAgent, isDisconnected):
            if isDisconnected:
                App.status.set('Disconnected')
                statusLabel.config(bg='#C0C0C0')
                self._edgeAgent = None
                self.timer = None

        def on_message(edgeAgent, message):
            if message.type == constant.MessageType['ConfigAck']:
                response = 'Upload Config Result: {0}'.format(
                    str(message.message.result))
                messagebox.showwarning("Information", response)
            elif message.type == constant.MessageType['WriteValue']:
                message = message.message
                for device in message.deviceList:
                    print("deviceId: {0}".format(device.id))
                    for tag in device.tagList:
                        print("tagName: {0}, Value: {1}".format(
                            tag.name, str(tag.value)))
                        if device.id == "Device1" and tag.name == "DTag1":
                            App.dTag1Value.set(tag.value)

        def clickedDisconnected():
            if self._edgeAgent is None or not self._edgeAgent.isConnected:
                return
            self._edgeAgent.disconnect()

        def clickedSendData():
            if self._edgeAgent is None or not self._edgeAgent.isConnected:
                messagebox.showwarning("Warging", 'edge not connected')
                return
            frequency = int(App.frequency.get())
            if self.timer is None:
                self.timer = RepeatedTimer(frequency, __sendData)
                __sendData()

        def __sendData():
            data = __generateData()
            self._edgeAgent.sendData(data)

        def clickedDeviceStatus():
            if self._edgeAgent is None or not self._edgeAgent.isConnected:
                messagebox.showwarning("Warging", 'edge not connected')
                return
            status = __generateStatus()
            self._edgeAgent.sendDeviceStatus(status)

        def clickedUploadConfig():
            if self._edgeAgent is None or not self._edgeAgent.isConnected:
                messagebox.showwarning("Warging", 'edge not connected')
                return
            config = __generateConfig()
            self._edgeAgent.uploadConfig(action=constant.ActionType['Create'],
                                         edgeConfig=config)

        def clickedUpdateConfig():
            if self._edgeAgent is None or not self._edgeAgent.isConnected:
                messagebox.showwarning("Warging", 'edge not connected')
                return
            config = __generateConfig()
            self._edgeAgent.uploadConfig(action=constant.ActionType['Update'],
                                         edgeConfig=config)

        def clickedDeleteNode():
            if self._edgeAgent is None or not self._edgeAgent.isConnected:
                messagebox.showwarning("Warging", 'edge not connected')
                return
            config = __generateDelteNodeConfig()
            self._edgeAgent.uploadConfig(action=constant.ActionType['Delete'],
                                         edgeConfig=config)

        def clickedDeleteDevice():
            if self._edgeAgent is None or not self._edgeAgent.isConnected:
                messagebox.showwarning("Warging", 'edge not connected')
                return
            config = __generateDelteDeviceConfig()
            self._edgeAgent.uploadConfig(action=constant.ActionType['Delete'],
                                         edgeConfig=config)

        def clickedDeleteTag():
            if self._edgeAgent is None or not self._edgeAgent.isConnected:
                messagebox.showwarning("Warging", 'edge not connected')
                return
            config = __generateDelteTagConfig()
            self._edgeAgent.uploadConfig(action=constant.ActionType['Delete'],
                                         edgeConfig=config)

        def __generateData():
            edgeData = EdgeData()
            for i in range(1, int(App.deviceCount.get()) + 1):
                for j in range(1, int(App.analogCount.get()) + 1):
                    deviceId = 'Device' + str(i)
                    tagName = 'ATag' + str(j)
                    value = random.uniform(0, 100)
                    tag = EdgeTag(deviceId, tagName, value)
                    edgeData.tagList.append(tag)
                for j in range(1, int(App.discreteCount.get()) + 1):
                    deviceId = 'Device' + str(i)
                    tagName = 'DTag' + str(j)
                    value = random.randint(0, 99)
                    value = value % 2
                    tag = EdgeTag(deviceId, tagName, value)
                    edgeData.tagList.append(tag)
                for j in range(1, int(App.textCount.get()) + 1):
                    deviceId = 'Device' + str(i)
                    tagName = 'TTag' + str(j)
                    value = random.uniform(0, 100)
                    value = 'TEST ' + str(value)
                    tag = EdgeTag(deviceId, tagName, value)
                    edgeData.tagList.append(tag)

            edgeData.timestamp = datetime.datetime.now()
            return edgeData

        def __generateStatus():
            deviceStatus = EdgeDeviceStatus()
            for i in range(1, int(App.deviceCount.get()) + 1):
                deviceId = 'Device' + str(i)
                device = EdgeStatus(id=deviceId,
                                    status=constant.Status['Online'])
                deviceStatus.deviceList.append(device)
            return deviceStatus

        def __generateConfig():
            config = EdgeConfig()
            nodeConfig = NodeConfig(nodeType=constant.EdgeType['Gateway'])
            config.node = nodeConfig
            for i in range(1, int(App.deviceCount.get()) + 1):
                deviceConfig = DeviceConfig(id='Device' + str(i),
                                            name='Device' + str(i),
                                            description='Device' + str(i),
                                            deviceType='Smart Device',
                                            retentionPolicyName='')
                for j in range(1, int(App.analogCount.get()) + 1):
                    analog = AnalogTagConfig(name='ATag' + str(j),
                                             description='ATag ' + str(j),
                                             readOnly=False,
                                             arraySize=0,
                                             spanHigh=1000,
                                             spanLow=0,
                                             engineerUnit='',
                                             integerDisplayFormat=4,
                                             fractionDisplayFormat=2)
                    deviceConfig.analogTagList.append(analog)
                for j in range(1, int(App.discreteCount.get()) + 1):
                    discrete = DiscreteTagConfig(name='DTag' + str(j),
                                                 description='DTag ' + str(j),
                                                 readOnly=False,
                                                 arraySize=0,
                                                 state0='0',
                                                 state1='1',
                                                 state2='',
                                                 state3='',
                                                 state4='',
                                                 state5='',
                                                 state6='',
                                                 state7='')
                    deviceConfig.discreteTagList.append(discrete)
                for j in range(1, int(App.textCount.get()) + 1):
                    text = TextTagConfig(name='TTag' + str(j),
                                         description='TTag ' + str(j),
                                         readOnly=False,
                                         arraySize=0)
                    deviceConfig.textTagList.append(text)
                config.node.deviceList.append(deviceConfig)
            return config

        def __generateDelteNodeConfig():
            config = EdgeConfig()
            nodeConfig = NodeConfig()
            config.node = nodeConfig
            return config

        def __generateDelteDeviceConfig():
            config = EdgeConfig()
            nodeConfig = NodeConfig()
            config.node = nodeConfig
            for i in range(1, int(App.deviceCount.get()) + 1):
                deviceConfig = DeviceConfig(id='Device' + str(i))
                config.node.deviceList.append(deviceConfig)
            return config

        def __generateDelteTagConfig():
            config = EdgeConfig()
            nodeConfig = NodeConfig()
            config.node = nodeConfig
            for i in range(1, int(App.deviceCount.get()) + 1):
                deviceConfig = DeviceConfig(id='Device' + str(i))
                for j in range(1, int(App.analogCount.get()) + 1):
                    analog = AnalogTagConfig(name='ATag' + str(j))
                    deviceConfig.analogTagList.append(analog)
                for j in range(1, int(App.discreteCount.get()) + 1):
                    discrete = DiscreteTagConfig(name='DTag' + str(j))
                    deviceConfig.discreteTagList.append(discrete)
                for j in range(1, int(App.textCount.get()) + 1):
                    text = TextTagConfig(name='TTag' + str(j))
                    deviceConfig.textTagList.append(text)
                config.node.deviceList.append(deviceConfig)
            return config

        # input
        nodeFrame = tkinter.Frame(master)
        nodeFrame.grid(column=0, row=2, columnspan=2, sticky='W')
        ttk.Label(nodeFrame, text='NodeId:').pack(side=tkinter.TOP)
        App.nodeId = tkinter.StringVar()
        tkinter.Entry(nodeFrame, textvariable=App.nodeId,
                      width=10).pack(side=tkinter.TOP)
        wvFrame = tkinter.Frame(master)
        wvFrame.grid(column=1, row=2, columnspan=2, sticky='W')
        ttk.Label(wvFrame, text='DTag1 Value:').pack(side=tkinter.TOP)
        App.dTag1Value = tkinter.IntVar()
        App.dTag1Value.set(1)
        ttk.Label(wvFrame, textvariable=App.dTag1Value).pack(side=tkinter.TOP)
        deviceFrame = tkinter.Frame(master)
        deviceFrame.grid(column=0, row=3, columnspan=2, sticky='W')
        ttk.Label(deviceFrame, text='Device Count:').pack(side=tkinter.TOP)
        App.deviceCount = tkinter.IntVar()
        App.deviceCount.set(1)
        tkinter.Entry(deviceFrame, textvariable=App.deviceCount,
                      width=10).pack(side=tkinter.TOP)
        analogFrame = tkinter.Frame(master)
        analogFrame.grid(column=0, row=4, sticky='EWNS')
        ttk.Label(analogFrame, text='Analog Tag Count:').pack(side=tkinter.TOP)
        App.analogCount = tkinter.IntVar()
        App.analogCount.set(5)
        tkinter.Entry(analogFrame, textvariable=App.analogCount,
                      width=10).pack(side=tkinter.TOP)
        discreteFrame = tkinter.Frame(master)
        discreteFrame.grid(column=1, row=4, sticky='EWNS')
        ttk.Label(discreteFrame,
                  text='Discrete Tag Count:').pack(side=tkinter.TOP)
        App.discreteCount = tkinter.IntVar()
        App.discreteCount.set(5)
        tkinter.Entry(discreteFrame, textvariable=App.discreteCount,
                      width=10).pack(side=tkinter.TOP)
        textFrame = tkinter.Frame(master)
        textFrame.grid(column=2, row=4, sticky='EWNS')
        ttk.Label(textFrame, text='Text Tag Count:').pack(side=tkinter.TOP)
        App.textCount = tkinter.IntVar()
        App.textCount.set(5)
        tkinter.Entry(textFrame, textvariable=App.textCount,
                      width=10).pack(side=tkinter.TOP)
        fraquencyFrame = tkinter.Frame(master)
        fraquencyFrame.grid(column=3, row=4, sticky='EWNS')
        ttk.Label(fraquencyFrame,
                  text='Data Fredquency:').pack(side=tkinter.TOP)
        App.frequency = tkinter.IntVar()
        App.frequency.set(1)
        tkinter.Entry(fraquencyFrame, textvariable=App.frequency,
                      width=10).pack(side=tkinter.TOP)

        # button
        ttk.Button(master, text='Connect',
                   command=clickedConnect).grid(column=2, row=1, sticky='EWNS')
        ttk.Button(master, text='Disconnect',
                   command=clickedDisconnected).grid(column=3,
                                                     row=1,
                                                     sticky='EWNS')
        ttk.Button(master,
                   text='Update Device Status',
                   command=clickedDeviceStatus).grid(column=2,
                                                     row=2,
                                                     sticky='EWNS')
        ttk.Button(master, text='Send Data',
                   command=clickedSendData).grid(column=3,
                                                 row=2,
                                                 sticky='EWNS')
        ttk.Button(master, text='Upload Config',
                   command=clickedUploadConfig).grid(column=4,
                                                     row=0,
                                                     sticky='EWNS')
        ttk.Button(master, text='Update Config',
                   command=clickedUpdateConfig).grid(column=4,
                                                     row=1,
                                                     sticky='EWNS')
        ttk.Button(master, text='Delete All Config',
                   command=clickedDeleteNode).grid(column=4,
                                                   row=2,
                                                   sticky='EWNS')
        ttk.Button(master, text='Delete Devices',
                   command=clickedDeleteDevice).grid(column=4,
                                                     row=3,
                                                     sticky='EWNS')
        ttk.Button(master, text='Delete Tag',
                   command=clickedDeleteTag).grid(column=4,
                                                  row=4,
                                                  sticky='EWNS')
    dataRecover=True,
    # Connection type (DCCS, MQTT), default is DCCS
    connectType=constant.ConnectType['DCCS'],
    MQTT=MQTTOptions(  # If connectType is MQTT, must fill this options
        hostName="127.0.0.1",
        port=1883,
        userName="******",
        password="******",
        # MQTT protocal (TCP, Websocket), default is TCP
        protocalType=constant.Protocol['TCP']),
    DCCS=DCCSOptions(
        apiUrl="https://api-dccs-ensaas.sa.wise-paas.com/",  # DCCS API Url
        credentialKey="3fd45702956acdcaf50de85d0e5bd26x"  # Creadential key
    ))

edge_agent = EdgeAgent(options=options)


def handler_on_connected(agent, isConnected):
    # Connected: when EdgeAgent is connected to IoTHub.
    print("Connected successfully")


def handler_on_disconnected(agent, isDisconnected):
    # Disconnected: when EdgeAgent is disconnected to IoTHub.
    print("Disconnected")


def handler_on_message(agent, messageReceivedEventArgs):
    '''
    MessageReceived: when EdgeAgent receives MQTT message FROM CLOUD. The message type is as follows: