fixing get_user bugs when user null

This commit is contained in:
Fanani M. Ihsan 2016-05-29 20:27:01 +07:00
parent 16acb77cbe
commit ff4495e0f7
2 changed files with 151 additions and 158 deletions

40
test.py
View File

@ -8,10 +8,9 @@ from zk import const
zk = zk.ZK('192.168.1.201', port=4370, timeout=5) zk = zk.ZK('192.168.1.201', port=4370, timeout=5)
print 'Connecting to device ...' print 'Connecting to device ...'
conn = zk.connect() conn = zk.connect()
if conn.get('status'): if conn:
print conn
print 'Disabling device ...' print 'Disabling device ...'
print zk.disable_device() zk.disable_device()
print 'Firmware Version: : {}'.format(zk.get_firmware_version()) print 'Firmware Version: : {}'.format(zk.get_firmware_version())
# Load test create 2000 users # Load test create 2000 users
# for i in range(1, 2000+1): # for i in range(1, 2000+1):
@ -19,31 +18,28 @@ if conn.get('status'):
# if i == 1: # if i == 1:
# privilege = const.USER_ADMIN # privilege = const.USER_ADMIN
# print zk.set_user(uid=i, name='user #{}'.format(i), privilege=privilege, password='12345678', group_id='', user_id='{}'.format(i)) # print zk.set_user(uid=i, name='user #{}'.format(i), privilege=privilege, password='12345678', group_id='', user_id='{}'.format(i))
print '--- Get User ---' # print '--- Get User ---'
users = zk.get_users() users = zk.get_users()
if users.get('status'): for user in users:
for user in users.get('data'): privilege = 'User'
privilege = 'User' if user.privilege == const.USER_ADMIN:
if user.privilege == const.USER_ADMIN: privilege = 'Admin'
privilege = 'Admin'
print '- UID #{}'.format(user.uid) print '- UID #{}'.format(user.uid)
print ' Name : {}'.format(user.name) print ' Name : {}'.format(user.name)
print ' Privilege : {}'.format(privilege) print ' Privilege : {}'.format(privilege)
print ' Password : {}'.format(user.password) print ' Password : {}'.format(user.password)
print ' Group ID : {}'.format(user.group_id) print ' Group ID : {}'.format(user.group_id)
print ' User ID : {}'.format(user.user_id) print ' User ID : {}'.format(user.user_id)
print "Voice Test ..." print "Voice Test ..."
print zk.test_voice() zk.test_voice()
# print 'Restarting device ...' # print 'Restarting device ...'
# print zk.restart() # zk.restart()
# print 'Turning off device ...' # print 'Turning off device ...'
# print zk.power_off() # zk.power_off()
print 'Enabling device ...' print 'Enabling device ...'
print zk.enable_device() zk.enable_device()
print 'Disconnecting to device ...' print 'Disconnecting to device ...'
print zk.disconnect() zk.disconnect()
else:
print 'Connecting Error: {}'.format(conn.get('message'))

View File

