Adjusting and cleaning up ZigbeeTest to install Vigilia ZigBee gateway and devices.
[iot2.git] / benchmarks / other / XbeePythonDriver / xbee_driver.py
index 99e93ae948319a18c75e861be05737f96033e139..488effe3ee358d411d00135a33f1bbc06a402c58 100644 (file)
@@ -1,3 +1,10 @@
+# -----------------------------------------------------------------------------
+# ZigBee Gateway Driver for Vigilia v.1.0
+# Created by Ali Younis
+# Modified by Rahmadi Trimananda, Lee Changwoo, Jiawei
+# (c) 2016-2018 University of California, Irvine
+# -----------------------------------------------------------------------------
+
 from xbee import ZigBee
 import serial
 import time
@@ -16,7 +23,8 @@ 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
+SYSTEM_MASTER_ADDRESS = ("192.168.1.198", 12345) # ip address and portof the system master node
+LOCAL_ADDRESS = "192.168.1.192" # local IP address
 
 # time for messages to wait for a response before the system clears away that 
 # sequence identifier
@@ -27,7 +35,6 @@ 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"
 
 # -----------------------------------------------------------------------------
@@ -42,7 +49,7 @@ didGetLocalRadioLowAddress = False;
 zigbeeConnection = None
 zigbeeConnectionMutex = Lock()
 
-#singleton mabe by changwoo
+#singleton mabe by Changwoo
 matchDescriptorReqSingleton = True
 deviceAnnouncementSingleton = True
 ManagementPermitJoiningReqSuccess = False
@@ -56,12 +63,12 @@ zigbeeLongShortAddrMutex = Lock()
 zigbeeSeqNumberToClient = dict()
 zigbeeSeqNumberToClientMutex = Lock()
 
-zigeeBindRequest = dict()
-zigeeBindRequestMutex = Lock()
+zigbeeBindRequest = dict()
+zigbeeBindRequestMutex = Lock()
 
 # Keeps record of where to send callbacks to when an HA message is received
 zibeeHACallback = dict()
-zibeeHACallbackMutex = Lock()
+zigbeeHACallbackMutex = Lock()
 
 
 # Keeps a record of device addresses whose short addresses have not been 
@@ -76,13 +83,14 @@ doEndFlag = False
 # 2 sockets, one for sending (not bound to a port manually)
 # and one for receiving, known port binding by application
 # both UDP sockets
-sendSoceket = socket(AF_INET, SOCK_DGRAM)
-receiveSoceket = socket(AF_INET, SOCK_DGRAM)
+sendSocket = socket(AF_INET, SOCK_DGRAM)
+receiveSocket = socket(AF_INET, SOCK_DGRAM)
+
 
 # zigbee address authority list
 zigbeeAddressAuthorityDict = dict()
 
-# made by changwoo
+# Added by Changwoo
 seqNumberForNotification = dict()
 
 # -----------------------------------------------------------------------------
@@ -369,7 +377,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(2)
+        time.sleep(0.5)
 
 def addressUpdateWorkerMethod():
     ''' Method to keep refreshing the short addresses of the known zigbee devices'''
@@ -421,7 +429,7 @@ def addressUpdateWorkerMethod():
                                 )
             zigbeeConnectionMutex.release()
 
-        time.sleep(8)
+        time.sleep(1)
 
 
 # -------------
