Completing ZigbeeTest with doorlock test
[iot2.git] / benchmarks / other / XbeePythonDriver / xbee_driver.py
index 84e7a0b0ac3ac63351dcda7132599be0a5be5c1c..99e93ae948319a18c75e861be05737f96033e139 100644 (file)
@@ -16,16 +16,18 @@ import threading
 # -----------------------------------------------------------------------------
 UDP_RECEIVE_PORT = 5005        # port used for incoming UDP data
 UDP_RECEIVE_BUFFER_SIZE = 4096  # max buffer size of an incoming UDP packet
-SYSTEM_MASTER_ADDRESS = ("192.168.2.108", 12345) # ip address and portof the system master node computer ip addr running java
+SYSTEM_MASTER_ADDRESS = ("192.168.2.108", 12345) # ip address and portof the system master node
 
 # time for messages to wait for a response before the system clears away that 
 # sequence identifier
 ZIGBEE_SEQUENCE_NUMBER_CLEAR_TIME_SEC = 5 
 
-ZIGBEE_SERIAL_PORT = "/dev/cu.usbserial-DN01DJIP"  # USB-Serial port of local radio
+#ZIGBEE_SERIAL_PORT = "/dev/cu.usbserial-DN01DCRH"  # USB-Serial port of local radio
+ZIGBEE_SERIAL_PORT = "/dev/ttyUSB0"
 ZIGBEE_SERIAL_BAUD = 115200                       # Baud rate for above port
 
 # address of our local zigbee radio
+#ZIGBEE_DEVICE_ADDRESS = "0013a20040d99cb4"
 ZIGBEE_DEVICE_ADDRESS = "xxxxxxxxxxxxxxxx"
 
 # -----------------------------------------------------------------------------
@@ -40,6 +42,11 @@ didGetLocalRadioLowAddress = False;
 zigbeeConnection = None
 zigbeeConnectionMutex = Lock()
 
+#singleton mabe by changwoo
+matchDescriptorReqSingleton = True
+deviceAnnouncementSingleton = True
+ManagementPermitJoiningReqSuccess = False
+
 # zigbee mapping from long to short object dict
 zigbeeLongShortAddr = dict()
 zigbeeLongShortAddrMutex = Lock()
@@ -72,14 +79,18 @@ doEndFlag = False
 sendSoceket = socket(AF_INET, SOCK_DGRAM)
 receiveSoceket = socket(AF_INET, SOCK_DGRAM)
 
-
 # zigbee address authority list
 zigbeeAddressAuthorityDict = dict()
 
+# made by changwoo
+seqNumberForNotification = dict()
+
 # -----------------------------------------------------------------------------
 # Helper Methods
 # -----------------------------------------------------------------------------
-
+def reverseShortAddress(shortAddr):
+    result = shortAddr[len(shortAddr)/2:]+shortAddr[0:len(shortAddr)/2]
+    return result
 
 def parseCommandLineArgs(argv):
     global ZIGBEE_SERIAL_PORT
@@ -358,7 +369,7 @@ def getConnectedRadioLongAddress():
         zigbeeConnection.send('at', command="SL")
         
         # sleep for a bit to give the radio time to respond before we check again
-        time.sleep(0.5)
+        time.sleep(2)
 
 def addressUpdateWorkerMethod():
     ''' Method to keep refreshing the short addresses of the known zigbee devices'''
@@ -397,6 +408,7 @@ def addressUpdateWorkerMethod():
 
             # create and send binding command
             zigbeeConnectionMutex.acquire()
+           
             zigbeeConnection.send('tx_explicit',
                                 frame_id='\x01',
                                 dest_addr_long=hexStringToZigbeeHexString(ad),
@@ -409,7 +421,7 @@ def addressUpdateWorkerMethod():
                                 )
             zigbeeConnectionMutex.release()
 
-        time.sleep(1)
+        time.sleep(8)
 
 
 # -------------
@@ -540,13 +552,8 @@ def processUdpSendAddressMessage(parsedData, addr):
     global zigbeeUnregisteredAddressesMutex
     global sendSoceket
 
-    if(zigbeeAddressAuthorityDict.has_key(addr)):
-        l = zigbeeAddressAuthorityDict[addr]
-        if(parsedData['device_address_long'] not in l):
-            return
-    else:
-        return
-
+    print "process send address"
+    
 
     # construct success message
     message = "type: send_address_response\n"
@@ -555,7 +562,8 @@ def processUdpSendAddressMessage(parsedData, addr):
 
     # tell client that we got their request
     sendSoceket.sendto(message,addr)
-
+    print "responding", message
+    
     # construct 
     zigbeeLongShortAddrMutex.acquire()
     doesHaveKey = zigbeeLongShortAddr.has_key(parsedData['device_address_long'])
