Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

PushSDK Development Guide

Version No.: V1.0


Date: March 2011

1
PushSDK Development Guide Ver 1.0

Contents

1 Document Description................................................................................................................................ 2
1.1 Function Description ......................................................................................................................... 2
1.2 Intended Audience............................................................................................................................. 2
1.3 Terms................................................................................................................................................. 2
1.4 Technical Support Service................................................................................................................. 2

2 Function Description.................................................................................................................................. 3
2.1 Acquire Configuration Information................................................................................................... 3
2.2 Transfer Device Data......................................................................................................................... 4
2.3 Acquire Commands ........................................................................................................................... 4
2.4 Return an Execution Result ............................................................................................................... 4

3 PushSDK Request Parameters and Interfaces ........................................................................................ 4


3.1 CDATA Interface and Related Parameters ........................................................................................ 4
3.1.1 GET Mode .............................................................................................................................. 5
3.1.2 POST Mode............................................................................................................................ 8
3.2 Getrequest Interface ........................................................................................................................ 16
3.2.1 GET Mode ............................................................................................................................ 16
3.3 DeviceCMD Interface ..................................................................................................................... 20

4 Setting up and Configuring Server Environment (Taking Python as An Example)........................... 23

5 Appendix 1 List of Supported Configuration Options .......................................................................... 25

1
PushSDK Development Guide Ver 1.0

Contents

1 Document Description................................................................................................................................ 2
1.1 Function Description ......................................................................................................................... 2
1.2 Intended Audience............................................................................................................................. 2
1.3 Terms................................................................................................................................................. 2
1.4 Technical Support Service................................................................................................................. 2

2 Function Description.................................................................................................................................. 3
2.1 Acquire Configuration Information................................................................................................... 3
2.2 Transfer Device Data......................................................................................................................... 4
2.3 Acquire Commands ........................................................................................................................... 4
2.4 Return an Execution Result ............................................................................................................... 4

3 PushSDK Request Parameters and Interfaces ........................................................................................ 4


3.1 CDATA Interface and Related Parameters ........................................................................................ 4
3.1.1 GET Mode .............................................................................................................................. 5
3.1.2 POST Mode............................................................................................................................ 8
3.2 Getrequest Interface ........................................................................................................................ 16
3.2.1 GET Mode ............................................................................................................................ 16
3.3 DeviceCMD Interface ..................................................................................................................... 20

4 Setting up and Configuring Server Environment (Taking Python as An Example)........................... 23

5 Appendix 1 List of Supported Configuration Options .......................................................................... 25

1
PushSDK Development Guide Ver 1.0

2 Function Description

HTTP PUSH Protocol Flow Diagram:

2.1 Acquire Configuration Information


The device sends a request to the following address:
Post http://IP address of server/iclock/cdata?SN=Device serial number&options=all
The server returns the following information:
GET OPTION FROM: 123456
Stamp=82983982
OpStamp=9238883
PhotoStamp=9238833
ErrorDelay=60
Delay=30
TransTimes=00:00;14:05
TransInterval=1

3
PushSDK Development Guide Ver 1.0

1 Document Description

Thank you for using the PushSDK of our company to develop server applications. PUSHSDK is
a communication protocol developed by ZTE based on the Hyper Text Transfer Protocol (HTTP). It
implements data transfer by adopting the mechanism that enables a device to access the server in an
unsolicited mode. PUSHSDK is applicable to stable TCP/IP­capable networks, for example, the commonly
used Local Area Network (LAN) and the World Wide Web (WWW). It supports resumable multithread
downloading and unsolicited upload of new information. Its high scalability allows users to conveniently
develop and extend new functions.

1.1 Function Description


PushSDK provides an HTTP­based data transfer format to support data transmission and communication
between the device and the server.

1.2 Intended Audience


This document is intended for the website developers, maintenance engineers and administrators who
understand web programming languages and database languages and have capability of developing
websites.

1.3 Terms
Term Meaning
Interface Provides a URL address for the device to communicate with the server.
Request Indicates a process of sending data over HTTP to the recipient.
Indicates a process of returning relevant information from the server to the device based on the
Return
requested address.
Denotes the time at which data is uploaded and the device obtains information from the server.
Timestamp
Timestamp is used for time synchronization between the device and the server.
IP address of server Indicates the IP address of a web server
Device sequence
Indicates the unique serial number displayed on the device.
number

2
PushSDK Development Guide Ver 1.0

3.1.1 GET Mode


When a device sends a request in GET mode to the server, the device aims to obtain the configuration
information related to itself.
IP address of the accessed interface:
http://IP address of
server/iclock/cdata?SN={SNO}&options=all&pushver={Version}&language={LanguageNo}
Parameter Meaning
{SNO} Device serial number
{Version} PushSDK version number
{LanguageNo} Language version number

The parameter {LanguageNo} supports the following values:


Parameter value Meaning
83 Chinese
69 English

The server returns the following information:


GET OPTION FROM: {SNO}
Stamp={Stamp}
OpStamp={OpStamp}
PhotoStamp={PhotoStamp}
ErrorDelay={ ErrorDelay }
Delay={ Delay }
TransTimes={ TransTimes }
TransInterval={ TransInterval }
TransFlag={ TransFlag }
Realtime={ Realtime }
Encrypt={Encrypt}
ServerVer={ServerVer}
{ TableNameStamp }

The meanings of the parameters above are listed as follows:


Parameter Meaning
{SNO} Indicates the device serial number.
Indicates the time at which the device uploads the latest attendance logs (This parameter is used
{ Stamp }
by the protocol firmware of earlier versions, but is reserved in current version).
Indicates the time at which the device uploads the latest operation records (This parameter is used
{ OpStamp }
by the protocol firmware of earlier versions, but is reserved in current version).
Indicates the time at which the device uploads the photos of the verification scene (This
{PhotoStamp }
parameter is used by the protocol firmware of earlier versions, but is reserved in current version).
Indicates the interval after which the device re­accesses the server upon access failure. (unit:
{ErrorDelay }
second)
{Delay } Indicates the interval after which the device accesses the server normally. (unit: second)
Indicates the time point to regularly check and transmit new data (H:M in 24­hour format).
{TransTimes}
Several time points need to be separated with a semicolon (;). This parameter supports a

5
PushSDK Development Guide Ver 1.0

Parameter Meaning
maximum of 10 time points.
{TransInterval } Indicates the new data check and transfer interval. (unit: minute)
For the protocol firmware of earlier versions, return a flag in character array format, for example,
“1111000000”. If “0000000000” is returned, it indicates the Att2008 of an old version. In this
case, you only need to upload the attendance photo flag. For the Att2008 of a new version, set a
flag for attendance photo upload. 0: Automatic upload of this type of data is prohibited. 1:
Automatic upload of this type of data is allowed. Table 1­2 lists the flags of the data types
supported by the standard firmware for automatic upload.
{TransFlag }
For the new version firmware, return a flag in character string format, for example, “TransData
AttLog\tOpLog\tAttPhoto”. The characters are separated by \t. To automatically upload a certain
type of data, set a corresponding flag in character string format. Table 1­2 lists the flags of the
data types supported by the standard firmware for automatic upload.
To automatically upload user and fingerprint information, you must set the automatic upload of
operation logs.
{Realtime }
{Encrypt }
{ServerVer }
Indicates the time at which data is automatically updated. TableName indicates the data table
name which must be consistent with the data table name registered by firmware. Stamp is a fixed
{TableNameStamp } flag. All the timestamps for automatic upload of data tables must be returned to the device. Each
such timestamp is displayed on every single line. For example, ATTLOGStamp=82983982
indicates the timestamp for attendance logs. For details of data table names, see Table 1­3.

Table 1­1

Supported Data Type Description


Character string Character array
AttLog 0 Attendance log.
OpLog 1 Operation log.
AttPhoto 2 Attendance photo
EnrollUser 4 Enroll a new user.
ChgUser 6 Modify user information.
EnrollFP 3 Enroll a new fingerprint.
ChgFP 7 Modify a fingerprint.
FPImag 5 Fingerprint image.

Table 1­2

Table name Function Automatic upload


ATTLOG Attendance log Yes
Yes (including the operation data recorded in operation
OPERLOG Operation log logs, such as, modified user information and enrolled
fingerprints.)
ATTPHOTO Attendance photo Yes

6
PushSDK Development Guide Ver 1.0

Table name Function Automatic upload


SMS Short message No
USER_SMS List of short message service users No
USERINFO User information No
FINGERTMP Fingerprint template No
ATTLOG Attendance log YES
Yes (including the operation data recorded in operation
OPERLOG Operation log logs, such as, modified user information and enrolled
fingerprints.)

Table 1­3

Function implementation on server side: (take python as an example)


Customers can set the device related information in their own systems based on the parameters above and
save their settings in databases.
device = checkDevice(request, response) #Acquire the device information from the database.

if request.method == 'GET':

# Set variables and store the acquired information.

pushverValue = 0.0

if request.REQUEST.has_key('pushver'):

pushverValue = request.REQUEST['pushver'] #Acquire the version number of PushSDK.

attlogStamp = "Stamp" #Set a timestamp for the attendance log.

operlogStamp = "OpStamp" #Set a timestamp for the operation log.

attphotoStamp = "PhotoStamp" #Set a timestamp for an attendance photo upload event.

TransFlag = "0000000000" #Set a transmission flag.

if pushverValue >= 2.0: #Judge whether the PushSDK is a new version. If yes, use the new timestamp.

attlogStamp = "ATTLOGStamp"

operlogStamp = "OPERLOGStamp"

attphotoStamp = "ATTPHOTOStamp"

TransFlag = device.UpdateDB.replace("\\t", "\t")#Read the transmission flag from the database.

resp += "GET OPTION FROM: %s\n" % device.SN #Prepare the character string to be returned to the device,
where SN indicates the device serial number.

resp += "%s=%s\n" % (attlogStamp, device.LogStamp) #Set a timestamp for the attendance log.

resp += "%s=%s\n" % (operlogStamp, device.OpLogStamp or 0) #Set a timestamp for the operation log.

resp += "%s=%s\n" % (attphotoStamp, device.PhotoStamp or 0) #Set a timestamp for a photo upload event.

resp += "ErrorDelay=%d\n" % max(30, settings.MIN_REQ_DELAY) #Set a timestamp for the log.

resp += "Delay=%d\n" % settings.MIN_REQ_DELAY #Set an interval after which the device re­accesses the
server.

7
PushSDK Development Guide Ver 1.0

resp += "TransTimes=%s\n" % device.TransTimes #Set the periodic transmission time.