@@ -439,7 +447,7 @@ def sendUdpSuccessFail(addr, packetTypeStr, packetIdStr, sucOrFail, reason=None)
 
     '''
 
-    global sendSoceket
+    global sendSocket
 
     # construct the message
     message = "type: " + packetTypeStr.strip() + "\n"
@@ -452,7 +460,7 @@ def sendUdpSuccessFail(addr, packetTypeStr, packetIdStr, sucOrFail, reason=None)
         message += "reason: " + reason + "\n"
 
     # send message in a UDP packet
-    sendSoceket.sendto(message,addr)
+    sendSocket.sendto(message,addr)
 
 def processUdpZdoBindReqMessage(parsedData, addr):
 
@@ -464,7 +472,7 @@ def processUdpZdoBindReqMessage(parsedData, addr):
             return
     else:
         return
-
+        
     # get the short address for this device long address if possible
     zigbeeLongShortAddrMutex.acquire()
     if(zigbeeLongShortAddr.has_key(parsedData['device_address_long'])):
@@ -475,6 +483,7 @@ def processUdpZdoBindReqMessage(parsedData, addr):
     # if there is not one then we cannot since we need both the short and
     # the long address
     if(shortAddr != None):
+        print "> Short address exists", shortAddr
 
         # get a request number
         seqNumber = createSequenceNumberForClient(addr, parsedData['packet_id'])
@@ -488,12 +497,12 @@ def processUdpZdoBindReqMessage(parsedData, addr):
 
         # a bind request was made so must store and wait for response 
         # before we setup callbacks, so keep just the data we need to create the callback
-        zigeeBindRequestMutex.acquire()
-        zigeeBindRequest[seqNumber] = (parsedData['device_address_long'],
+        zigbeeBindRequestMutex.acquire()
+        zigbeeBindRequest[seqNumber] = (parsedData['device_address_long'],
                                         parsedData['cluster_id'], 
                                         parsedData['packet_id'], 
                                         addr)
-        zigeeBindRequestMutex.release()
+        zigbeeBindRequestMutex.release()
 
         # construct the short and long addresses of the message for sending
         # make sure they are in the correct format
@@ -532,10 +541,10 @@ def processUdpZdoBindReqMessage(parsedData, addr):
         pass
 
 def processUdpZdoUnBindReqMessage(parsedData, addr):
-    zibeeHACallbackMutex.acquire();
+    zigbeeHACallbackMutex.acquire();
     if(zibeeHACallback.has_key(parsedData['device_address_long'], parsedData['cluster_id'])):
         zibeeHACallback(parsedData['device_address_long'], parsedData['cluster_id']).remove(addr)
-    zibeeHACallbackMutex.release()
+    zigbeeHACallbackMutex.release()
     sendUdpSuccessFail(addr, 'zdo_unbind_request', parsedData['packet_id'], True)
 
 
@@ -550,7 +559,7 @@ def processUdpSendAddressMessage(parsedData, addr):
     global zigbeeLongShortAddrMutex
     global zigbeeUnregisteredAddresses
     global zigbeeUnregisteredAddressesMutex
-    global sendSoceket
+    global sendSocket
 
     print "process send address"
     
@@ -561,7 +570,7 @@ def processUdpSendAddressMessage(parsedData, addr):
     message += "response: success\n"
 
     # tell client that we got their request
-    sendSoceket.sendto(message,addr)
+    sendSocket.sendto(message,addr)
     print "responding", message
     
     # construct 
@@ -578,13 +587,15 @@ def processUdpSendAddressMessage(parsedData, addr):
     zigbeeUnregisteredAddresses.append(parsedData['device_address_long'])
     zigbeeUnregisteredAddressesMutex.release()
 
-#made by changwoo
+
+
+# Added by Changwoo
 def processUdpEnrollmentResponse(parsedData, addr):
 
     global zigbeeLongShortAddr
     global zigbeeLongShortAddrMutex
-    global zigeeBindRequestMutex
-    global zigeeBindRequest
+    global zigbeeBindRequestMutex
+    global zigbeeBindRequest
     global zigbeeConnectionMutex
     global zigbeeConnection
     shortAddr = None
@@ -650,13 +661,13 @@ def processUdpEnrollmentResponse(parsedData, addr):
 
 
 
-#made by changwoo
+# Added by Changwoo
 def processUdpZclWriteAttributesMessage(parsedData, addr):
 
     global zigbeeLongShortAddr
     global zigbeeLongShortAddrMutex
-    global zigeeBindRequestMutex
-    global zigeeBindRequest
+    global zigbeeBindRequestMutex
+    global zigbeeBindRequest
     global zigbeeConnectionMutex
     global zigbeeConnection
     shortAddr = None
@@ -695,7 +706,6 @@ def processUdpZclWriteAttributesMessage(parsedData, addr):
         payloadData += '\x02'
         payloadData += '\x10\x00'
         payloadData += '\xF0'
-#        payloadData += '\xDA\x9A\xD9\x40\x00\xA2\x13\x00'
         payloadData += hexStringToZigbeeHexString(changeEndian(ZIGBEE_DEVICE_ADDRESS))
 
         zigbeeConnectionMutex.acquire()
@@ -721,13 +731,13 @@ def processUdpZclWriteAttributesMessage(parsedData, addr):
         sendUdpSuccessFail(addr, 'zcl_write_attributes', parsedData['packet_id'], False, 'short_address_unknown')
         pass
 
-#made by changwoo
+# Added by Changwoo
 def processUdpZclChangeSwitchReqMessage(parsedData, addr):
 
     global zigbeeLongShortAddr
     global zigbeeLongShortAddrMutex
-    global zigeeBindRequestMutex
-    global zigeeBindRequest
+    global zigbeeBindRequestMutex
+    global zigbeeBindRequest
     global zigbeeConnectionMutex
     global zigbeeConnection
     shortAddr = None
@@ -791,14 +801,146 @@ def processUdpZclChangeSwitchReqMessage(parsedData, addr):
         pass
 
 
+# Added by Jiawei
+def processUdpZclLockOrUnlockDoorReqMessage(parsedData, addr):
+
+    global zigbeeLongShortAddr
+    global zigbeeLongShortAddrMutex
+    global zigbeeBindRequestMutex
+    global zigbeeBindRequest
+    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, 'lock_or_unlock_door_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',
+                            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 value == '\x01':
+            print '> The door lock is unlocked'
+        elif value == '\x00':
+            print '> The door lock is locked'
+        else:
+            print '> Unknown door lock value: ' + str(value)
+
+        zigbeeConnectionMutex.release()
+
+
+    else:
+        # send a fail response
+        sendUdpSuccessFail(addr, 'lock_or_unlock_door_request', parsedData['packet_id'], False, 'short_address_unknown')
+
+
+# Added by Jiawei
+def processUdpZclReadDoorStatusReqMessage(parsedData, addr):
+
+    global zigbeeLongShortAddr
+    global zigbeeLongShortAddrMutex
+    global zigbeeBindRequestMutex
+    global zigbeeBindRequest
+    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'])
 
-# made by changwoo
+        # send back failure
+        if(seqNumber == -1):
+
+            # send an error message, could not get a sequence number to use at this time
+            sendUdpSuccessFail(addr, 'read_door_status_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'])
+
+        # create and send binding command
+        zigbeeConnectionMutex.acquire()
+
+        zigbeeConnection.send('tx_explicit',
+                            frame_id='\x40',
+                            dest_addr_long=destLongAddr,
+                            dest_addr=destShortAddr,
+                            src_endpoint='\x01',
+                            dest_endpoint=dstEndpoint,
+                            cluster=clusterId,  
+                            profile=profileId,
+                            data='\x10' + chr(seqNumber) + '\x00' + '\x00\x00'
+                            )
+        time.sleep(1)
+
+        zigbeeConnectionMutex.release()
+        print "send read door status"
+
+    else:
+        # send a fail response
+        sendUdpSuccessFail(addr, 'read_door_status_request', parsedData['packet_id'], False, 'short_address_unknown')
+
+
+# Added by Changwoo
 def processUdpBroadcastingRouteRecordReqMessage(parsedData, addr):
 
     global zigbeeLongShortAddr
     global zigbeeLongShortAddrMutex
-    global zigeeBindRequestMutex
-    global zigeeBindRequest
+    global zigbeeBindRequestMutex
+    global zigbeeBindRequest
     global zigbeeConnectionMutex
     global zigbeeConnection
     shortAddr = None
@@ -856,13 +998,13 @@ def processUdpBroadcastingRouteRecordReqMessage(parsedData, addr):
         pass
 
 
-#made by changwoo
+# Added by Changwoo
 def processUdpManagementPermitJoiningReqMessage(parsedData, addr):
 
     global zigbeeLongShortAddr
     global zigbeeLongShortAddrMutex
-    global zigeeBindRequestMutex
-    global zigeeBindRequest
+    global zigbeeBindRequestMutex
+    global zigbeeBindRequest
     global zigbeeConnectionMutex
     global zigbeeConnection
     global matchDescriptorReqSingleton
@@ -936,8 +1078,8 @@ def processUdpZclReadAttributesMessage(parsedData, addr):
 
     global zigbeeLongShortAddr
     global zigbeeLongShortAddrMutex
-    global zigeeBindRequestMutex
-    global zigeeBindRequest
+    global zigbeeBindRequestMutex
+    global zigbeeBindRequest
     global zigbeeConnectionMutex
     global zigbeeConnection
 
@@ -1027,8 +1169,8 @@ def processUdpZclConfigureReportingMessage(parsedData, addr):
 
     global zigbeeLongShortAddr
     global zigbeeLongShortAddrMutex
-    global zigeeBindRequestMutex
-    global zigeeBindRequest
+    global zigbeeBindRequestMutex
+    global zigbeeBindRequest
     global zigbeeConnectionMutex
     global zigbeeConnection
 
@@ -1102,7 +1244,6 @@ 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
 
@@ -1115,9 +1256,7 @@ def processUdpPolicySet(parsedData, addr):
 
 
     # do nothing if wrong source
-    #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]:
+    if addr == SYSTEM_MASTER_ADDRESS :
         key = (parsedData['ip_address'], int(parsedData['port']))
         if (zigbeeAddressAuthorityDict.has_key(key)):
             zigbeeAddressAuthorityDict[key].append(parsedData['device_address_long'])
@@ -1184,8 +1323,8 @@ def processZigbeeRxExplicitCommandMessage(parsedData):
 
         parsedData -- Pre-parsed (into a dict) data from message.
     '''