@@ -570,6 +578,355 @@ def processUdpSendAddressMessage(parsedData, addr):
     zigbeeUnregisteredAddresses.append(parsedData['device_address_long'])
     zigbeeUnregisteredAddressesMutex.release()
 
+#made by changwoo
+def processUdpEnrollmentResponse(parsedData, addr):
+
+    global zigbeeLongShortAddr
+    global zigbeeLongShortAddrMutex
+    global zigeeBindRequestMutex
+    global zigeeBindRequest
+    global zigbeeConnectionMutex
+    global zigbeeConnection
+    shortAddr = None
+
+    # get the short address for this device long address if possible
+    zigbeeLongShortAddrMutex.acquire()
+    if(zigbeeLongShortAddr.has_key(parsedData['device_address_long'])):
+        shortAddr = zigbeeLongShortAddr[parsedData['device_address_long']]
+    zigbeeLongShortAddrMutex.release()
+
+
+    # if there is a short address than we can send the message
+    # if there is not one then we cannot since we need both the short and
+    # the long address
+    if(shortAddr != None):
+
+        # get a request number
+        seqNumber = createSequenceNumberForClient(addr, parsedData['packet_id'])
+        
+        # send back failure
+        if(seqNumber == -1):
+
+            # send an error message, could not get a sequence number to use at this time
+            sendUdpSuccessFail(addr, 'zcl_enrollment_response', parsedData['packet_id'], False, 'out_of_space')
+            return
+
+        # get the info for sending
+        destLongAddr = hexStringToZigbeeHexString(parsedData['device_address_long'])
+        destShortAddr = hexStringToZigbeeHexString(shortAddr)
+        clusterId = hexStringToZigbeeHexString(parsedData['cluster_id'])
+        dstEndpoint = hexStringToZigbeeHexString(parsedData['device_endpoint'])
+       profileId = hexStringToZigbeeHexString(parsedData['profile_id'])
+
+        # create the payload data
+        payloadData = ""
+        payloadData += '\x01'
+        payloadData += chr(seqNumber)
+        payloadData += '\x00'
+        payloadData += '\x00\x00'
+
+        # create and send binding command
+        zigbeeConnectionMutex.acquire()
+        zigbeeConnection.send('tx_explicit',
+                            frame_id='\x40',
+                            # frame_id=chr(seqNumber),
+                            dest_addr_long=destLongAddr,
+                            dest_addr=destShortAddr,
+                            src_endpoint='\x01',
+                            dest_endpoint=dstEndpoint,
+                            cluster=clusterId,  
+                            profile=profileId,
+                            data=payloadData
+                            )
+       print '> EnrollmentResponse is sent'
+        zigbeeConnectionMutex.release()
+
+
+    else:
+        # send a fail response
+        sendUdpSuccessFail(addr, 'zcl_enrollment_response', parsedData['packet_id'], False, 'short_address_unknown')
+        pass
+
+
+
+
+#made by changwoo
+def processUdpZclWriteAttributesMessage(parsedData, addr):
+
+    global zigbeeLongShortAddr
+    global zigbeeLongShortAddrMutex
+    global zigeeBindRequestMutex
+    global zigeeBindRequest
+    global zigbeeConnectionMutex
+    global zigbeeConnection
+    shortAddr = None
+
+    # get the short address for this device long address if possible
+    zigbeeLongShortAddrMutex.acquire()
+    if(zigbeeLongShortAddr.has_key(parsedData['device_address_long'])):
+        shortAddr = zigbeeLongShortAddr[parsedData['device_address_long']]
+    zigbeeLongShortAddrMutex.release()
+
+    # if there is a short address than we can send the message
+    # if there is not one then we cannot since we need both the short and
+    # the long address
+    if(shortAddr != None):
+        # get a request number
+        seqNumber = createSequenceNumberForClient(addr, parsedData['packet_id'])
+        
+        # send back failure
+        if(seqNumber == -1):
+
+            # send an error message, could not get a sequence number to use at this time
+            sendUdpSuccessFail(addr, 'zcl_write_attributes', parsedData['packet_id'], False, 'out_of_space')
+            return
+
+        # get the info for sending
+        destLongAddr = hexStringToZigbeeHexString(parsedData['device_address_long'])
+        destShortAddr = hexStringToZigbeeHexString(shortAddr)
+        clusterId = hexStringToZigbeeHexString(parsedData['cluster_id'])
+       profileId = hexStringToZigbeeHexString(parsedData['profile_id'])
+        dstEndpoint = hexStringToZigbeeHexString(parsedData['device_endpoint'])
+
+        # create the payload data
+        payloadData = ""
+        payloadData += '\x00'
+        payloadData += chr(seqNumber)
+        payloadData += '\x02'
+        payloadData += '\x10\x00'
+        payloadData += '\xF0'
+#        payloadData += '\xDA\x9A\xD9\x40\x00\xA2\x13\x00'
+        payloadData += hexStringToZigbeeHexString(changeEndian(ZIGBEE_DEVICE_ADDRESS))
+
+        zigbeeConnectionMutex.acquire()
+        zigbeeConnection.send('tx_explicit',
+                            frame_id='\x08',
+                            # frame_id=chr(seqNumber),
+                            dest_addr_long=destLongAddr,
+                            dest_addr=destShortAddr,
+                            src_endpoint='\x01',
+                            dest_endpoint=dstEndpoint,
+                            cluster=clusterId,
+                            profile=profileId,
+                            data=payloadData
+                            )
+
+       print ''
+       print '> WriteAttributesReq is sent : '+str(shortAddr)
+        zigbeeConnectionMutex.release()
+
+
+    else:
+        # send a fail response
+        sendUdpSuccessFail(addr, 'zcl_write_attributes', parsedData['packet_id'], False, 'short_address_unknown')
+        pass
+
+#made by changwoo
+def processUdpZclChangeSwitchReqMessage(parsedData, addr):
+
+    global zigbeeLongShortAddr
+    global zigbeeLongShortAddrMutex
+    global zigeeBindRequestMutex
+    global zigeeBindRequest
+    global zigbeeConnectionMutex
+    global zigbeeConnection
+    shortAddr = None
+
+    # get the short address for this device long address if possible
+    zigbeeLongShortAddrMutex.acquire()
+    if(zigbeeLongShortAddr.has_key(parsedData['device_address_long'])):
+        shortAddr = zigbeeLongShortAddr[parsedData['device_address_long']]
+    zigbeeLongShortAddrMutex.release()
+
+
+    # if there is a short address than we can send the message
+    # if there is not one then we cannot since we need both the short and
+    # the long address
+    if(shortAddr != None):
+
+        # get a request number
+        seqNumber = createSequenceNumberForClient(addr, parsedData['packet_id'])
+
+        # send back failure
+        if(seqNumber == -1):
+
+            # send an error message, could not get a sequence number to use at this time
+            sendUdpSuccessFail(addr, 'change_switch_request', parsedData['packet_id'], False, 'out_of_space')
+            return
+
+        # get the info for sending
+        destLongAddr = hexStringToZigbeeHexString(parsedData['device_address_long'])
+        destShortAddr = hexStringToZigbeeHexString(shortAddr)
+        dstEndpoint = hexStringToZigbeeHexString(parsedData['device_endpoint'])
+       clusterId = hexStringToZigbeeHexString(parsedData['cluster_id'])
+       profileId = hexStringToZigbeeHexString(parsedData['profile_id'])
+       value = hexStringToZigbeeHexString(parsedData['value'])
+
+        # create and send binding command
+        zigbeeConnectionMutex.acquire()
+
+        zigbeeConnection.send('tx_explicit',
+                            frame_id='\x40',
+                            # frame_id=chr(seqNumber),
+                            dest_addr_long=destLongAddr,
+                            dest_addr=destShortAddr,
+                            src_endpoint='\x01',
+                            dest_endpoint=dstEndpoint,
+                            cluster=clusterId,  
+                            profile=profileId,
+                            data='\x01'+chr(seqNumber)+value
+                            )
+        time.sleep(1)
+       if parsedData['value']==1:
+               print '> The outlet sensor turned on'
+       else :
+               print '> The outlet sensor turned off'
+
+        zigbeeConnectionMutex.release()
+
+
+    else:
+        # send a fail response
+        sendUdpSuccessFail(addr, 'zcl_read_attributes', parsedData['packet_id'], False, 'short_address_unknown')
+        pass
+
+
+
+# made by changwoo
+def processUdpBroadcastingRouteRecordReqMessage(parsedData, addr):
+
+    global zigbeeLongShortAddr
+    global zigbeeLongShortAddrMutex
+    global zigeeBindRequestMutex
+    global zigeeBindRequest
+    global zigbeeConnectionMutex
+    global zigbeeConnection
+    shortAddr = None
+
+    # get the short address for this device long address if possible
+    zigbeeLongShortAddrMutex.acquire()
+    if(zigbeeLongShortAddr.has_key(parsedData['device_address_long'])):
+        shortAddr = zigbeeLongShortAddr[parsedData['device_address_long']]
+    zigbeeLongShortAddrMutex.release()
+
+
+    # if there is a short address than we can send the message
+    # if there is not one then we cannot since we need both the short and
+    # the long address
+    if(shortAddr != None):
+
+        # get a request number
+        seqNumber = createSequenceNumberForClient(addr, parsedData['packet_id'])
+
+        # send back failure
+        if(seqNumber == -1):
+
+            # send an error message, could not get a sequence number to use at this time
+            sendUdpSuccessFail(addr, 'broadcast_route_record_request', parsedData['packet_id'], False, 'out_of_space')
+            return
+
+        # get the info for sending
+        destLongAddr = hexStringToZigbeeHexString(parsedData['device_address_long'])
+        destShortAddr = hexStringToZigbeeHexString(shortAddr)
+        dstEndpoint = hexStringToZigbeeHexString(parsedData['device_endpoint'])
+
+        # create and send binding command
+        zigbeeConnectionMutex.acquire()
+
+        zigbeeConnection.send('tx_explicit',
+                            frame_id='\x01',
+                            # frame_id=chr(seqNumber),
+                            dest_addr_long='\x00\x00\x00\x00\x00\x00\xff\xff',
+                            dest_addr='\xff\xfe',
+                            src_endpoint='\x00',
+                            dest_endpoint=dstEndpoint,
+                            cluster='\x00\x32',  
+                            profile='\x00\x00',
+                            data='\x12'+'\x01'
+                            )
+        time.sleep(1)
+       print '> BroadcastingRouteRecordReq is sent'
+
+        zigbeeConnectionMutex.release()
+
+
+    else:
+        # send a fail response
+        sendUdpSuccessFail(addr, 'zcl_read_attributes', parsedData['packet_id'], False, 'short_address_unknown')
+        pass
+
+
+#made by changwoo
+def processUdpManagementPermitJoiningReqMessage(parsedData, addr):
+
+    global zigbeeLongShortAddr
+    global zigbeeLongShortAddrMutex
+    global zigeeBindRequestMutex
+    global zigeeBindRequest
+    global zigbeeConnectionMutex
+    global zigbeeConnection
+    global matchDescriptorReqSingleton
+    shortAddr = None
+
+    # get the short address for this device long address if possible
+    zigbeeLongShortAddrMutex.acquire()
+    if(zigbeeLongShortAddr.has_key(parsedData['device_address_long'])):
+        shortAddr = zigbeeLongShortAddr[parsedData['device_address_long']]
+    zigbeeLongShortAddrMutex.release()
+
+
+    # if there is a short address than we can send the message
+    # if there is not one then we cannot since we need both the short and
+    # the long address
+    if(shortAddr != None):
+
+        # get a request number
+        seqNumber = createSequenceNumberForClient(addr, parsedData['packet_id'])
+        
+        # send back failure
+        if(seqNumber == -1):
+
+            # send an error message, could not get a sequence number to use at this time
+            sendUdpSuccessFail(addr, 'management_permit_joining_request', parsedData['packet_id'], False, 'out_of_space')
+            return
+
+        # get the info for sending
+        destLongAddr = hexStringToZigbeeHexString(parsedData['device_address_long'])
+        destShortAddr = hexStringToZigbeeHexString(shortAddr)
+        clusterId = hexStringToZigbeeHexString(parsedData['cluster_id'])
+
+        # create the payload data
+        payloadData = ""
+        payloadData += chr(seqNumber)
+        payloadData += '\x5a'
+        payloadData += '\x00'
+
+        # create and send binding command
+        zigbeeConnectionMutex.acquire()
+        zigbeeConnection.send('tx_explicit',
+                            frame_id='\x01',
+                            # frame_id=chr(seqNumber),
+                            dest_addr_long=destLongAddr,
+                            dest_addr=destShortAddr,
+                            src_endpoint='\x00',
+                            dest_endpoint='\x00',
+                            cluster=clusterId,  
+                            profile='\x00\x00',
+                            data=payloadData
+                            )
+       print '> ManagementPermitJoiningReq is sent'
+
+       #stop answering 0x6
+       matchDescriptorReqSingleton= False
+        zigbeeConnectionMutex.release()
+
+
+    else:
+        # send a fail response
+        sendUdpSuccessFail(addr, 'management_permit_joining_request', parsedData['packet_id'], False, 'short_address_unknown')
+        pass
+
+
 def processUdpZclReadAttributesMessage(parsedData, addr):
     ''' Method handle a ZCL read attribute command
 
@@ -585,6 +942,7 @@ def processUdpZclReadAttributesMessage(parsedData, addr):
     global zigbeeConnection
 
 
+
     if(zigbeeAddressAuthorityDict.has_key(addr)):
         l = zigbeeAddressAuthorityDict[addr]
         if(parsedData['device_address_long'] not in l):
@@ -674,7 +1032,6 @@ def processUdpZclConfigureReportingMessage(parsedData, addr):
     global zigbeeConnectionMutex
     global zigbeeConnection
 
-
     if(zigbeeAddressAuthorityDict.has_key(addr)):
         l = zigbeeAddressAuthorityDict[addr]
         if(parsedData['device_address_long'] not in l):
@@ -682,6 +1039,7 @@ def processUdpZclConfigureReportingMessage(parsedData, addr):
     else:
         return
 
+
     shortAddr = None
 
     # get the short address for this device long address if possible
@@ -744,6 +1102,7 @@ def processUdpZclConfigureReportingMessage(parsedData, addr):
         sendUdpSuccessFail(addr, 'zcl_configure_reporting', parsedData['packet_id'], False, 'short_address_unknown')
         pass
 
+
 def processUdpPolicySet(parsedData, addr):
     ''' Method handle a policy set message
 