resp += "TransInterval=%d\n" % max(settings.MIN_TRANSINTERVAL, device.TransInterval)

resp += "TransFlag=%s\n" % device.UpdateDB.replace("\\t", "\t")#Set a transmission flag.

try:

if not (device.TZAdj == None):

resp += "TimeZone=%s\n" % device.TZAdj #Set a time zone.

except:

pass

resp += "Realtime=%s\n" % settings.TRANS_REALTIME #Set whether to transfer new records in realtime.

resp += "Encrypt=%s\n" % settings.ENCRYPT #Set whether to encrypt the to­be­transferred data.

if pushverValue >= 2.0:

resp += "ServerVer=0.0.2 2010­07­22\n" #Only the new version provides the information about server version and
table name timestamp.

response["Content­Length"] = len(resp)

response = HttpResponse(mimetype='text/plain') #Set the httpcontenttype.

response.write(resp)

3.1.2 POST Mode


When a device accesses the server over the interface in POST mode, the device aims to upload attendance
logs, user information, fingerprint information and photos.
The device can upload user data and fingerprint template information and access the administrator’s
operation logs through the following address:
http://IP address of server
/iclock/cdata?SN={SNO}&table={OPERLOG}&Stamp={Stamp}
Parameter Meaning
{SNO} Device serial number.
{OPERLOG} This parameter is used to upload the table name. For details, see Table 1­3.
{LanguageNo} Language version number

Conventions on the uploaded data format:


A record is initialized with an ID to denote the content of this record. The ID is followed by a blank space
and all field values separated by \t. The record is ended with \n. Usually the field values are expressed in
the format of “FieldName=Value”.
Format of uploaded data:
1. User information:
USER PIN={PIN} Name={Name} Passwd={Passwd} Card={Card} Grp={Grp} TZ={TZ}
Parameter Meaning
{PIN} PIN number for attendance purpose

8
PushSDK Development Guide Ver 1.0

{Name} User name


{Passwd} Password
{Card} ID card number
{Grp} Group information
{TZ} This parameter can be left empty. Reserved.

* Format of ID card number: If an ID card number in HEX format is surrounded by square brackets “[“and
“]", this number denotes a complete ID card number; otherwise, it is consistent with the number displayed
on screen after card swiping.
The server acquires user information:
if request.method == 'POST':

raw_Data = request.raw_post_data #Acquire the data uploaded in POST mode from the device.

if settings.ENCRYPT: #Judge whether the data needs to be encrypted or decrypted.

import lzo

rawData = lzo.bufferDecrypt(raw_Data, device.SN)

else:

rawData = raw_Data #Store the raw data into variables.

lines = raw_Data.split("\n") #Split the raw data into lines by line feed. Each line is a piece of user record.

flds = {}; #Create a tuple to store user information.

try:

for line in lines:

ops = line.split(" ", 1) #Split user records by blank space.

for item in ops[1].split("\t"):

index = item.find("=")

if index > 0: flds[item[:index]] = item[index + 1:] #Store the user information into flds.

if ops[0] == "USER": #If the information is user information

employee = getEmployee(pin, device) #Search for the user based on the PIN number. If there is no
match, the user is a new one.

if ename and (ename != employee.EName) or not ename:#If the user name is empty, change of user name is
allowed.

fldNames.append('name')

values.append(ename)

employee.EName = ename

#if passwd and (passwd!=e.Password):

if passwd and (passwd != employee.Password) or not passwd: fldNames.append('password')

values.append(passwd)

employee.Password = passwd

9
PushSDK Development Guide Ver 1.0

if priv != employee.Privilege:

fldNames.append('privilege')

values.append(priv)

employee.Privilege = priv

if card and (cardToNum(card) != employee.Card) or not card: #Set a card number.


fldNames.append('Card')

values.append(cardToNum(card))

employee.Card = cardToNum(card)

if agrp != employee.AccGroup:

fldNames.append('AccGroup')

values.append(agrp)

employee.AccGroup = agrp

if tz != employee.TimeZones:

fldNames.append('TimeZones')

values.append(tz)

employee.TimeZones = tz

employee.save() #Store the user information into a database.

except Exception, e:

print_exc()

response = HttpResponse(mimetype='text/plain') #Set the httpcontenttype.

response.write(“OK”) #Return an upload success message to the device.

return response

2. Fingerprint template information


FP PIN={PIN} FID={FID} Valid={Valid} TMP={TMP}
Parameter Meaning
{PIN} PIN number for attendance purpose
{FID} User’s fingerprint serial number
{Valid} Whether the current fingerprint image is valid.
Fingerprint template encrypted using BASE64 code. For example:
{TMP}
ocoRgZPRN8EwJNQxQTY......

The server acquires fingerprint template information:


if request.method == 'POST':

raw_Data = request.raw_post_data #Acquire the data uploaded from the device in POST mode.

if settings.ENCRYPT: #Judge whether the data needs to be encrypted or decrypted.

import lzo

rawData = lzo.bufferDecrypt(raw_Data, device.SN)

10
PushSDK Development Guide Ver 1.0

else:

rawData = raw_Data #Store the raw data into variables.

lines = raw_Data.split("\n") #Split the raw data into lines by line feed. Each line is a piece of user record.

flds = {}; #Create a tuple to store user information.

try:

for line in lines:

ops = line.split(" ", 1) #Split user records by blank space.

for item in ops[1].split("\t"):

index = item.find("=")

