From 402ba438d1739ebe95e35c6fbd93b9250af90512 Mon Sep 17 00:00:00 2001 From: Arturo Hernandez Date: Fri, 27 Apr 2018 20:00:13 -0400 Subject: [PATCH] Added support for python3 (WIP) possible broken a lot of things still needs more safeguards --- test_machine.py | 120 ++++++++++---------- zk/__init__.py | 4 +- zk/base.py | 287 ++++++++++++++++++++++++------------------------ zk/finger.py | 4 +- zk/user.py | 2 +- 5 files changed, 213 insertions(+), 204 deletions(-) diff --git a/test_machine.py b/test_machine.py index c9846e3..4d3aa67 100755 --- a/test_machine.py +++ b/test_machine.py @@ -5,6 +5,7 @@ import traceback import argparse import time import datetime +from builtins import input sys.path.append("zk") @@ -45,42 +46,42 @@ args = parser.parse_args() zk = ZK(args.address, port=args.port, timeout=args.timeout, password=args.password, force_udp=args.force_udp) # , firmware=args.firmware try: - print 'Connecting to device ...' + print('Connecting to device ...') conn = zk.connect() - print 'SDK build=1 :', conn.set_sdk_build_1() # why? - print 'Disabling device ...' + print('SDK build=1 : %s' % conn.set_sdk_build_1()) # why? + print ('Disabling device ...') conn.disable_device() fmt = conn.get_extend_fmt() - print 'ExtendFmt : {}'.format(fmt) + print ('ExtendFmt : {}'.format(fmt)) fmt = conn.get_user_extend_fmt() - print 'UsrExtFmt : {}'.format(fmt) - print 'Face FunOn : {}'.format(conn.get_face_fun_on()) - print 'Face Version : {}'.format(conn.get_face_version()) - print 'Finger Version : {}'.format(conn.get_fp_version()) - print 'Old Firm compat : {}'.format(conn.get_compat_old_firmware()) + print ('UsrExtFmt : {}'.format(fmt)) + print ('Face FunOn : {}'.format(conn.get_face_fun_on())) + print ('Face Version : {}'.format(conn.get_face_version())) + print ('Finger Version : {}'.format(conn.get_fp_version())) + print ('Old Firm compat : {}'.format(conn.get_compat_old_firmware())) net = conn.get_network_params() - print 'IP:{} mask:{} gateway:{}'.format(net['ip'],net['mask'], net['gateway']) + print ('IP:{} mask:{} gateway:{}'.format(net['ip'],net['mask'], net['gateway'])) now = datetime.datetime.today().replace(microsecond=0) if args.updatetime: - print '--- Updating Time---' + print ('--- Updating Time---') conn.set_time(now) zk_time = conn.get_time() dif = abs(zk_time - now).total_seconds() - print 'Time : {}'.format(zk_time) + print ('Time : {}'.format(zk_time)) if dif > 120: print("WRN: TIME IS NOT SYNC!!!!!! (local: %s) use command -u to update" % now) - print 'Firmware Version : {}'.format(conn.get_firmware_version()) - print 'Platform : %s' % conn.get_platform() - print 'DeviceName : %s' % conn.get_device_name() - print 'Pin Width : %i' % conn.get_pin_width() - print 'Serial Number : %s' % conn.get_serialnumber() - print 'MAC: %s' % conn.get_mac() - print '' - print '--- sizes & capacity ---' + print ('Firmware Version : {}'.format(conn.get_firmware_version())) + print ('Platform : %s' % conn.get_platform()) + print ('DeviceName : %s' % conn.get_device_name()) + print ('Pin Width : %i' % conn.get_pin_width()) + print ('Serial Number : %s' % conn.get_serialnumber()) + print ('MAC: %s' % conn.get_mac()) + print ('') + print ('--- sizes & capacity ---') conn.read_sizes() - print conn - print '' - print '--- Get User ---' + print (conn) + print ('') + print ('--- Get User ---') users = conn.get_users() max_uid = 0 prev = None @@ -90,15 +91,15 @@ try: if user.uid > max_uid: max_uid = user.uid privilege = 'User' if user.privilege == const.USER_DEFAULT else 'Admin-%s' % user.privilege - print '-> UID #{:<5} Name : {:<27} Privilege : {}'.format(user.uid, user.name, privilege) - print ' Group ID : {:<8} User ID : {:<8} Password : {:<8} Card : {}'.format(user.group_id, user.user_id, user.password, user.card) - #print len (user.repack73()), user.repack73().encode('hex') - #print '' + print ('-> UID #{:<5} Name : {:<27} Privilege : {}'.format(user.uid, user.name, privilege)) + print (' Group ID : {:<8} User ID : {:<8} Password : {:<8} Card : {}'.format(user.group_id, user.user_id, user.password, user.card)) + #print (len (user.repack73()), user.repack73().encode('hex')) + #print ('') if args.adduser and user.uid == args.adduser: prev = user if args.deleteuser: - print '' - print '-- Delete User UID#%s ---' % args.deleteuser + print ('') + print ('-- Delete User UID#%s ---' % args.deleteuser) #TODO implementar luego conn.delete_user(args.deleteuser) users = conn.get_users() #update @@ -106,8 +107,8 @@ try: if user.uid > max_uid: max_uid = user.uid privilege = 'User' if user.privilege == const.USER_DEFAULT else 'Admin-%s' % user.privilege - print '-> UID #{:<5} Name : {:<27} Privilege : {}'.format(user.uid, user.name, privilege) - print ' Group ID : {:<8} User ID : {:<8} Password : {:<8} Card : {}'.format(user.group_id, user.user_id, user.password, user.card) + print ('-> UID #{:<5} Name : {:<27} Privilege : {}'.format(user.uid, user.name, privilege)) + print (' Group ID : {:<8} User ID : {:<8} Password : {:<8} Card : {}'.format(user.group_id, user.user_id, user.password, user.card)) #print len (user.repack73()), user.repack73().encode('hex') #print '' if args.adduser and user.uid == args.adduser: @@ -118,25 +119,26 @@ try: if prev: user = prev privilege = 'User' if user.privilege == const.USER_DEFAULT else 'Admin-%s' % user.privilege - print '' - print '--- Modify User %i ---' % user.uid - print '-> UID #{:<5} Name : {:<27} Privilege : {}'.format(user.uid, user.name, privilege) - print ' Group ID : {:<8} User ID : {:<8} Password : {:<8} Card : {}'.format(user.group_id, user.user_id, user.password, user.card) + print ('') + print ('--- Modify User %i ---' % user.uid) + print ('-> UID #{:<5} Name : {:<27} Privilege : {}'.format(user.uid, user.name, privilege)) + print (' Group ID : {:<8} User ID : {:<8} Password : {:<8} Card : {}'.format(user.group_id, user.user_id, user.password, user.card)) #discard prev else: - print '--- Add new User %i ---' % uid - name = raw_input('Name :') - admin = raw_input('Admin (y/n):') + print ('--- Add new User %i ---' % uid) + name = input('Name :') + admin = input('Admin (y/N):') privilege = 14 if admin == 'y' else 0 - password = raw_input('Password :') - user_id = raw_input('User ID2 :') - card = int(raw_input('Card :')) + password = input('Password :') + user_id = input('User ID2 :') + card = input('Card :') + card = int(card) if card else 0 if prev: conn.delete_user(uid) #borrado previo try: conn.set_user(uid, name, privilege, password, '', user_id, card) - except ZKErrorResponse, e: - print "error: ", e + except ZKErrorResponse as e: + print ("error: %s" % e) #try new format zk_user = User(uid, name, privilege, password, '', user_id, card) conn.save_user_template(zk_user) @@ -147,34 +149,34 @@ try: else: conn.test_voice(23) # not registered conn.refresh_data() - print "Voice Test ..." + print ("Voice Test ...") conn.test_voice(10) if args.templates: - print "Read Templates..." + print ("Read Templates...") templates = conn.get_templates() for tem in templates: - print tem + print (tem) if args.records: - print "Read Records..." + print ("Read Records...") attendance = conn.get_attendance() i = 0 for att in attendance: i +=1 - print "ATT {:>6}: uid:{:>3}, t: {}".format(i, att.uid, att.timestamp) - print '' - print '--- sizes & capacity ---' + print ("ATT {:>6}: uid:{:>3}, t: {}".format(i, att.uid, att.timestamp)) + print ('') + print ('--- sizes & capacity ---') conn.read_sizes() - print conn - print '' -except Exception, e: - print "Process terminate : {}".format(e) - print "Error: %s" % sys.exc_info()[0] - print '-'*60 + print (conn) + print ('') +except Exception as e: + print ("Process terminate : {}".format(e)) + print ("Error: %s" % sys.exc_info()[0]) + print ('-'*60) traceback.print_exc(file=sys.stdout) - print '-'*60 + print ('-'*60) finally: if conn: - print 'Enabling device ...' + print ('Enabling device ...') conn.enable_device() conn.disconnect() - print '' + print ('') diff --git a/zk/__init__.py b/zk/__init__.py index 94900e7..8f49c65 100644 --- a/zk/__init__.py +++ b/zk/__init__.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -from base import ZK +from .base import ZK -VERSION = (0, 3) +VERSION = (0, 9) __all__ = ['ZK'] diff --git a/zk/base.py b/zk/base.py index 69e8ee0..d72c2a2 100644 --- a/zk/base.py +++ b/zk/base.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- import sys +#from builtins import str from datetime import datetime from socket import AF_INET, SOCK_DGRAM, SOCK_STREAM, socket from struct import pack, unpack @@ -110,6 +111,7 @@ class ZK(object): self.__session_id = 0 self.__reply_id = const.USHRT_MAX-1 self.__data_recv = None + self.__data = None def __create_socket(self): """ based on self.tcp""" if self.tcp: @@ -167,7 +169,7 @@ class ZK(object): return pack('H', checksum) - def __send_command(self, command, command_string='', response_size=8): + def __send_command(self, command, command_string=b'', response_size=8): ''' send command to the terminal ''' @@ -186,12 +188,12 @@ class ZK(object): self.__sock.sendto(buf, self.__address) self.__data_recv = self.__sock.recv(response_size) self.__header = unpack('HHHH', self.__data_recv[:8]) - except Exception, e: + except Exception as e: raise ZKNetworkError(str(e)) self.__response = self.__header[0] self.__reply_id = self.__header[3] - + self.__data = self.__data_recv[8:] #could be empty if self.__response in [const.CMD_ACK_OK, const.CMD_PREPARE_DATA, const.CMD_DATA]: return { 'status': True, @@ -203,14 +205,14 @@ class ZK(object): } def __ack_ok(self): """ event ack ok """ - buf = self.__create_header(const.CMD_ACK_OK, "", self.__session_id, const.USHRT_MAX - 1) + buf = self.__create_header(const.CMD_ACK_OK, b'', self.__session_id, const.USHRT_MAX - 1) try: if self.tcp: top = self.__create_tcp_top(buf) self.__sock.send(top) else: self.__sock.sendto(buf, self.__address) - except Exception, e: + except Exception as e: raise ZKNetworkError(str(e)) @@ -221,7 +223,7 @@ class ZK(object): Returns the amount of bytes that are going to be sent""" response = self.__response if response == const.CMD_PREPARE_DATA: - size = unpack('I', self.__data_recv[8:12])[0] + size = unpack('I', self.__data[:4])[0] return size else: return 0 @@ -236,23 +238,26 @@ class ZK(object): """Decode a timestamp retrieved from the timeclock copied from zkemsdk.c - DecodeTime""" + """ t = t.encode('hex') t = int(self.__reverse_hex(t), 16) - #print "decode from %s "% format(t, '04x') + #print ("decode from %s "% format(t, '04x')) + """ + t = unpack("= 28: - uid, privilege, password, name, card, group_id, timezone, user_id = unpack('HB5s8s5sBhI',userdata.ljust(28)[:28]) - password = unicode(password.split('\x00')[0], errors='ignore') - name = unicode(name.split('\x00')[0], errors='ignore').strip() - card = unpack('Q', card.ljust(8,'\x00'))[0] #or hex value? + uid, privilege, password, name, card, group_id, timezone, user_id = unpack('= 72: - uid, privilege, password, name, separator, group_id, user_id = unpack('Hc8s24s4sx7sx24s', userdata.ljust(72)[:72]) + uid, privilege, password, name, card, group_id, user_id = unpack(' 16: #not empty - res = unpack("H", data_recv.ljust(24,"\x00")[16:18])[0] - print "res", res + res = unpack("H", data_recv.ljust(24,b"\x00")[16:18])[0] + print("res %i" % res) if res == 0 or res == 6 or res == 4: # 6 timeout, 4 mismatch error, 0 can't start(why?) print ("posible timeout o reg Fallido") break else: if len(data_recv) > 8: #not empty - res = unpack("H", data_recv.ljust(16,"\x00")[8:10])[0] - print "res", res + res = unpack("H", data_recv.ljust(16,b"\x00")[8:10])[0] + print("res %i" % res) if res == 6 or res == 4: print ("posible timeout o reg Fallido") break - print "A:%i esperando 2do regevent" % attempts + print ("A:%i esperando 2do regevent" % attempts) data_recv = self.__sock.recv(1032) # timeout? tarda bastante... self.__ack_ok() - print (data_recv).encode('hex') + #print ((data_recv).encode('hex')) if self.tcp: if len(data_recv) > 8: #not empty - res = unpack("H", data_recv.ljust(24,"\x00")[16:18])[0] - print "res", res + res = unpack("H", data_recv.ljust(24,b"\x00")[16:18])[0] + print("res %i" % res) if res == 6 or res == 4: print ("posible timeout o reg Fallido") break @@ -1029,8 +1034,8 @@ class ZK(object): attempts -= 1 else: if len(data_recv) > 8: #not empty - res = unpack("H", data_recv.ljust(16,"\x00")[8:10])[0] - print "res", res + res = unpack("H", data_recv.ljust(16,b"\x00")[8:10])[0] + print("res %i" % res) if res == 6 or res == 4: print ("posible timeout o reg Fallido") break @@ -1038,20 +1043,20 @@ class ZK(object): print ("ok, continue?") attempts -= 1 if attempts == 0: - print "esperando 3er regevent" + print ("esperando 3er regevent") data_recv = self.__sock.recv(1032) # timeout? tarda bastante... self.__ack_ok() - print (data_recv).encode('hex') + #print ((data_recv).encode('hex')) if self.tcp: - res = unpack("H", data_recv.ljust(24,"\x00")[16:18])[0] + res = unpack("H", data_recv.ljust(24,b"\x00")[16:18])[0] else: - res = unpack("H", data_recv.ljust(16,"\x00")[8:10])[0] + res = unpack("H", data_recv.ljust(16,b"\x00")[8:10])[0] if res == 6 or res == 4: print ("posible timeout o reg Fallido") if res == 0: - size = unpack("H", data_recv.ljust(16,"\x00")[10:12])[0] - pos = unpack("H", data_recv.ljust(16,"\x00")[12:14])[0] - print "enroll ok", size, pos + size = unpack("H", data_recv.ljust(16,b"\x00")[10:12])[0] + pos = unpack("H", data_recv.ljust(16,b"\x00")[12:14])[0] + print("enroll ok", size, pos) done = True self.__sock.settimeout(self.__timeout) self.cancel_capture() @@ -1081,27 +1086,27 @@ class ZK(object): #else if cmd_response.get('code') == const.CMD_DATA: # less than 1024!!! if self.tcp: - return self.__data_recv[16:] #TODO: check size? + return self.__data[8:] #TODO: check size? else: - return self.__data_recv[8:] + return self.__data if cmd_response.get('code') == const.CMD_PREPARE_DATA: data = [] bytes = self.__get_data_size() #TODO: check with size - #print "prepare data size is", bytes + #print ("prepare data size is", bytes) if self.tcp: data_recv = self.__sock.recv(bytes + 32) recieved = len(data_recv) tcp_length = unpack('HHI', data_recv[:8])[2] #bytes+8 if tcp_length < (bytes + 8): - print "request chunk too big!" + print ("request chunk too big!") response = unpack('HHHH', data_recv[8:16])[0] if recieved >= (bytes + 32): #complete if response == const.CMD_DATA: resp = data_recv[16:bytes+16] # no ack? - #print "resp len", len(resp) + #print ("resp len", len(resp)) return resp else: - print "broken packet!!!" + print("broken packet!!!") return '' #broken else: # incomplete data.append(data_recv[16:]) # w/o tcp and header @@ -1114,16 +1119,16 @@ class ZK(object): data_recv = self.__sock.recv(16) response = unpack('HHHH', data_recv[8:16])[0] if response == const.CMD_ACK_OK: - return ''.join(data) + return b''.join(data) #data_recv[bytes+16:].encode('hex') #included CMD_ACK_OK - print "bad response ", data_recv.encode('hex') + print("bad response %s" % data_recv) #print data return '' #else udp while True: #limitado por respuesta no por tamaño data_recv = self.__sock.recv(response_size) response = unpack('HHHH', data_recv[:8])[0] - #print "# %s packet response is: %s" % (pac, response) + #print ("# %s packet response is: %s" % (pac, response)) if response == const.CMD_DATA: data.append(data_recv[8:]) #header turncated bytes -= 1024 #UDP @@ -1131,10 +1136,10 @@ class ZK(object): break #without problem. else: #truncado! continuar? - print "broken!" + print ("broken!") break - #print "still needs %s" % bytes - return ''.join(data) + #print ("still needs %s" % bytes) + return b''.join(data) def read_with_buffer(self, command, fct=0 ,ext=0): """ Test read info with buffered command (ZK6: 1503) """ @@ -1143,7 +1148,7 @@ class ZK(object): else: MAX_CHUNK = 16 * 1024 command_string = pack('= 8: - uid, status, timestamp = unpack('HH4s', attendance_data.ljust(8)[:8]) + uid, status, timestamp = unpack('HH4s', attendance_data.ljust(8, b'\x00')[:8]) attendance_data = attendance_data[8:] user_id = str(uid) #TODO revisar posibles valores cruzar con userdata timestamp = self.__decode_time(timestamp) @@ -1192,7 +1197,7 @@ class ZK(object): attendances.append(attendance) elif record_size == 16: # extended while len(attendance_data) >= 16: - uid, timestamp, status, verified, reserved, workcode = unpack('= 40: - uid, user_id, sparator, timestamp, status, space = unpack('H24sc4sc8s', attendance_data.ljust(40)[:40]) - user_id = user_id.split('\x00')[0] + uid, user_id, sparator, timestamp, status, space = unpack(' 7sx group id, timezone?