@@ -752,15 +1111,20 @@ def processUdpPolicySet(parsedData, addr):
     '''
     print "=================================================================="
     print "Policy set: ", parsedData
-    
+    print 'addr : ', addr
+
+
     # do nothing if wrong source
-    if addr == SYSTEM_MASTER_ADDRESS:
+    #if addr == SYSTEM_MASTER_ADDRESS or addr == SYSTEM_MASTER_ADDRESS2 or addr == SYSTEM_MASTER_ADDRESS3 :
+    #if addr == SYSTEM_MASTER_ADDRESS :
+    if addr[0] == SYSTEM_MASTER_ADDRESS[0]:
         key = (parsedData['ip_address'], int(parsedData['port']))
         if (zigbeeAddressAuthorityDict.has_key(key)):
             zigbeeAddressAuthorityDict[key].append(parsedData['device_address_long'])
         else:
             zigbeeAddressAuthorityDict[key] = [parsedData['device_address_long']]
 
+
 def processUdpPolicyClear(parsedData, addr):
     ''' Method handle a policy set message
 
@@ -771,9 +1135,11 @@ def processUdpPolicyClear(parsedData, addr):
     print "Clear policy: ", parsedData
     
     # do nothing if wrong source
-    if addr == SYSTEM_MASTER_ADDRESS:
+    #if addr == SYSTEM_MASTER_ADDRESS or addr == SYSTEM_MASTER_ADDRESS2 or addr == SYSTEM_MASTER_ADDRESS3:
+    if addr == SYSTEM_MASTER_ADDRESS :
         zigbeeAddressAuthorityDict.clear()
 