if index > 0: flds[item[:index]] = item[index + 1:] #Store the fingerprint information into flds.

try:

if fp and int(flds["Size"]) == len(fp): #Judge the length consistency. fptemplate =


fptemp.objects.get(UserID=employee.id, FingerID=flds["FID"]) #Acquire the fingerprint template information.

if fp[:100] == fptemplate.Template[:100]:

pass #Template is the same.

else:

sql = "update template set template = '%s', SN='%s', utime='%s' where userid='%s' and fingerid=%s" % (fp,
device.SN, str(datetime.datetime.now())[:19], employee.UserID.id, employee.FingerID) #Update the user fingerprint
template.

except ObjectDoesNotExist: #If the user fingerprint template does not exist

if fp and int(flds["Size"]) == len(fp): #Judge the length consistency. sql = "insert into
template(template, userid, fingerid, SN, utime, valid, DelTag) values('%s', '%s', %s, '%s', '%s', 1, '0')" % (fp, employee.id,
flds["FID"], device.SN, str(datetime.datetime.now())[:19])

cursor.execute(sql) #Import a new user template into the database.

response = HttpResponse(mimetype='text/plain') #Set the httpcontenttype.

response.write(“OK”)

return response

Operation logs

Format:

OPLOG {OPCode}\t{AdminID}\t {DateTime}\t {Object1}\t {Object2}\t {Object3}\t {Object4}

* \t is a tab character.

Example:

OPLOG 5 0 2011­03­10 11:03:10 10 0 0 0

Parameter Meaning
{ OPCode } Operation code
{ AdminID } Administrator ID

11
PushSDK Development Guide Ver 1.0

Parameter Meaning
{ DateTime } Date and time
{ Object1} Operation object 1 **
{ Object2} Operation object 2
{ Object3} Operation object 3
{ Object4} Operation object 4

An operation code can be relevant to different operation objects. For details, see the table below.
Operation code Operation content Parameter description
0 Startup
1 Shutdown
In 1:1 verification mode, “Object 1” indicates the
2 Verification fails.
PIN number of the user.
“Object1” indicates the cause of the alarm. It
supports the following values:
50: Door Close Detected
51: Door Open Detected
3 Alarm 55: Machine Been Broken
53: Out Door Button
54: Door Broken Accidentally
58: Try Invalid Verification
65535: Alarm Cancelled
4 Access the menu.
5 Modify the setting. “Object1” indicates the modified settings.
“Object1” indicates the user ID.
“Object2” indicates the serial number of the
6 Enroll a fingerprint. fingerprint.
“Object3” indicates the length of the fingerprint
template.
7 Enroll a password.
8 Enroll an HID card.
9 Delete a user. “Object1” indicates the user ID.
10 Delete a fingerprint. “Object1” indicates the user ID.
11 Delete a password. “Object1” indicates the user ID.
12 Delete an RF card. “Object1” indicates the user ID.
13 Purge data.
14 Create an MF card.
15 Enroll an MF card.
16 Register an MF card.
17 Cancel the registration of an MF card.
18 Purge the content of an MF card.
19 Move the enrolled data into a card.
20 Copy the data from a card into a device.
21 Set the time.
22 Factory defaults

12
PushSDK Development Guide Ver 1.0

Operation code Operation content Parameter description


23 Delete an entry/exit record.
24 Delete the administrator authority.
Modify the settings of an access control
25
group.
26 Modify the settings of user access control.
27 Modify the access control time.
28 Modify the settings of unlock combinations.
29 Unlock
30 Enroll a new user.
31 Change the fingerprint attributes.
32 Duress alarm

* If an operation code does not correspond to any operation object, the default value of the operation object
is 0.
The server acquires operation logs:
if request.method == 'POST':

raw_Data = request.raw_post_data #Acquire the data uploaded from the device in POST mode.

if settings.ENCRYPT: #Judge whether the data needs to be encrypted or decrypted.

import lzo

rawData = lzo.bufferDecrypt(raw_Data, device.SN)

else:

rawData = raw_Data #Store the raw data into variables.

lines = raw_Data.split("\n") #Split the raw data into lines by line feed. Each line is a piece of user record.

flds = {}; #Create a tuple to store operation logs.

try:

for line in lines:

ops = line.split(" ", 1) #Split operation logs by blank space.

for item in ops[1].split("\t"):

index = item.find("=")

if index > 0: flds[item[:index]] = item[index + 1:] #Store the fingerprint information into flds.

if ops[0] == 'OPLOG':

try:

logtime = datetime.datetime.strptime(flds[2], "%Y­%m­%d %H:%M:%S")

except:

return None

if (datetime.datetime.now() + datetime.timedelta(1, 0, 0)) < logtime: #Set the time to be one day later
than current time. #Judge whether the time is set properly.

13
PushSDK Development Guide Ver 1.0

return None

if device.TZAdj <> None:

logtime = logtime ­ datetime.timedelta(0, device.TZAdj * 60 * 60) + server_time_delta #UTC TIME,


then server time #Convert time according to different time zones.

obj = oplog(SN=device, admin=flds[1], OP=flds[0], OPTime=logtime,

Object=flds[3], Param1=flds[4], Param2=flds[5], Param3=flds[6]) #Create a new operation log object.

obj.save() #Store the operation log into a database.

response = HttpResponse(mimetype='text/plain') #Set the httpcontenttype.