-    global zigeeBindRequestMutex
-    global zigeeBindRequest
+    global zigbeeBindRequestMutex
+    global zigbeeBindRequest
     global zigbeeConnectionMutex
     global zigbeeConnection
     global ManagementPermitJoiningReqSuccess
@@ -1211,13 +1350,174 @@ def processZigbeeRxExplicitCommandMessage(parsedData):
     global deviceAnnouncementSingleton
     global seqNumberForNotification
 
+    # Added by Jiawei
+    #doorlock response
+    if (parsedData['cluster'] == '\x01\x01' and parsedData['profile'] == '\x01\x04'):
+        zclSeqNumber = parsedData['rf_data'][1]
+        tup = None
+        zigbeeSeqNumberToClientMutex.acquire()
+        if(zigbeeSeqNumberToClient.has_key(ord(zclSeqNumber))):
+            tup = zigbeeSeqNumberToClient[ord(zclSeqNumber)]
+            del zigbeeSeqNumberToClient[ord(zclSeqNumber)]
+        zigbeeSeqNumberToClientMutex.release()
+
+        rfdata = parsedData['rf_data']
+        framecontrol = rfdata[0]
+        command = rfdata[2]
+
+        if tup != None:
+            packetId = tup[2]
+        
+        if framecontrol == '\x19':
+            if(command == '\x00'):
+                print ''
+                print "( 0x0101 ) Door Lock: Lock Door Response"
+                print time.strftime("%H:%M:%S", time.localtime())
+                value = rfdata[3]
+                if(value == '\x00'):
+                    print "Door locked successfully"
+                else:
+                    print "An error occurred in door locking"
+            elif(command == '\x01'):
+                print ''
+                print "( 0x0101 ) Door Lock: Unlock Door Response"
+                print time.strftime("%H:%M:%S", time.localtime())
+                value = rfdata[3]
+                if(value == '\x00'):
+                    print "Door unlocked successfully"
+                else:
+                    print "An error occurred in door unlocking"
+            return
+        elif framecontrol == '\x18':
+            if(command == '\x01'):
+                attributeId = (ord(rfdata[3]) * 256) + ord(rfdata[4])
+                if attributeId == 0x0000:
+                    value = rfdata[7]
+                    print "Door status: "
+                    if value == '\x00':
+                        print "Not fully locked"
+                    elif value == '\x01':
+                        print "Locked"
+                    elif value == '\x02':
+                        print "Unlocked"
+                    else:
+                        print "Unknown value: " + zigbeeHexStringToHexString(value)
+                           
+                    message = "type : zcl_read_attributes_response \n"
+                    message += "packet_id: " + packetId + "\n"
+                    message += "cluster_id: " + zigbeeHexStringToHexString(parsedData['cluster']) + "\n"
+                    message += "profile_id: " + zigbeeHexStringToHexString(parsedData['profile']) + "\n"
+                    message += "attributes: "
+
+                    attrIdStr = "%0.4x" % attributeId
+                    attrIdStr = changeEndian(attrIdStr)
+                    message += attrIdStr
+                    message += ", "
+
+                    zclPayload = parsedData['rf_data'][3:]
+                    zclPayload = zclPayload[3:]
+                    attributeType = zclPayload[0]
+                    message += "%0.2x" % ord(attributeType)
+                    message += ", "
+
+                    message += "success"
+                    message += ", "
+
+                    message += "%0.2x" % ord(value)
+                    message += ";"
+
+                    message += ";"
+                    
+                    message = message[0:len(message) - 1]
+                    message += "\n"
+
+                    # no one to send the response to so just move on
+                    if(tup == None):
+                        # cant really do anything here
+                        return
+                    sendSocket.sendto(message,tup[0])
+            elif command == '\x07':
+                status = rfdata[3]
+                print ''
+                print "( 0x0101 ) Door Lock: Configure reporting response"
+                print 'rfdata : ' + zigbeeHexStringToHexString(rfdata)
+                if status == '\x00':
+                    print "Configure report successfully"
+                    message = "type : zcl_configure_reporting_response \n"
+                    message += "packet_id: " + packetId + "\n"
+                    message += "cluster_id: " + zigbeeHexStringToHexString(parsedData['cluster']) + "\n"
+                    message += "profile_id: " + zigbeeHexStringToHexString(parsedData['profile']) + "\n"
+                    message += "attributes: " 
+                    message +=  "all_success \n";
+
+                    # no one to send the response to so just move on
+                    if(tup == None):
+                        # cant really do anything here
+                        return
+                    sendSocket.sendto(message,tup[0])
+                else:     
+                    print "Configure report unsuccessfully, status =", zigbeeHexStringToHexString(status)
+            elif(command == '\x0A'):
+                print "New update"
+                attributeId = (ord(rfdata[3]) * 256) + ord(rfdata[4])
+                if attributeId == 0x0000:
+                    value = rfdata[6]
+                    if value == '\x00':
+                        print "Not fully locked"
+                    elif value == '\x01':
+                        print "Locked"
+                    elif value == '\x02':
+                        print "Unlocked"
+                    else:
+                        print "Unknown value: " + zigbeeHexStringToHexString(value)
+
+                    message = "type : zcl_read_attributes_response \n"
+                    message += "packet_id: " + ("%0.2x" % ord(zclSeqNumber)) + "\n"
+                    message += "cluster_id: " + zigbeeHexStringToHexString(parsedData['cluster']) + "\n"
+                    message += "profile_id: " + zigbeeHexStringToHexString(parsedData['profile']) + "\n"
+                    message += "attributes: "
+
+                    attrIdStr = "%0.4x" % attributeId
+                    attrIdStr = changeEndian(attrIdStr)
+                    message += attrIdStr
+                    message += ", "
+
+                    zclPayload = parsedData['rf_data'][3:]
+                    zclPayload = zclPayload[3:]
+                    attributeType = zclPayload[0]
+                    message += "%0.2x" % ord(attributeType)
+                    message += ", "
+
+                    message += "success"
+                    message += ", "
+
+                    message += "%0.2x" % ord(value)
+                    message += ";"
+
+                    message += ";"
+                    
+                    message = message[0:len(message) - 1]
+                    message += "\n"
+
+                    # get callback clients to respond to
+                    callbackIndex = (zigbeeHexStringToHexString(parsedData['source_addr_long']), zigbeeHexStringToHexString(parsedData['cluster']))
+                    retAddr = None
+                    zigbeeHACallbackMutex.acquire()
+                    if(zibeeHACallback.has_key(callbackIndex)):
+                        retAddr = zibeeHACallback[callbackIndex]
+                    zigbeeHACallbackMutex.release()
+
+                    # no one to respond to so do nothing here
+                    if(retAddr == None):
+                        return
+                    for ra in retAddr:
+                        sendSocket.sendto(message,ra)
+            return
+
     # if this is a ZDO message/response