+
 # -------------
 # Zigbee 
 # -------------
@@ -820,11 +1186,14 @@ def processZigbeeRxExplicitCommandMessage(parsedData):
     '''
     global zigeeBindRequestMutex
     global zigeeBindRequest
+    global zigbeeConnectionMutex
+    global zigbeeConnection
+    global ManagementPermitJoiningReqSuccess
 
     # get the long and short addresses from the message payload since we can 
     # use these to update the short addresses since this short address is fresh
     longAddr = zigbeeHexStringToHexString(parsedData['source_addr_long'])
-    shortAddr = zigbeeHexStringToHexString( parsedData['source_addr'])
+    shortAddr = zigbeeHexStringToHexString(parsedData['source_addr'])
 
     # check if this short address is for a device that has yet to be 
     # registered
@@ -838,13 +1207,53 @@ def processZigbeeRxExplicitCommandMessage(parsedData):
     zigbeeLongShortAddr[longAddr] = shortAddr
     zigbeeLongShortAddrMutex.release()
 
+    global matchDescriptorReqSingleton
+    global deviceAnnouncementSingleton
+    global seqNumberForNotification
 
     # if this is a ZDO message/response
+    #print "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
+    #print parsedData
+    #print "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
     if(parsedData['profile'] == '\x00\x00'):
 
+       # made by changwoo
+        # if this is a Match Descriptor Request so we need to answer.
+        if(parsedData['cluster'] == '\x00\x06' and matchDescriptorReqSingleton):
+            zigbeeConnectionMutex.acquire()
+            zigbeeConnection.send('tx_explicit',
+                            frame_id='\x08',
+                            # frame_id=chr(seqNumber),
+                            dest_addr_long=parsedData['source_addr_long'],
+                            dest_addr=parsedData['source_addr'],
+                            src_endpoint='\x00',
+                            dest_endpoint='\x00',
+                            cluster='\x00\x06',
+                            profile='\x00\x00',
+                            data=parsedData['rf_data']
+                            )
+            time.sleep(1)
+            zigbeeConnection.send('tx_explicit',
+                            frame_id='\x40',
+                            # frame_id=chr(seqNumber),
+                            dest_addr_long=parsedData['source_addr_long'],
+                            dest_addr=parsedData['source_addr'],
+                            src_endpoint='\x00',
+                            dest_endpoint='\x00',
+                            cluster='\x80\x06',
+                            profile='\x00\x00',
+                            data=parsedData['rf_data'][0]+ '\x00\x00\x00' + '\x01\x01'
+                            )
+            time.sleep(1)
+            print ''
+            print '[ 0x0006 ] Match Descriptor Request - answered'
+            print '> rfdata : '+zigbeeHexStringToHexString(parsedData['rf_data'])
+            zigbeeConnectionMutex.release()
+
+
         # if this is a device announcement so we can get some useful data from it
-        if(parsedData['cluster'] == '\x00\x13'):
-            
+        elif(parsedData['cluster'] == '\x00\x13' and deviceAnnouncementSingleton):
+            #print parsedData
             # pick out the correct parts of the payload
             longAddr = zigbeeHexStringToHexString(parsedData['rf_data'][3:11])
             shortAddr = zigbeeHexStringToHexString(parsedData['rf_data'][1:3])
@@ -865,12 +1274,34 @@ def processZigbeeRxExplicitCommandMessage(parsedData):
                 zigbeeUnregisteredAddresses.remove(longAddr)
             zigbeeUnregisteredAddressesMutex.release()
 
+
+           # made by changwoo
+            zigbeeConnectionMutex.acquire()
+            zigbeeConnection.send('tx_explicit',
+                            frame_id='\x08',
+                            # frame_id=chr(seqNumber),
+                            dest_addr_long=parsedData['source_addr_long'],
+                            dest_addr=parsedData['source_addr'],
+                            src_endpoint='\x00',
+                            dest_endpoint='\x00',
+                            cluster='\x00\x13',
+                            profile='\x00\x00',
+                            data=parsedData['rf_data']
+                            )
+           print ''
+           print '[ 0x0013 ] device announcement - answered'
+           print '> rfdata : '+zigbeeHexStringToHexString(parsedData['rf_data'])
+           deviceAnnouncementSingleton = False
+            zigbeeConnectionMutex.release()
+
+
         # if this is a response to a zdo bind_req message
         elif(parsedData['cluster'] == '\x80\x21'):
 
             # get the status and sequence number from the message
             seqNumber = parsedData['rf_data'][0]
             statusCode = parsedData['rf_data'][1]
+            print ">response to a zdo bind_req message parsedData>"
 
             # get the bind tuple information
             # for this specific bind request
@@ -915,6 +1346,7 @@ def processZigbeeRxExplicitCommandMessage(parsedData):
 
         # if this is a response to a short address query
         elif(parsedData['cluster'] == '\x80\x00'):
+            print ">response to a short address query 0x8000"
             
             # get a status code
             statusCode = parsedData['rf_data'][0]
@@ -939,6 +1371,27 @@ def processZigbeeRxExplicitCommandMessage(parsedData):
             zigbeeLongShortAddr[longAddr] = shortAddr
             zigbeeLongShortAddrMutex.release()
 
+       #made by changwoo
+        elif(parsedData['cluster'] == '\x80\x06'):
+           print ''
+           print '[ 0x8006 ] get Match Descriptor Response'
+           print '> rfdata : '+zigbeeHexStringToHexString(parsedData['rf_data'])
+
+       #made by changwoo
+        elif(parsedData['cluster'] == '\x80\x36'):
+           print ''
+           print '[ 0x8036 ] get Management Permit Joining Response'
+           print '> rfdata : '+zigbeeHexStringToHexString(parsedData['rf_data'])
+
+           ManagementPermitJoiningReqSuccess = True
+
+       #made by changwoo
+        else :
+           print ''
+           print '[ '+zigbeeHexStringToHexString(parsedData['cluster'])+' ] ...'
+           print '> rfdata : '+zigbeeHexStringToHexString(parsedData['rf_data'])
+
+
     # if this is a home automation zcl message/response
     elif (parsedData['profile'] == '\x01\x04'):
 
@@ -946,9 +1399,45 @@ def processZigbeeRxExplicitCommandMessage(parsedData):
         zclFrameControl = parsedData['rf_data'][0]
         zclSeqNumber = parsedData['rf_data'][1]
         zclCommand = parsedData['rf_data'][2]
+       zclStatus = parsedData['rf_data'][3]
+
+       #made by changwoo
+        if(zclCommand == '\x00'):
+           print ''
+           print '> ('+zigbeeHexStringToHexString(zclStatus)+') notification! : '+ zigbeeHexStringToHexString( parsedData['rf_data'] )
+           
+           # find who to send response 
+           tup = None
+            zigbeeSeqNumberToClientMutex.acquire()
+
+           if(longAddr in seqNumberForNotification):
+               key = longAddr
+                if(zigbeeSeqNumberToClient.has_key(seqNumberForNotification[key])):
+                    tup = zigbeeSeqNumberToClient[seqNumberForNotification[key]]
+                    #del zigbeeSeqNumberToClient[seqNumberForNotification] # don't delete.
+            zigbeeSeqNumberToClientMutex.release()
+
+            # no one to send the response to so just move on
+            if(tup == None):
+                # cant really do anything here
+                return
+            # create the response message
+            packetId = tup[2]
+            message = "type : zcl_zone_status_change_notification\n"
+            message += "packet_id: " + packetId + "\n"
+            message += "cluster_id: " + zigbeeHexStringToHexString(parsedData['cluster']) + "\n"
+            message += "profile_id: " + zigbeeHexStringToHexString(parsedData['profile']) + "\n"
+            message += "status: " + zigbeeHexStringToHexString(zclStatus) + "\n"
+            message += "attributes: success"
+            message += "\n"
+            # send the socket
+            sendSoceket.sendto(message,tup[0])
+           print(">port : ", tup[0][1])
+
+
 
         # this is a zcl read attribute response
-        if(zclCommand == '\x01'):
+        elif(zclCommand == '\x01'):
 
             # get the zcl payload
             zclPayload = parsedData['rf_data'][3:]
@@ -1037,10 +1526,55 @@ def processZigbeeRxExplicitCommandMessage(parsedData):
 
             message = message[0:len(message) - 1]
             message += "\n"
-
             # send the socket
             sendSoceket.sendto(message,tup[0])
 
+
+
+
+       # made by changwoo
+        # this is a zcl write attribute response
+       elif(zclCommand == '\x04'):
+
+            # get the zcl payload
+            zclPayload = parsedData['rf_data'][3]
+           # the response is '70' which means already resister the mac address or 'success', then let JAVA knows it
+           if(zclStatus == '\x70' or zclPayload == '\x00'):
+
+                # find who to send response to 
+                tup = None
+                zigbeeSeqNumberToClientMutex.acquire()
+                if(zigbeeSeqNumberToClient.has_key(ord(zclSeqNumber))):
+                    tup = zigbeeSeqNumberToClient[ord(zclSeqNumber)]
+                   seqNumberForNotification[longAddr] = ord(zclSeqNumber)
+                    #del zigbeeSeqNumberToClient[ord(zclSeqNumber)]
+                zigbeeSeqNumberToClientMutex.release()
+                # no one to send the response to so just move on
+                if(tup == None):
+                    # cant really do anything here
+                    return
+            
+                # create the response message
+                packetId = tup[2]
+                message = "type : zcl_write_attributes_response\n"
+                message += "packet_id: " + packetId + "\n"
+                message += "cluster_id: " + zigbeeHexStringToHexString(parsedData['cluster']) + "\n"
+                message += "profile_id: " + zigbeeHexStringToHexString(parsedData['profile']) + "\n"
+                message += "attributes: success"
+                message += "\n"
+                # send the socket
+                sendSoceket.sendto(message,tup[0])
+               print ''
+               print '[ 0x0500 ] get Write Attribute Response success'
+               print '> rfdata : '+zigbeeHexStringToHexString(parsedData['rf_data'])
+
+           else:
+               print ''
+               print '[ 0x0500 ] get Write Attribute Response'
+               print '> rfdata : '+zigbeeHexStringToHexString(parsedData['rf_data'])
+
+
+
         # this is a zcl configure attribute response
         elif(zclCommand == '\x07'):
 
@@ -1114,7 +1648,7 @@ def processZigbeeRxExplicitCommandMessage(parsedData):
 
         # this is a zcl report attribute message
         elif(zclCommand == '\x0a'):
-
+           print "get Report attribute "
             # get teh zcl payload
             zclPayload = parsedData['rf_data'][3:]
             attibuteResponseList = []
@@ -1177,7 +1711,8 @@ def processZigbeeRxExplicitCommandMessage(parsedData):
 
             message = message[0:len(message) - 1]
             message += "\n"
-
+           print "Sending", message
+           
             # send to all client that want this callback
             for ra in retAddr:
                 sendSoceket.sendto(message,ra)
@@ -1190,22 +1725,24 @@ def handleNewZigbeeMessage(parsedData):
 
         parsedData -- Pre-parsed (into a dict) data from message.
     '''