response.write(“OK”)

#Return an upload success message to the device.

Upload the photos of the verification scene

Data format:

PIN={PIN}\nSN={SN}\n size={SIZE}\n CMD={TYPE}\0{ BINARY IMAGE DATA}

Description:

Parameter Meaning
Indicate the unique identification number of an image, and supports two formats:
PIN=DATETIME­U: indicates that the user passes the verification. Where DATETIME is the
{ PIN } user verification time expressed in YYYYMMDDHHNNSS format, and U is the attendance
number of the user.
PIN=DATETIME: indicates that the user fails to pass the verification.
{ SN } Indicates the device serial number.
{ SIZE } Indicates the size of the photo file.
Indicates the photo transmission type. If the value of this parameter is uploadphoto, the
{ TYPE } background uploads the photo. If the value of this parameter is realupload, the device uploads the
photo in realtime.
{ BINARY IMAGE
Indicates the binary data of the onsite JPG image.
DATA }

* \0 indicates the ending character of a string in C language.

The server acquires the uploaded photo:

response = HttpResponse(mimetype='text/plain') #Set the contenttype

device = checkDevice(request, response) #Acquire the related device information based on the request.

if(device == None): return response #If the device does not exist, the following information is returned:

try:

pin = request.REQUEST["PIN"] #Acquire the user ID.

pin = pin.split(".")[0].split("­") #Split the PIN number.

dt = pin[0]

if len(pin) == 2: #Success Picture #If the acquired data is an attendance photo


14
PushSDK Development Guide Ver 1.0

pin = pin[1]

else:

pin = None

fname = getUploadFileName("%s/%s/%s" % (device.SN, dt[:4], dt[4:8]), pin, dt[8:] + ".jpg")


#Acquire the uploaded photo.

try:

os.makedirs(os.path.split(fname)[0]) #Store the photo in the server.

except:

pass #errorLog(request)

f = file(fname, "wb")

d = request.raw_post_data

if "CMD=uploadphoto" in d: d = d.split("CMD=uploadphoto")[1][1:] #Judge the photo type.

if "CMD=realupload" in d: d = d.split("CMD=realupload")[1][1:] #If the photo is uploaded in realtime

f.write(d)

f.close()

#if request.REQUEST.has_key('PhotoStamp'):

if request.REQUEST.has_key('Stamp') and request.REQUEST.has_key('table') and request.REQUEST['table'] ==


'ATTPHOTO': #Judge whether the request path is used to upload the attendance photo.

devlog(SN=device, Cnt=1, OP=u"PICTURE", Object=pin, OpTime=datetime.datetime.now()).save() #Create


a log object and save it.

device.PhotoStamp=request.REQUEST['PhotoStamp'] #Update the timestamp of the device.

device.PhotoStamp = request.REQUEST['Stamp']

saveDeviceStamp(conn.cursor(), device, 'photostamp', device.PhotoStamp)

conn._commit()

except Exception, e:

errorLog(request) #Store the error log.

response.write("OK\n") #Return an upload success message to the device.

Note: After finishing each of the three types of operations above, you must update the corresponding
timestamps on the server. For example, you must update the value related to the attendance log
timestamp, namely, AttLog, after attendance log upload is complete. Similarly, you also need to
update the related timestamps after upload photos and fingerprint images, so as to keep timestamp
consistency between the device and the server, thus ensuring proper data transmission.

15
PushSDK Development Guide Ver 1.0

3.2 Getrequest Interface

3.2.1 GET Mode


Address 1: http://IP address of server/iclock/getrequest?SN={SN}
Interface description:
The commands from the server are not immediately sent to a device, but cached first instead. The device
sends the following request to the server at an interval (usually 30 seconds) to query whether there is any
command from the server. The Getrequest interface is used to return the commands to be executed by a
device.
The server can return several commands at a time (The number of commands must not exceed 200, and the
total number of bytes must not exceed 40 Kbyte. For GPRS transmission, the total number of bytes must
not exceed 10 Kbyte). These commands are separated in different lines. Each line is initialized with “C:”
and ended with “\n”. IDx indicates the command serial number which is used to uniquely identify every
command. CMDx indicates the detailed content of a command. For details of the command sets and
command formats supported by the system, see the relevant contents below.
Each command from the server must correspond to a unique ID in the database to distinguish different
commands.
Parameter Meaning
{ SN } Device serial number

Format of returned commands:

C:ID1:CMD1 \n

C:ID2:CMD2 \n

C:ID3:CMD3 \n

For example:

C:ID1:CHECK \n

C:ID2:CLEAR DATA \n

Function implementation on server side:

response = HttpResponse(mimetype='text/plain')

try:

resp = ""

device = checkDevice(request, response) #Check whether the device exists in the system based on the SN.

if(device == None): return response #If the device does not exist, the following information is returned:

cmds = deviceCmd(device) #Acquire the commands to be executed by the device from the server.

cmds = deviceCmd(device)

if len(cmds) > 0:

16
PushSDK Development Guide Ver 1.0

maxRet = 200 #A maximum of 200 commands can be transmitted.

maxRetSize = 40 * 1024 #A maximum of 40 Kbyte data can be transmitted.

for acmd in cmds:

if acmd.CmdTransTime == None or ((datetime.datetime.now() ­ acmd.CmdTransTime).seconds > 10):

if acmd.CmdContent.find("DATA USER ") == 0 or acmd.CmdContent.find("DATA UPDATE USERINFO")