-    #print "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
-    #print parsedData
-    #print "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
     if(parsedData['profile'] == '\x00\x00'):
 
-       # made by changwoo
+       # Added by Changwoo
         # if this is a Match Descriptor Request so we need to answer.
         if(parsedData['cluster'] == '\x00\x06' and matchDescriptorReqSingleton):
             zigbeeConnectionMutex.acquire()
@@ -1253,7 +1553,6 @@ def processZigbeeRxExplicitCommandMessage(parsedData):
 
         # if this is a device announcement so we can get some useful data from it
         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])
@@ -1274,8 +1573,7 @@ def processZigbeeRxExplicitCommandMessage(parsedData):
                 zigbeeUnregisteredAddresses.remove(longAddr)
             zigbeeUnregisteredAddressesMutex.release()
 
-
-           # made by changwoo
+            # Added by Changwoo
             zigbeeConnectionMutex.acquire()
             zigbeeConnection.send('tx_explicit',
                             frame_id='\x08',
@@ -1301,15 +1599,15 @@ def processZigbeeRxExplicitCommandMessage(parsedData):
             # 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>"
+            print "> response to a zdo bind_req message parsedData"
 
             # get the bind tuple information
             # for this specific bind request
             tup = None
-            zigeeBindRequestMutex.acquire() 
-            if(zigeeBindRequest.has_key(ord(seqNumber))):
-                tup = zigeeBindRequest[ord(seqNumber)]
-            zigeeBindRequestMutex.release()
+            zigbeeBindRequestMutex.acquire() 
+            if(zigbeeBindRequest.has_key(ord(seqNumber))):
+                tup = zigbeeBindRequest[ord(seqNumber)]
+            zigbeeBindRequestMutex.release()
 
             if(tup == None):
                 # cant really do anything in this case...
@@ -1321,16 +1619,18 @@ def processZigbeeRxExplicitCommandMessage(parsedData):
 
                 # add a callback for this specific device and cluster 
                 # to the HA callback dict 
-                zibeeHACallbackMutex.acquire();
+                zigbeeHACallbackMutex.acquire();
                 if(zibeeHACallback.has_key((tup[0], tup[1]))):
                     if(tup[3] not in zibeeHACallback[(tup[0], tup[1])]):
                         zibeeHACallback[(tup[0], tup[1])].append(tup[3])
                 else:
                     zibeeHACallback[(tup[0], tup[1])] = [tup[3]]
-                zibeeHACallbackMutex.release()
-
+                zigbeeHACallbackMutex.release()
+                
                 # send success message
                 sendUdpSuccessFail(tup[3], 'zdo_bind_request', tup[2], True)
+                
+                print "> Success message sent!"
 
             # Not Supported
             elif (ord(statusCode) == 170):
@@ -1346,7 +1646,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"
+            #print ">response to a short address query 0x8000"
             
             # get a status code
             statusCode = parsedData['rf_data'][0]
@@ -1371,13 +1671,13 @@ def processZigbeeRxExplicitCommandMessage(parsedData):
             zigbeeLongShortAddr[longAddr] = shortAddr
             zigbeeLongShortAddrMutex.release()
 
-       #made by changwoo
+       # Added by Changwoo
         elif(parsedData['cluster'] == '\x80\x06'):
            print ''
            print '[ 0x8006 ] get Match Descriptor Response'
            print '> rfdata : '+zigbeeHexStringToHexString(parsedData['rf_data'])
 
-       #made by changwoo
+       # Added by Changwoo
         elif(parsedData['cluster'] == '\x80\x36'):
            print ''
            print '[ 0x8036 ] get Management Permit Joining Response'
@@ -1385,7 +1685,7 @@ def processZigbeeRxExplicitCommandMessage(parsedData):
 
            ManagementPermitJoiningReqSuccess = True
 
-       #made by changwoo
+       # Added by Changwoo
         else :
            print ''
            print '[ '+zigbeeHexStringToHexString(parsedData['cluster'])+' ] ...'
@@ -1401,7 +1701,7 @@ def processZigbeeRxExplicitCommandMessage(parsedData):
         zclCommand = parsedData['rf_data'][2]
        zclStatus = parsedData['rf_data'][3]
 
-       #made by changwoo
+       # Added by Changwoo
         if(zclCommand == '\x00'):
            print ''
            print '> ('+zigbeeHexStringToHexString(zclStatus)+') notification! : '+ zigbeeHexStringToHexString( parsedData['rf_data'] )
@@ -1431,7 +1731,7 @@ def processZigbeeRxExplicitCommandMessage(parsedData):
             message += "attributes: success"
             message += "\n"
             # send the socket
-            sendSoceket.sendto(message,tup[0])
+            sendSocket.sendto(message,tup[0])
            print(">port : ", tup[0][1])
 
 
@@ -1527,13 +1827,10 @@ def processZigbeeRxExplicitCommandMessage(parsedData):
             message = message[0:len(message) - 1]
             message += "\n"
             # send the socket
-            sendSoceket.sendto(message,tup[0])
-
+            sendSocket.sendto(message,tup[0])
 
-
-
-       # made by changwoo
-        # this is a zcl write attribute response
+       # Added by Changwoo
+    # this is a zcl write attribute response
        elif(zclCommand == '\x04'):
 
             # get the zcl payload
@@ -1563,7 +1860,7 @@ def processZigbeeRxExplicitCommandMessage(parsedData):
                 message += "attributes: success"
                 message += "\n"
                 # send the socket
-                sendSoceket.sendto(message,tup[0])
+                sendSocket.sendto(message,tup[0])
                print ''
                print '[ 0x0500 ] get Write Attribute Response success'
                print '> rfdata : '+zigbeeHexStringToHexString(parsedData['rf_data'])
@@ -1606,7 +1903,7 @@ def processZigbeeRxExplicitCommandMessage(parsedData):
                 # if all the configurations are a success then only send back a success
                 # based on zigbee specs
                 message +=  "all_success \n";
-                sendSoceket.sendto(message,tup[0])
+                sendSocket.sendto(message,tup[0])
             
             else:
                 attibuteResponseList = []
@@ -1644,7 +1941,7 @@ def processZigbeeRxExplicitCommandMessage(parsedData):
 
                 message = message[0:len(message) - 1]
                 message += "\n"
-                sendSoceket.sendto(message,tup[0])
+                sendSocket.sendto(message,tup[0])
 
         # this is a zcl report attribute message
         elif(zclCommand == '\x0a'):
@@ -1675,10 +1972,10 @@ def processZigbeeRxExplicitCommandMessage(parsedData):
             # get callback clients to respond to
             callbackIndex = (zigbeeHexStringToHexString(parsedData['source_addr_long']), zigbeeHexStringToHexString(parsedData['cluster']))
             retAddr = None
-            zibeeHACallbackMutex.acquire()
+            zigbeeHACallbackMutex.acquire()
             if(zibeeHACallback.has_key(callbackIndex)):
                 retAddr = zibeeHACallback[callbackIndex]
-            zibeeHACallbackMutex.release()
+            zigbeeHACallbackMutex.release()
 
             # no one to respond to so do nothing here
             if(retAddr == None):
@@ -1715,7 +2012,7 @@ def processZigbeeRxExplicitCommandMessage(parsedData):
            
             # send to all client that want this callback
             for ra in retAddr:
-                sendSoceket.sendto(message,ra)
+                sendSocket.sendto(message,ra)
 
 # -----------------------------------------------------------------------------
 # Communication Callback/Parse Methods
@@ -1727,23 +2024,25 @@ def handleNewZigbeeMessage(parsedData):
     '''
     #print "=================================================================="
     #print ''
-    print "New Zigbee Message"
+    #print "New Zigbee Message"
     #printMessageData(parsedData)
 
     # dispatch to the correct zigbee handler
     if (parsedData['id'] == 'at_response'):
-        print "parsedDataID : at_response"
+        #print "parsedDataID : at_response"
         processZigbeeATCommandMessage(parsedData)
 
     elif (parsedData['id'] == 'rx_explicit'):
-        print "parsedDataID : rx_explicit"
+        #print "parsedDataID : rx_explicit"
         processZigbeeRxExplicitCommandMessage(parsedData)
 
-    else:
-        print "Unknown API format"
+    #else:
+        #print "Unknown API format"
 
     #print "=================================================================="
 
+
+
 def handleNewUdpPacket(data, addr):
     ''' Method to parse and handle an incoming UDP packet.
 
@@ -1791,24 +2090,28 @@ def handleNewUdpPacket(data, addr):
         elif(parsedData["type"] == "zcl_read_attributes"):
             processUdpZclReadAttributesMessage(parsedData, addr)
         elif(parsedData["type"] == "zcl_configure_reporting"):
-            print "> zcl_configure_reporting call"
+            print "> processUdpZclConfigureReportingMessage 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
+        elif(parsedData["type"] == "management_permit_joining_request"): # Added by Changwoo
+            processUdpManagementPermitJoiningReqMessage(parsedData, addr)
+        elif(parsedData["type"] == "zcl_write_attributes" and ManagementPermitJoiningReqSuccess): # Added 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)
+        elif(parsedData["type"] == "zcl_enrollment_response"): # Added by Changwoo
+            processUdpEnrollmentResponse(parsedData, addr)
+        elif(parsedData["type"] == "zdo_broadcast_route_record_request"): # Added by Changwoo
+            processUdpBroadcastingRouteRecordReqMessage(parsedData, addr)
+        elif(parsedData["type"] == "zcl_change_switch_request"): # Added by Changwoo
+            processUdpZclChangeSwitchReqMessage(parsedData, addr)
+        elif(parsedData["type"] == "zcl_lock_or_unlock_door_request"): # Added by Jiawei
+            processUdpZclLockOrUnlockDoorReqMessage(parsedData, addr)
+        elif(parsedData["type"] == "zcl_read_door_status_request"): # Added by Jiawei
+            processUdpZclReadDoorStatusReqMessage(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
@@ -1850,8 +2153,7 @@ 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(('192.168.2.227', UDP_RECEIVE_PORT))
-    receiveSoceket.bind(('192.168.2.192', UDP_RECEIVE_PORT))
+    receiveSocket.bind((LOCAL_ADDRESS, UDP_RECEIVE_PORT))
 
     # create the thread that does short address lookups
     addressUpdateWorkerThread = threading.Thread(target=addressUpdateWorkerMethod)
@@ -1862,12 +2164,12 @@ def main():
         while(True):
             print "=================================================================="
             print ''
-           print "Waiting..."
+            print "Waiting..."
             print "=================================================================="
 
             # wait for an incoming UDP packet
             # this is a blocking call
-            data, addr = receiveSoceket.recvfrom(4096)
+            data, addr = receiveSocket.recvfrom(4096)
 
             # handle the UDP packet appropriately
             handleNewUdpPacket(data, addr)
@@ -1889,8 +2191,8 @@ def main():
 
     # make sure to close all the connections
     zigbeeConnection.halt()
-    receiveSoceket.close()
-    sendSoceket.close()
+    receiveSocket.close()
+    sendSocket.close()
 
 if __name__ == "__main__":
     # call main function since this is being run as the start