-    print "=================================================================="
+    #print "=================================================================="
+    #print ''
     print "New Zigbee Message"
-    # printMessageData(parsedData)
+    #printMessageData(parsedData)
 
     # dispatch to the correct zigbee handler
     if (parsedData['id'] == 'at_response'):
+        print "parsedDataID : at_response"
         processZigbeeATCommandMessage(parsedData)
 
     elif (parsedData['id'] == 'rx_explicit'):
-        #printMessageData(parsedData)
+        print "parsedDataID : rx_explicit"
         processZigbeeRxExplicitCommandMessage(parsedData)
 
     else:
         print "Unknown API format"
 
-    print "=================================================================="
+    #print "=================================================================="
 
 def handleNewUdpPacket(data, addr):
     ''' Method to parse and handle an incoming UDP packet.
@@ -1213,10 +1750,12 @@ def handleNewUdpPacket(data, addr):
         data -- Data that was in the UDP packet.
         addr -- Address (IP and Port) of the UDP packet origin.
     '''
+    global ManagementPermitJoiningReqSuccess
 
-    print "=================================================================="
-    print "Got New UDP packet..."
-    # print data
+    #print "=================================================================="
+    #print ''
+    #print "Got New UDP packet..."
+    #print data
 
 
     # data comes in as 'key: value\n key: value...' string and so needs to be