== 0 or acmd.CmdContent.find("SMS ") >= 0 or acmd.CmdContent.find("WEATHER ") == 0: #Transmit the command
which needs to be decrypted into GB2312 code.

cc = acmd.CmdContent

try:

cc = cc.encode("gb18030")

except:

try:

cc = cc.decode("utf­8").encode("gb18030")

except:

errorLog(request)

else:

cc = str(acmd.CmdContent)

if cc:

#In the case of inconsistency of fingerprint template versions, downloading is not allowed.

devObject = getDevice(acmd.SN_id)

if devObject.FPVersion:

#Acquire the fingerprint template.

if "TMP=" in cc:

tmp = cc.split("TMP=")

if tmp and len(tmp) > 1:tmp = tmp[1]

#Judge the type of the fingerprint template.

FPVersion1 = ""

if tmp :

if tmp[:3] == "oco":FPVersion1 = "9"

else:FPVersion1 = "10"

if FPVersion1 and FPVersion1 != devObject.FPVersion:cc = ""#If the algorithms adopted in the


fingerprint template and the device are inconsistent, downloading is prohibited.

if cc:resp += "C:%d:%s\n" % (acmd.id, cc)

if acmd.CmdTransTime: #If commands failed to be sent last time, 10 less commands are sent this time,
because the transmission failure may result from data oversize.

17
PushSDK Development Guide Ver 1.0

maxRet ­= 10

acmd.CmdTransTime = datetime.datetime.now()

acmd.save()

c = c + 1;

if (c > maxRet) or (len(resp) > maxRetSize): break;

if acmd.CmdContent in ["REBOOT", "RESTART"]: break; #The reboot command can only be the last
command. except Exception, e: #If there is an exception, cast the exception.

resp = "%s" % e

response["Content­Length"] = len(resp)

response.write(resp)

return response

Note: 1. The commands from the server are not instantly sent to the device, so the device may fail to
acquire or execute the commands in realtime. In such a case, the server can send an R­CMD message to the
device over the UDP 4374 port. Upon receiving this message, the device will instantly query commands
from the server. This mechanism greatly improves the response speed of the device, but it applies only to
the cases where the server can be directly connected to the device, for example, within a LAN or the device
has an IP address of a public network.
The server sends an R­CMD command:
import socket

sNotify = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

try:

ip=device.IPAddress

if ip: sNotify.sendto("R­CMD", (ip, 4374))

except:

errorLog()

pass

Command List

Command Meaning
SHELL {CMD_String} Run system commands. {CMD_String} is a system command.
CHECK Check data updates.
CLEAR LOG Purge attendance logs.
CLEAR DATA Purge all data.
CLEAR PHOTO Purge the photos collected on site.
INFO Send the device information to the server.
Set the device options. ITEM indicates the option content. VALUE indicates the
option value. For example:
SET OPTION ITEM=VALUE
SET OPTION IPAddress=192.168.1.225. For details of the options supported by the
devices, see Appendix 1.

18
PushSDK Development Guide Ver 1.0

Command Meaning
REBOOT Reboot
<SUBCMD> includes the following sub­commands: UPDATE tablename value: Add
or modify the data in the tablename list.
For example:
DATA <SUBCMD>
UPDATE FINGERTMP PIN=%d\tFID=%d\tSize=%d\tValid=%d\tTMP=%s
UPDATE USERINFO
%d\tName=%s\tPri=%d\tPasswd=%s\tCard=[ %02x%02x%] \tGrp=%d\tTZ=%d
DELETE tablename key: Delete the data in the tablename list based on the key.
DELETE tablename key
DELETE FINGERTMP PIN=%d\tFID=%d
QUERY tablename key: Query the data in the tablename list based on the key.
QUERY tablename key QUERY USERINFO PIN=%d
If no PIN is specified, upload all the PINs.

The user and fingerprint information is in the same format as the information uploaded by the device.
Address 2: http://IP address of
server/iclock/getrequest?SN={SN}&INFO={object1},{object2},{object3},{object4},{object5}
Interface description:
When a device sends a request to the server for the first time, enrolls users or fingerprints, or records
attendance logs, related information is stored under the URL path (INFO=firmware version number,
number of enrolled users, number of enrolled fingerprints, number of attendance logs, IP address of the
attendance machine, and fingerprint algorithm ID).
Parameter Meaning
{ SN } Device serial number
{object1} Firm version number
{object2} Number of enrolled users
{object3} Number of enrolled fingerprints
{object4} Number of attendance logs
{object5} IP address of the attendance machine
{object6} Fingerprint algorithm ID

Function implementation on server side:


response = HttpResponse(mimetype='text/plain')

try:

resp = ""

device = checkDevice(request, response)

if(device == None): return response

info = request.GET.get("INFO", "") #Version number, number of users, number of fingerprints, and number of
attendance logs.

if info:

info = info.split(",")

if len(info) >= 6: #Fingerprint algorithm ID

19
PushSDK Development Guide Ver 1.0

info =
"FWVersion=%s\nUserCount=%s\nFPCount=%s\nTransactionCount=%s\nIPAddress=%s\nFPVersion=%s\n" %
tuple(info[:6]) #Six parameters

elif len(info) == 5:

info = "FWVersion=%s\nUserCount=%s\nFPCount=%s\nTransactionCount=%s\nIPAddress=%s\n" % tuple(info)