@ -7,15 +7,18 @@ from zk.user import User
class ZK(object): class ZK(object):
__data_recv = None
is_connect = False is_connect = False
__data_recv = None
__sesion_id = 0
__reply_id = 0
def __init__(self, ip, port=4370, timeout=60): def __init__(self, ip, port=4370, timeout=60):
self.__address = (ip, port) self.__address = (ip, port)
self.__sock = socket(AF_INET, SOCK_DGRAM) self.__sock = socket(AF_INET, SOCK_DGRAM)
self.__sock.settimeout(timeout) self.__sock.settimeout(timeout)
def __create_header(self, command, checksum=0, session_id=0, reply_id=65534, command_string=''): def __create_header(self, command, command_string, checksum, session_id, reply_id):
''' '''
Puts a the parts that make up a packet together and packs them into a byte string Puts a the parts that make up a packet together and packs them into a byte string
''' '''
@ -55,40 +58,24 @@ class ZK(object):
return pack('H', checksum) return pack('H', checksum)
def __send_command(self, command, command_string='', response_size=8, checksum=0): def __send_command(self, command, command_string, checksum, session_id, reply_id, response_size):
try: buf = self.__create_header(command, command_string, checksum, session_id, reply_id)
buf = self.__create_header(command, checksum, self.__sesion_id, self.__reply_id, command_string) self.__sock.sendto(buf, self.__address)
self.__sending_packet(buf) self.__data_recv = self.__sock.recv(response_size)
self.__receive_packet(response_size) self.__response = unpack('HHHH', self.__data_recv[:8])[0]
self.__reply_id = unpack('HHHH', self.__data_recv[:8])[3]
if self.__response == const.CMD_ACK_OK: if self.__response in [const.CMD_ACK_OK, const.CMD_PREPARE_DATA]:
return { return {
'status': True, 'status': True,
'code': self.__response, 'code': self.__response
'message': 'success', }
'data': self.__data_recv else:
}
else:
return {
'status': False,
'code': self.__response,
'message': 'failed',
'data': self.__data_recv
}
except Exception, e:
return { return {
'status': False, 'status': False,
'code': const.CMD_ACK_ERROR, 'code': self.__response
'message': str(e),
'data': ''
} }
def __sending_packet(self, buf):
self.__sock.sendto(buf, self.__address)
def __receive_packet(self, buf_size):
self.__data_recv = self.__sock.recv(buf_size)
def __get_data_size(self): def __get_data_size(self):
"""Checks a returned packet to see if it returned CMD_PREPARE_DATA, """Checks a returned packet to see if it returned CMD_PREPARE_DATA,
indicating that data packets are to be sent indicating that data packets are to be sent
@ -101,39 +88,26 @@ class ZK(object):
else: else:
return 0 return 0
@property
def __response(self):
'''
Checks a returned packet to see if it returned `CMD_ACK_OK` indicating success
'''
return unpack('HHHH', self.__data_recv[:8])[0]
@property
def __sesion_id(self):
if not self.__data_recv:
return 0
return unpack('HHHH', self.__data_recv[:8])[2]
@property
def __reply_id(self):
if not self.__data_recv:
return const.USHRT_MAX - 1
return unpack('HHHH', self.__data_recv[:8])[3]
def connect(self): def connect(self):
''' '''
connect to device connect to device
''' '''
command = const.CMD_CONNECT command = const.CMD_CONNECT
cmd_response = self.__send_command(command) command_string = ''
cmd_response['data'] = '' checksum = 0
session_id = 0
reply_id = const.USHRT_MAX - 1
response_size = 8
cmd_response = self.__send_command(command, command_string, checksum, session_id, reply_id, response_size)
if cmd_response.get('status'): if cmd_response.get('status'):
self.is_connect = True self.is_connect = True
cmd_response['message'] = 'connected' # set the session id
return cmd_response self.__sesion_id = unpack('HHHH', self.__data_recv[:8])[2]
return True
else: else:
return cmd_response raise Exception("Invalid response")
def disconnect(self): def disconnect(self):
''' '''
@ -141,26 +115,69 @@ class ZK(object):
''' '''
command = const.CMD_EXIT command = const.CMD_EXIT
cmd_response = self.__send_command(command) command_string = ''
cmd_response['data'] = '' checksum = 0
session_id = self.__sesion_id
reply_id = self.__reply_id
response_size = 8
cmd_response = self.__send_command(command, command_string, checksum, session_id, reply_id, response_size)
if cmd_response.get('status'): if cmd_response.get('status'):
cmd_response['message'] = 'disconnected' return True
return cmd_response
else: else:
return cmd_response raise Exception("Invalid response")
def disable_device(self):
'''
disable (lock) connected device, make sure no activity when process run
'''
command = const.CMD_DISABLEDEVICE
command_string = ''
checksum = 0
session_id = self.__sesion_id
reply_id = self.__reply_id
response_size = 8
cmd_response = self.__send_command(command, command_string, checksum, session_id, reply_id, response_size)
if cmd_response.get('status'):
return True
else:
raise Exception("Invalid response")
def enable_device(self):
'''
re-enable connected device
'''
command = const.CMD_ENABLEDEVICE
command_string = ''
checksum = 0
session_id = self.__sesion_id
reply_id = self.__reply_id
response_size = 8
cmd_response = self.__send_command(command, command_string, checksum, session_id, reply_id, response_size)
if cmd_response.get('status'):
return True
else:
raise Exception("Invalid response")
def get_firmware_version(self): def get_firmware_version(self):
''' '''
get firmware version name get firmware version name
''' '''
command = const.CMD_GET_VERSION command = const.CMD_GET_VERSION
cmd_response = self.__send_command(command, response_size=1024) command_string = ''
checksum = 0
session_id = self.__sesion_id
reply_id = self.__reply_id
response_size = 1024
cmd_response = self.__send_command(command, command_string, checksum, session_id, reply_id, response_size)
if cmd_response.get('status'): if cmd_response.get('status'):
cmd_response['data'] = cmd_response.get('data')[8:].strip('\x00|\x01\x10x') firmware_version = self.__data_recv[8:].strip('\x00|\x01\x10x')
return cmd_response return firmware_version
else: else:
cmd_response['data'] = '' raise Exception("Invalid response")
return cmd_response
def restart(self): def restart(self):
''' '''
@ -168,13 +185,17 @@ class ZK(object):
''' '''
command = const.CMD_RESTART command = const.CMD_RESTART
cmd_response = self.__send_command(command) command_string = ''
cmd_response['data'] = '' checksum = 0
session_id = self.__sesion_id
reply_id = self.__reply_id
response_size = 8
cmd_response = self.__send_command(command, command_string, checksum, session_id, reply_id, response_size)
if cmd_response.get('status'): if cmd_response.get('status'):
cmd_response['message'] = 'device restarted' return True
return cmd_response
else: else:
return cmd_response raise Exception("Invalid response")
def power_off(self): def power_off(self):
''' '''
@ -182,52 +203,34 @@ class ZK(object):
''' '''
command = const.CMD_POWEROFF command = const.CMD_POWEROFF
cmd_response = self.__send_command(command) command_string = ''
cmd_response['data'] = '' checksum = 0
if cmd_response.get('status'): session_id = self.__sesion_id
cmd_response['message'] = 'device turning off' reply_id = self.__reply_id
return cmd_response response_size = 8
else:
return cmd_response
def disable_device(self): cmd_response = self.__send_command(command, command_string, checksum, session_id, reply_id, response_size)
'''
disable (lock) connected device, make sure no activity when process run
'''
command = const.CMD_DISABLEDEVICE
cmd_response = self.__send_command(command)
cmd_response['data'] = ''
if cmd_response.get('status'): if cmd_response.get('status'):
cmd_response['message'] = 'device disabled' return True
return cmd_response
else: else:
return cmd_response raise Exception("Invalid response")
def enable_device(self):
'''
re-enable connected device
'''
command = const.CMD_ENABLEDEVICE
cmd_response = self.__send_command(command)
cmd_response['data'] = ''
if cmd_response.get('status'):
cmd_response['message'] = 'device enabled'
return cmd_response
else:
return cmd_response
def test_voice(self): def test_voice(self):
''' '''
play test voice play test voice
''' '''
command = const.CMD_TESTVOICE command = const.CMD_TESTVOICE
cmd_response = self.__send_command(command) command_string = ''
cmd_response['data'] = '' checksum = 0
session_id = self.__sesion_id
reply_id = self.__reply_id
response_size = 8
cmd_response = self.__send_command(command, command_string, checksum, session_id, reply_id, response_size)
if cmd_response.get('status'): if cmd_response.get('status'):
cmd_response['message'] = 'voice detected' return True
return cmd_response
else: else:
return cmd_response raise Exception("Invalid response")
def set_user(self, uid, name, privilege, password='', group_id='', user_id=''): def set_user(self, uid, name, privilege, password='', group_id='', user_id=''):
''' '''
@ -241,25 +244,35 @@ class ZK(object):
privilege = chr(privilege) privilege = chr(privilege)
command_string = pack('2sc8s28sc7sx24s', uid, privilege, password, name, chr(0), group_id, user_id) command_string = pack('2sc8s28sc7sx24s', uid, privilege, password, name, chr(0), group_id, user_id)
cmd_response = self.__send_command(command, command_string, 1024) checksum = 0
cmd_response['data'] = '' session_id = self.__sesion_id
reply_id = self.__reply_id
response_size = 1024
cmd_response = self.__send_command(command, command_string, checksum, session_id, reply_id, response_size)
if cmd_response.get('status'): if cmd_response.get('status'):
cmd_response['message'] = 'new user created' return True
return cmd_response
else: else:
return cmd_response raise Exception("Invalid response")
def get_users(self): def get_users(self):
''' '''
get all users get all users
''' '''
command = const.CMD_USERTEMP_RRQ command = const.CMD_USERTEMP_RRQ
cmd_response = self.__send_command(command=command, response_size=1024) command_string = ''
if cmd_response: checksum = 0
bytes = self.__get_data_size() session_id = self.__sesion_id
userdata = [] reply_id = self.__reply_id
if bytes: response_size = 1024
while bytes > 0:
cmd_response = self.__send_command(command, command_string, checksum, session_id, reply_id, response_size)
users = []
if cmd_response.get('status'):
if cmd_response.get('code') == const.CMD_PREPARE_DATA:
bytes = self.__get_data_size()
userdata = []
while bytes > 0:
data_recv = self.__sock.recv(1032) data_recv = self.__sock.recv(1032)
userdata.append(data_recv) userdata.append(data_recv)
bytes -= 1024 bytes -= 1024
@ -267,8 +280,7 @@ class ZK(object):
data_recv = self.__sock.recv(8) data_recv = self.__sock.recv(8)
response = unpack('HHHH', data_recv[:8])[0] response = unpack('HHHH', data_recv[:8])[0]
if response == const.CMD_ACK_OK: if response == const.CMD_ACK_OK:
users = [] if userdata:
if len(userdata):
# The first 4 bytes don't seem to be related to the user # The first 4 bytes don't seem to be related to the user
for x in xrange(len(userdata)): for x in xrange(len(userdata)):
if x > 0: if x > 0:
@ -292,25 +304,10 @@ class ZK(object):
users.append(user) users.append(user)
userdata = userdata[72:] userdata = userdata[72:]
cmd_response['status'] = True
cmd_response['code'] = response
cmd_response['message'] = 'success'
cmd_response['data'] = users
return cmd_response
else: else:
return { raise Exception("Invalid response")
'status': False,
'code': response, return users
'message': 'failed',
'data': ''
}
else:
cmd_response['data'] = ''
return cmd_response
else:
cmd_response['data'] = ''
return cmd_response
def cancel_capture(self): def cancel_capture(self):
''' '''