@@ -1236,26 +1775,40 @@ def handleNewUdpPacket(data, addr):
             # from improper packing on the sender side
             parsedData[fields[0].strip()] = fields[1].strip()
 
+
     # wrap in try statement just in case there is an improperly formated packet we
     # can deal with it
     try:
         # dispatch to the correct process method
         if(parsedData["type"] == "zdo_bind_request"):
+            print "> processUdpZdoBindReqMessage call"
             processUdpZdoBindReqMessage(parsedData, addr)
         elif(parsedData["type"] == "zdo_unbind_request"):
             processUdpZdoUnBindReqMessage(parsedData, addr)
         elif(parsedData["type"] == "send_address"):
+            print "> processUdpSendAddressMessage call"
             processUdpSendAddressMessage(parsedData, addr)
         elif(parsedData["type"] == "zcl_read_attributes"):
             processUdpZclReadAttributesMessage(parsedData, addr)
         elif(parsedData["type"] == "zcl_configure_reporting"):
+            print "> zcl_configure_reporting call"
             processUdpZclConfigureReportingMessage(parsedData, addr)
         elif(parsedData["type"] == "policy_set"):
             processUdpPolicySet(parsedData, addr)
         elif(parsedData["type"] == "policy_clear"):
             processUdpPolicyClear(parsedData, addr)