elif len(info) == 4:

info = "FWVersion=%s\nUserCount=%s\nFPCount=%s\nTransactionCount=%s\n" % tuple(info)

else:

info = ""

if info: saveDevInfo(device, info) #Save the device information.

3.3 DeviceCMD Interface


Interface address: http://IP address of server/iclock/devicecmd?SN={SN}
Interface description: After executing the command, the device returns the command execution result
by using the following request.
Format of the POST data received over DeviceCMD interface:
ID={ID}&Return={Rvalue}&CMD={CMD}
Parameter Meaning
{ SN } Device serial number
{ ID } Command serial number in database
{ Rvalue } Return code after command execution
Additional data returned after command execution. When return code is 0, command is executed
{ CMD } successfully. When return code is ­1, command is executed unsuccessfully. For meanings of other
values, see related command description.

Function implementation on server side:


response = HttpResponse(mimetype='text/plain')

resp = ""

device = checkDevice(request, response) #Check whether the device exists.

if(device == None): return response

try:

rd = request.raw_post_data #Acquire the information sent in POST mode.

if settings.ENCRYPT: #Encrypt and decrypt

try:

import lzo

rawData = lzo.bufferDecrypt(rd, device.SN)

except:

20
PushSDK Development Guide Ver 1.0

rawData = rd

else:

rawData = rd

try:

data0 = rawData.decode("gb18030") #Decode the raw data.

except:

data0 = rawData

rets = {}

InfoLines = []

pdata = parsePosts(data0)

# appendFile("%s"%pdata)

for apost in pdata:

id = int(apost["ID"]) #Acquire the device ID.

ret = apost["Return"] #Acquire the return value.

# print id, ret, apost

if apost["CMD"] == "INFO": #If the INFO execution result is returned

saveDevInfo(device, apost['Content'])

rets[id] = ret

elif apost['CMD'] == 'PutFile' and ret > 100 * 1024:#Return the PUTFILE result.

cmdobj = updateCmd(id, ret)

if cmdobj: checkUpgradeFW(cmdobj, request)

elif (apost["CMD"] == "GetFile" or apost["CMD"] == "Shell") and ret > 0:

checkUpLoadFile(request, apost)

rets[id] = ret

else:

rets[id] = ret

if len(rets) > 0:

updateCmds(rets)

resp += "OK"

checkAndSave(device)

try:

nocmd_device = cache.get("nocmd_device")

if nocmd_device:

nocmd_device.remove(device.SN)

cache.set("nocmd_device", nocmd_device)
21
PushSDK Development Guide Ver 1.0

except: pass

except Exception, e:

errorLog(request)

response["Content­Length"] = len(resp)

response.write(resp)

return response

The returned contents vary with commands. Several commands are listed as follows:
Command: CLEAR PHOTO

POST data content: ID=command serial number&Return=return value

Command: INFO

POST data content: ID=command serial number&Return=return value&CMD=INFO\n{option}

{option} contains all the parameters on the devices. For details, see the option configuration table supported by the device.
Options are separated by line feed.

Command: SET OPTION ITEM=VALUE

POST data content: ID=command serial number&Return=0&CMD=SET OPTION

Command: RELOAD OPTIONS

POST data content: ID=command serial number&Return=return value

Command: GetFile FilePath

POST data content: ID=1234 SN=99999 FILENAME=FilePath CMD=GetFile Return=999 Content=ssss

Where ID=1234 is the command ID number, SN=999999 is the device serial number, FILENAME=FilePath is the file
name, Return=999 is the file size (number of bytes), and Content=ssss is the file content. ssss can be text with multiple lines
or be binary data.

The return values include the following:


0: indicates successful registration.

2: indicates the user’s fingerprint exists.

6: Indicates deregistration.

5: indicates the registered fingerprint already exists in the fingerprint library (fingerprint repetition).

4: indicates registration failure due to poor fingerprint quality or inconsistency of fingerprints pressed in three consecutive
times.

­1: indicates parameter error.

­3: indicates access error.

­9: indicates the fingerprint template and the given size do not match (This value is not supported in earlier versions. The
fingerprint template length verification is added in current version.)

­10: indicates the user specified by the PIN does not exist on the equipment. You can only perform related operations after
adding this user by running the DATA UPDATE USERINFO command.

­11: indicates invalid fingerprint template format.

22
PushSDK Development Guide Ver 1.0

­12: indicates invalid fingerprint template.

4 Setting up and Configuring Server Environment (Taking


Python as An Example)

1. Set up the development language environment


The python2.6 and the Django­1.2­beta­1 framework are adopted for the PushSDK development. You
need to install python and django, and add python installation path to the path variable. For example,
assume python is installed at the root directory of partition D (D:\Python26; D:\Python26\Scripts;) and
then add an environment variable, as shown in Figure 1.1. Create a variable named pythonpath and
change its value into the python­support directory (for example, E:\iclocksvr\trunk\python­support).

Figure 1.1 Setting python environment

Figure 1.2 Adding pythonpath

2. Select an editor
The wxPython powered Ulipad 4.0 is adopted in the PushSDK development. When using Ulipad, pay
attention to the following: When environment variables change, the files running on Ulipad will not
load the updated environment variables. You need to exit Ulipad and run it again to load updated
variables. Figure 1.3 shows some of the Ulipad configuration items. The firebug of Firefox browser is
recommended for the page debugging. To debug python codes, you can adopt Eclipse. For details
about how to add iclocksvr system in Eclipse configurations, see the Appendix.

23
PushSDK Development Guide Ver 1.0

Figure 1.3 Python variables in Ulipad

3. Select a database
You can install MySQL5.1, SQLServer2005, oracle10g or PostgreSQL9.0 as required.
You can start the project development after installing a database.
1. Run the django­admin.py startproject mysite command under the project directory to create a
directory named mysite at current directory.
The following files will be generated under the mysite directory:
· __init__.py: indicates a file required for Python to deem this directory as a development kit (that is, a
set of modules).
· manage.py: is a command line tool that allows you to interact with the Django project in many ways.
· settings.py: contains the configurations of the Django project.
· urls.py: indicates the URL statement of the Django project, that is, the content list of the sites
supported by Django.
Django contains a built­in lightweight Web server for use during site development. This Web server is
offered for you to develop sites quickly. That is, before preparing for the product release, you do not
have to perform product­level Web server (for example, Apache) configurations. This Web server
monitors code changes and automatically re­loads them once detecting any code change, which helps
you quickly modify projects without reboot.
2. Open the mysite directory and run the python manage.py runserver command. You can see the
following message:
· 1
Validating models...
0 errors found.

24
PushSDK Development Guide Ver 1.0

Django version 1.0, using settings 'mysite.settings'


Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL­C.
3. Add the iclock directory.
Create a directory named iclcokc under the mysite directory to store iclock­related modules.
4. Set the URL mapping.
You can open the url.py. file to set the URL under the project directory, for example, setting the
mapping for the Iclock/cdata request.

Then you can compile handling functions. The communication­related handling functions are provided by
the devview module as shown in the preceding figure.
The functions Cdata, getreq, devpost and postPhoto are used to handle contents in an HTTP request. For
details, see preceding handling procedures.

5 Appendix 1 List of Supported Configuration Options

Option Meaning
IPAddress Indicates The IP address of the equipment.
NetMask Indicates the subnet mask of the equipment.
GATEIPAddress Indicates the gateway address of the equipment
VOLUME Indicates the volume.
Indicates the Ethernet MAC address. The MAC address format in C language:
MAC
"%02X:%02X:%02X:%02X:%02X:%02X".
CardKey Indicates the Mifare card password.
DeviceID Indicates the device DI.
LockOn Indicates the unlocking duration.
AlarmAttLog Indicates the attendance alarm.
AlarmReRec Indicates the minimum interval between check­ins.
RS232BaudRate Indicates the baud rate of the RS­232/RS­485 communication.
AutoPowerOff Indicates the automatic power­off time. The automatic power­off time format: Hour × 256 +

25
PushSDK Development Guide Ver 1.0

Option Meaning
Minutes. This format is adopted for all the following items that involve time setting.
AutoPowerOn Indicates the automatic power­on time.
AutoPowerSuspend Indicates the automatic standby time.
AutoAlarm1–AutoAlarm50 Indicates 50 automatic alarms.
IdlePower Indicates the idle setting.
IdleMinute Indicates the idle time (unit: minute).
RS232On Indicates whether to enable the RS­232 connection.
RS485On Indicates whether to enable the RS­485 connection.
UnlockPerson Indicates the number of persons allowed to unlock in simple access control mode.
OnlyPINCard Indicates this parameter is used only when the Mifare card ID is read.
AlarmReRec Indicates the minimum interval between check­ins.
RS232BaudRate Indicates the baud rate of the RS­232/RS­485 communication.
Indicates the automatic power­off time. The automatic power­off time format: Hour × 256 +
AutoPowerOff Minutes.
This format is adopted for all the following items that involve time setting.
AutoPowerOn Indicates the automatic power­on time.
AutoPowerSuspend Indicates the automatic standby time.
AutoAlarm1–AutoAlarm50 Indicates 50 automatic alarms.
IdlePower Indicates the idle setting.
IdleMinute Indicates the idle time (unit: minute).
RS232On Indicates whether to enable the RS­232 connection.
RS485On Indicates whether to enable the RS­485 connection.
UnlockPerson Indicates the number of persons allowed to unlock in simple access control mode.
OnlyPINCard Indicates this parameter is used only when the Mifare card ID is read.
HiSpeedNet Indicates the network rate.
Must1To1 Indicates whether 1:1 fingerprint verification is allowed.
Indicates the unlocking time. An alarm signal will be generated if the door is not closed
ODD
within the specified period.
DSM
AADelay
DUHK Indicates whether to enable the duress alarm function.
DU11 Indicates duress alarm in 1:1 fingerprint verification mode.
DU1N Indicates duress alarm in 1:N fingerprint verification mode.
DUPWD Indicates duress alarm in password verification mode.
DUAD Indicates alarm delay time (Unit: Second) after the duress alarm is generated.
LockPWRButton Indicates the power­off locking button.
Indicates whether to send a broadcast message for other hosts on the network to know its
SUN
presence at equipment start­up.
I1NFrom Indicates the start user number in 1:N fingerprint verification mode.
I1NTo Indicates the stop user number in 1:N fingerprint verification mode.
I1H Indicates whether to enable the 1: H function.
I1G Indicates whether to enable the 1: G function.
KeyPadBeep Indicates whether to beep sound for every keystroke.
WorkCode Indicates whether to enable the WorkCode function.
26

You might also like