+       elif(parsedData["type"] == "management_permit_joining_request"): #made by changwoo
+           processUdpManagementPermitJoiningReqMessage(parsedData, addr)
+       elif(parsedData["type"] == "zcl_write_attributes" and ManagementPermitJoiningReqSuccess): #made by changwoo
+            processUdpZclWriteAttributesMessage(parsedData, addr)
+       elif(parsedData["type"] == "zcl_enrollment_response"): #made by changwoo
+           processUdpEnrollmentResponse(parsedData, addr)
+       elif(parsedData["type"] == "zdo_broadcast_route_record_request"): #made by changwoo
+           processUdpBroadcastingRouteRecordReqMessage(parsedData, addr)
+       elif(parsedData["type"] == "zcl_change_switch_request"): #made by changwoo
+           processUdpZclChangeSwitchReqMessage(parsedData, addr)
         else:
-            #print "unknown Packet: " + parsedData["type"]
+            print "unknown Packet: " + parsedData["type"]
             pass
     except:
         # if we ever get here then something went wrong and so just ignore this
@@ -1263,7 +1816,7 @@ def handleNewUdpPacket(data, addr):
         print "I didn't expect this error:", sys.exc_info()[0]
         traceback.print_exc()
 
-    print "=================================================================="
+    #print "=================================================================="
 
 
 # -----------------------------------------------------------------------------
@@ -1297,7 +1850,8 @@ def main():
 
     # setup incoming UDP socket and bind it to self and specified UDP port
     # sending socket does not need to be bound to anything
-    receiveSoceket.bind(('127.0.0.1', UDP_RECEIVE_PORT))
+    #receiveSoceket.bind(('192.168.2.227', UDP_RECEIVE_PORT))
+    receiveSoceket.bind(('192.168.2.192', UDP_RECEIVE_PORT))
 
     # create the thread that does short address lookups
     addressUpdateWorkerThread = threading.Thread(target=addressUpdateWorkerMethod)
@@ -1307,7 +1861,8 @@ def main():
         # Main running loop
         while(True):
             print "=================================================================="
-            print "Waiting..."
+            print ''
+           print "Waiting..."
             print "=================================================================="
 
             # wait for an incoming UDP packet