-
Notifications
You must be signed in to change notification settings - Fork 7
/
Pyfingerprint.py
1396 lines (996 loc) · 45.6 KB
/
Pyfingerprint.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
PyFingerprint
Copyright (C) 2015 Bastian Raschke <[email protected]>
All rights reserved.
LED functionalities added by Swe Geng 2018
"""
import os
import struct
import serial
from PIL import Image
## Baotou start byte
FINGERPRINT_STARTCODE = 0xEF01
## Packet identification
##
FINGERPRINT_COMMANDPACKET = 0x01
FINGERPRINT_ACKPACKET = 0x07
FINGERPRINT_DATAPACKET = 0x02
FINGERPRINT_ENDDATAPACKET = 0x08
## Instruction codes
##
FINGERPRINT_VERIFYPASSWORD = 0x13
FINGERPRINT_SETPASSWORD = 0x12
FINGERPRINT_SETADDRESS = 0x15
FINGERPRINT_SETSYSTEMPARAMETER = 0x0E
FINGERPRINT_GETSYSTEMPARAMETERS = 0x0F
FINGERPRINT_TEMPLATEINDEX = 0x1F
FINGERPRINT_TEMPLATECOUNT = 0x1D
FINGERPRINT_READIMAGE = 0x01
## Note: The documentation mean upload to host computer.
FINGERPRINT_DOWNLOADIMAGE = 0x0A
FINGERPRINT_CONVERTIMAGE = 0x02
FINGERPRINT_CREATETEMPLATE = 0x05
FINGERPRINT_STORETEMPLATE = 0x06
FINGERPRINT_SEARCHTEMPLATE = 0x04
FINGERPRINT_LOADTEMPLATE = 0x07
FINGERPRINT_DELETETEMPLATE = 0x0C
FINGERPRINT_CLEARDATABASE = 0x0D
FINGERPRINT_GENERATERANDOMNUMBER = 0x14
FINGERPRINT_COMPARECHARACTERISTICS = 0x03
## Note: The documentation mean download from host computer.
FINGERPRINT_UPLOADCHARACTERISTICS = 0x09
## Note: The documentation mean upload to host computer.
FINGERPRINT_DOWNLOADCHARACTERISTICS = 0x08
## LED controls
FINGERPRINT_LEDON = 0x50
FINGERPRINT_LEDOFF = 0x51
## Packet reply confirmations
##
FINGERPRINT_OK = 0x00
FINGERPRINT_ERROR_COMMUNICATION = 0x01
FINGERPRINT_ERROR_WRONGPASSWORD = 0x13
FINGERPRINT_ERROR_INVALIDREGISTER = 0x1A
FINGERPRINT_ERROR_NOFINGER = 0x02
FINGERPRINT_ERROR_READIMAGE = 0x03
FINGERPRINT_ERROR_MESSYIMAGE = 0x06
FINGERPRINT_ERROR_FEWFEATUREPOINTS = 0x07
FINGERPRINT_ERROR_INVALIDIMAGE = 0x15
FINGERPRINT_ERROR_CHARACTERISTICSMISMATCH = 0x0A
FINGERPRINT_ERROR_INVALIDPOSITION = 0x0B
FINGERPRINT_ERROR_FLASH = 0x18
FINGERPRINT_ERROR_NOTEMPLATEFOUND = 0x09
FINGERPRINT_ERROR_LOADTEMPLATE = 0x0C
FINGERPRINT_ERROR_DELETETEMPLATE = 0x10
FINGERPRINT_ERROR_CLEARDATABASE = 0x11
FINGERPRINT_ERROR_NOTMATCHING = 0x08
FINGERPRINT_ERROR_DOWNLOADIMAGE = 0x0F
FINGERPRINT_ERROR_DOWNLOADCHARACTERISTICS = 0x0D
## Unknown error codes
##
FINGERPRINT_ADDRCODE = 0x20
FINGERPRINT_PASSVERIFY = 0x21
FINGERPRINT_PACKETRESPONSEFAIL = 0x0E
FINGERPRINT_ERROR_TIMEOUT = 0xFF
FINGERPRINT_ERROR_BADPACKET = 0xFE
class PyFingerprint(object):
"""
A python written library for the ZhianTec ZFM-20 fingerprint sensor.
@attribute integer(4 bytes) __address
Address to connect to sensor.
@attribute integer(4 bytes) __password
Password to connect to sensor.
@attribute Serial __serial
UART serial connection via PySerial.
"""
__address = None
__password = None
__serial = None
def __init__(self, port='/dev/ttyUSB0', baudRate=57600, address=0xFFFFFFFF, password=0x00000000):
"""
Constructor
@param string port
@param integer baudRate
@param integer(4 bytes) address
@param integer(4 bytes) password
"""
if (os.path.exists(port) == False):
raise ValueError('The fingerprint sensor port "' + port + '" was not found!')
if (baudRate < 9600 or baudRate > 115200 or baudRate % 9600 != 0):
raise ValueError('The given baudrate is invalid!')
if (address < 0x00000000 or address > 0xFFFFFFFF):
raise ValueError('The given address is invalid!')
if (password < 0x00000000 or password > 0xFFFFFFFF):
raise ValueError('The given password is invalid!')
self.__address = address
self.__password = password
## Initialize PySerial connection
self.__serial = serial.Serial(port=port, baudrate=baudRate, bytesize=serial.EIGHTBITS, timeout=2)
if (self.__serial.isOpen() == True):
self.__serial.close()
self.__serial.open()
def __del__(self):
"""
Destructor
"""
## Close connection if still established
if (self.__serial is not None and self.__serial.isOpen() == True):
self.__serial.close()
def __rightShift(self, n, x):
"""
Shift a byte.
@param integer n
@param integer x
@return integer
"""
return (n >> x & 0xFF)
def __leftShift(self, n, x):
"""
Shift a byte.
@param integer n
@param integer x
@return integer
"""
return (n << x)
def __bitAtPosition(self, n, p):
"""
Get the bit of n at position p.
@param integer n
@param integer p
@return integer
"""
## A bitshift 2 ^ p
twoP = 1 << p
## Binary AND composition (on both positions must be a 1)
## This can only happen at position p
result = n & twoP
return int(result > 0)
def __byteToString(self, byte):
"""
Converts a byte to string.
@param byte byte
@return string
"""
return struct.pack('@B', byte)
def __stringToByte(self, string):
"""
Convert one "string" byte (like '0xFF') to real integer byte (0xFF).
@param string string
@return byte
"""
return struct.unpack('@B', string)[0]
def __writePacket(self, packetType, packetPayload):
"""
Send a packet to fingerprint sensor.
@param integer(1 byte) packetType
@param tuple packetPayload
@return void
"""
## Write header (one byte at once)
self.__serial.write(self.__byteToString(self.__rightShift(FINGERPRINT_STARTCODE, 8)))
self.__serial.write(self.__byteToString(self.__rightShift(FINGERPRINT_STARTCODE, 0)))
self.__serial.write(self.__byteToString(self.__rightShift(self.__address, 24)))
self.__serial.write(self.__byteToString(self.__rightShift(self.__address, 16)))
self.__serial.write(self.__byteToString(self.__rightShift(self.__address, 8)))
self.__serial.write(self.__byteToString(self.__rightShift(self.__address, 0)))
self.__serial.write(self.__byteToString(packetType))
## The packet length = package payload (n bytes) + checksum (2 bytes)
packetLength = len(packetPayload) + 2
self.__serial.write(self.__byteToString(self.__rightShift(packetLength, 8)))
self.__serial.write(self.__byteToString(self.__rightShift(packetLength, 0)))
## The packet checksum = packet type (1 byte) + packet length (2 bytes) + payload (n bytes)
packetChecksum = packetType + self.__rightShift(packetLength, 8) + self.__rightShift(packetLength, 0)
## Write payload
for i in range(0, len(packetPayload)):
self.__serial.write(self.__byteToString(packetPayload[i]))
packetChecksum += packetPayload[i]
## Write checksum (2 bytes)
self.__serial.write(self.__byteToString(self.__rightShift(packetChecksum, 8)))
self.__serial.write(self.__byteToString(self.__rightShift(packetChecksum, 0)))
def __readPacket(self):
"""
Receive a packet from fingerprint sensor.
Return a tuple that contain the following information:
0: integer(1 byte) The packet type.
1: integer(n bytes) The packet payload.
@return tuple
"""
receivedPacketData = []
i = 0
while (True):
## Read one byte
receivedFragment = self.__serial.read()
if (len(receivedFragment) != 0):
receivedFragment = self.__stringToByte(receivedFragment)
## print 'Received packet fragment = ' + hex(receivedFragment)
## Insert byte if packet seems valid
receivedPacketData.insert(i, receivedFragment)
i += 1
## Packet could be complete (the minimal packet size is 12 bytes)
if (i >= 12):
## Check the packet header
if (receivedPacketData[0] != self.__rightShift(FINGERPRINT_STARTCODE, 8) or receivedPacketData[
1] != self.__rightShift(FINGERPRINT_STARTCODE, 0)):
raise Exception('The received packet do not begin with a valid header!')
## Calculate packet payload length (combine the 2 length bytes)
packetPayloadLength = self.__leftShift(receivedPacketData[7], 8)
packetPayloadLength = packetPayloadLength | self.__leftShift(receivedPacketData[8], 0)
## Check if the packet is still fully received
## Condition: index counter < packet payload length + packet frame
if (i < packetPayloadLength + 9):
continue
## At this point the packet should be fully received
packetType = receivedPacketData[6]
## Calculate checksum:
## checksum = packet type (1 byte) + packet length (2 bytes) + packet payload (n bytes)
packetChecksum = packetType + receivedPacketData[7] + receivedPacketData[8]
packetPayload = []
## Collect package payload (ignore the last 2 checksum bytes)
for j in range(9, 9 + packetPayloadLength - 2):
packetPayload.append(receivedPacketData[j])
packetChecksum += receivedPacketData[j]
## Calculate full checksum of the 2 separate checksum bytes
receivedChecksum = self.__leftShift(receivedPacketData[i - 2], 8)
receivedChecksum = receivedChecksum | self.__leftShift(receivedPacketData[i - 1], 0)
if (receivedChecksum != packetChecksum):
raise Exception('The received packet is corrupted (the checksum is wrong)!')
return (packetType, packetPayload)
def verifyPassword(self):
"""
Verify password of the fingerprint sensor.
@return boolean
"""
packetPayload = (
FINGERPRINT_VERIFYPASSWORD,
self.__rightShift(self.__password, 24),
self.__rightShift(self.__password, 16),
self.__rightShift(self.__password, 8),
self.__rightShift(self.__password, 0),
)
self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)
receivedPacket = self.__readPacket()
receivedPacketType = receivedPacket[0]
receivedPacketPayload = receivedPacket[1]
if (receivedPacketType != FINGERPRINT_ACKPACKET):
raise Exception('The received packet is no ack packet!')
## DEBUG: Sensor password is correct
if (receivedPacketPayload[0] == FINGERPRINT_OK):
return True
elif (receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION):
raise Exception('Communication error')
elif (receivedPacketPayload[0] == FINGERPRINT_ADDRCODE):
raise Exception('The address is wrong')
## DEBUG: Sensor password is wrong
elif (receivedPacketPayload[0] == FINGERPRINT_ERROR_WRONGPASSWORD):
return False
else:
raise Exception('Unknown error ' + hex(receivedPacketPayload[0]))
def setPassword(self, newPassword):
"""
Set the password of the sensor.
@param integer(4 bytes) newPassword
@return boolean
"""
## Validate the password (maximum 4 bytes)
if (newPassword < 0x00000000 or newPassword > 0xFFFFFFFF):
raise ValueError('The given password is invalid!')
packetPayload = (
FINGERPRINT_SETPASSWORD,
self.__rightShift(newPassword, 24),
self.__rightShift(newPassword, 16),
self.__rightShift(newPassword, 8),
self.__rightShift(newPassword, 0),
)
self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)
receivedPacket = self.__readPacket()
receivedPacketType = receivedPacket[0]
receivedPacketPayload = receivedPacket[1]
if (receivedPacketType != FINGERPRINT_ACKPACKET):
raise Exception('The received packet is no ack packet!')
## DEBUG: Password set was successful
if (receivedPacketPayload[0] == FINGERPRINT_OK):
self.__password = newPassword
return True
elif (receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION):
raise Exception('Communication error')
else:
raise Exception('Unknown error ' + hex(receivedPacketPayload[0]))
def setAddress(self, newAddress):
"""
Set the module address of the sensor.
@param integer(4 bytes) newAddress
@return boolean
"""
## Validate the address (maximum 4 bytes)
if (newAddress < 0x00000000 or newAddress > 0xFFFFFFFF):
raise ValueError('The given address is invalid!')
packetPayload = (
FINGERPRINT_SETADDRESS,
self.__rightShift(newAddress, 24),
self.__rightShift(newAddress, 16),
self.__rightShift(newAddress, 8),
self.__rightShift(newAddress, 0),
)
self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)
receivedPacket = self.__readPacket()
receivedPacketType = receivedPacket[0]
receivedPacketPayload = receivedPacket[1]
if (receivedPacketType != FINGERPRINT_ACKPACKET):
raise Exception('The received packet is no ack packet!')
## DEBUG: Address set was successful
if (receivedPacketPayload[0] == FINGERPRINT_OK):
self.__address = newAddress
return True
elif (receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION):
raise Exception('Communication error')
else:
raise Exception('Unknown error ' + hex(receivedPacketPayload[0]))
def setSystemParameter(self, parameterNumber, parameterValue):
"""
Set a system parameter of the sensor.
@param integer(1 byte) parameterNumber
@param integer(1 byte) parameterValue
@return boolean
"""
## Validate the baudrate parameter
if (parameterNumber == 4):
if (parameterValue < 1 or parameterValue > 12):
raise ValueError('The given baudrate parameter is invalid!')
## Validate the security level parameter
elif (parameterNumber == 5):
if (parameterValue < 1 or parameterValue > 5):
raise ValueError('The given security level parameter is invalid!')
## Validate the package length parameter
elif (parameterNumber == 6):
if (parameterValue < 0 or parameterValue > 3):
raise ValueError('The given package length parameter is invalid!')
## The parameter number is not valid
else:
raise ValueError('The given parameter number is invalid!')
packetPayload = (
FINGERPRINT_SETSYSTEMPARAMETER,
parameterNumber,
parameterValue,
)
self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)
receivedPacket = self.__readPacket()
receivedPacketType = receivedPacket[0]
receivedPacketPayload = receivedPacket[1]
if (receivedPacketType != FINGERPRINT_ACKPACKET):
raise Exception('The received packet is no ack packet!')
## DEBUG: Parameter set was successful
if (receivedPacketPayload[0] == FINGERPRINT_OK):
return True
elif (receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION):
raise Exception('Communication error')
elif (receivedPacketPayload[0] == FINGERPRINT_ERROR_INVALIDREGISTER):
raise Exception('Invalid register number')
else:
raise Exception('Unknown error ' + hex(receivedPacketPayload[0]))
def getSystemParameters(self):
"""
Get all available system information of the sensor.
Return a tuple that contain the following information:
0: integer(2 bytes) The status register.
1: integer(2 bytes) The system id.
2: integer(2 bytes) The storage capacity.
3: integer(2 bytes) The security level.
4: integer(4 bytes) The sensor address.
5: integer(2 bytes) The packet length.
6: integer(2 bytes) The baudrate.
@return tuple
"""
packetPayload = (
FINGERPRINT_GETSYSTEMPARAMETERS,
)
self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)
receivedPacket = self.__readPacket()
receivedPacketType = receivedPacket[0]
receivedPacketPayload = receivedPacket[1]
if (receivedPacketType != FINGERPRINT_ACKPACKET):
raise Exception('The received packet is no ack packet!')
## DEBUG: Read successfully
if (receivedPacketPayload[0] == FINGERPRINT_OK):
statusRegister = self.__leftShift(receivedPacketPayload[1], 8) | self.__leftShift(receivedPacketPayload[2],
0)
systemID = self.__leftShift(receivedPacketPayload[3], 8) | self.__leftShift(receivedPacketPayload[4], 0)
storageCapacity = self.__leftShift(receivedPacketPayload[5], 8) | self.__leftShift(receivedPacketPayload[6],
0)
securityLevel = self.__leftShift(receivedPacketPayload[7], 8) | self.__leftShift(receivedPacketPayload[8],
0)
deviceAddress = ((receivedPacketPayload[9] << 8 | receivedPacketPayload[10]) << 8 | receivedPacketPayload[
11]) << 8 | receivedPacketPayload[12] ## TODO
packetLength = self.__leftShift(receivedPacketPayload[13], 8) | self.__leftShift(receivedPacketPayload[14],
0)
baudRate = self.__leftShift(receivedPacketPayload[15], 8) | self.__leftShift(receivedPacketPayload[16], 0)
return (statusRegister, systemID, storageCapacity, securityLevel, deviceAddress, packetLength, baudRate)
elif (receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION):
raise Exception('Communication error')
else:
raise Exception('Unknown error ' + hex(receivedPacketPayload[0]))
def getTemplateIndex(self, page):
"""
Get a list of the template positions with usage indicator.
@param integer(1 byte) page
@return list
"""
if (page < 0 or page > 3):
raise ValueError('The given index page is invalid!')
packetPayload = (
FINGERPRINT_TEMPLATEINDEX,
page,
)
self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)
receivedPacket = self.__readPacket()
receivedPacketType = receivedPacket[0]
receivedPacketPayload = receivedPacket[1]
if (receivedPacketType != FINGERPRINT_ACKPACKET):
raise Exception('The received packet is no ack packet!')
## DEBUG: Read index table successfully
if (receivedPacketPayload[0] == FINGERPRINT_OK):
templateIndex = []
## Contain the table page bytes (skip the first status byte)
pageElements = receivedPacketPayload[1:]
for pageElement in pageElements:
## Test every bit (bit = template position is used indicator) of a table page element
for p in range(0, 7 + 1):
positionIsUsed = (self.__bitAtPosition(pageElement, p) == 1)
templateIndex.append(positionIsUsed)
return templateIndex
elif (receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION):
raise Exception('Communication error')
else:
raise Exception('Unknown error ' + hex(receivedPacketPayload[0]))
def getTemplateCount(self):
"""
Get the number of stored templates.
@return integer(2 bytes)
"""
packetPayload = (
FINGERPRINT_TEMPLATECOUNT,
)
self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)
receivedPacket = self.__readPacket()
receivedPacketType = receivedPacket[0]
receivedPacketPayload = receivedPacket[1]
if (receivedPacketType != FINGERPRINT_ACKPACKET):
raise Exception('The received packet is no ack packet!')
## DEBUG: Read successfully
if (receivedPacketPayload[0] == FINGERPRINT_OK):
templateCount = self.__leftShift(receivedPacketPayload[1], 8)
templateCount = templateCount | self.__leftShift(receivedPacketPayload[2], 0)
return templateCount
elif (receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION):
raise Exception('Communication error')
else:
raise Exception('Unknown error ' + hex(receivedPacketPayload[0]))
def readImage(self):
"""
Read the image of a finger and stores it in ImageBuffer.
@return boolean
"""
packetPayload = (
FINGERPRINT_READIMAGE,
)
self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)
receivedPacket = self.__readPacket()
receivedPacketType = receivedPacket[0]
receivedPacketPayload = receivedPacket[1]
if (receivedPacketType != FINGERPRINT_ACKPACKET):
raise Exception('The received packet is no ack packet!')
## DEBUG: Image read successful
if (receivedPacketPayload[0] == FINGERPRINT_OK):
return True
elif (receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION):
raise Exception('Communication error')
## DEBUG: No finger found
elif (receivedPacketPayload[0] == FINGERPRINT_ERROR_NOFINGER):
return False
elif (receivedPacketPayload[0] == FINGERPRINT_ERROR_READIMAGE):
raise Exception('Could not read image')
else:
raise Exception('Unknown error ' + hex(receivedPacketPayload[0]))
## TODO:
## Implementation of uploadImage()
def downloadImage(self, imageDestination):
"""
Download the image of a finger to host computer.
@param string imageDestination
@return void
"""
destinationDirectory = os.path.dirname(imageDestination)
if (os.access(destinationDirectory, os.W_OK) == False):
raise ValueError('The given destination directory "' + destinationDirectory + '" is not writable!')
packetPayload = (
FINGERPRINT_DOWNLOADIMAGE,
)
self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)
## Get first reply packet
receivedPacket = self.__readPacket()
receivedPacketType = receivedPacket[0]
receivedPacketPayload = receivedPacket[1]
if (receivedPacketType != FINGERPRINT_ACKPACKET):
raise Exception('The received packet is no ack packet!')
## DEBUG: The sensor will sent follow-up packets
if (receivedPacketPayload[0] == FINGERPRINT_OK):
pass
elif (receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION):
raise Exception('Communication error')
elif (receivedPacketPayload[0] == FINGERPRINT_ERROR_DOWNLOADIMAGE):
raise Exception('Could not download image')
else:
raise Exception('Unknown error ' + hex(receivedPacketPayload[0]))
## Initialize image library
resultImage = Image.new('L', (256, 288), 'white')
pixels = resultImage.load()
## Y coordinate of current pixel
line = 0
## Get follow-up data packets until the last data packet is received
while (receivedPacketType != FINGERPRINT_ENDDATAPACKET):
receivedPacket = self.__readPacket()
receivedPacketType = receivedPacket[0]
receivedPacketPayload = receivedPacket[1]
if (receivedPacketType != FINGERPRINT_DATAPACKET and receivedPacketType != FINGERPRINT_ENDDATAPACKET):
raise Exception('The received packet is no data packet!')
## X coordinate of current pixel
x = 0
for i in range(0, len(receivedPacketPayload)):
## Thanks to Danylo Esterman <[email protected]> for the "multiple with 17" improvement:
## Draw left 4 Bits one byte of package
pixels[x, line] = (receivedPacketPayload[i] >> 4) * 17
x = x + 1
## Draw right 4 Bits one byte of package
pixels[x, line] = (receivedPacketPayload[i] & 0b00001111) * 17
x = x + 1
line = line + 1
resultImage.save(imageDestination)
def convertImage(self, charBufferNumber=0x01):
"""
Convert the image in ImageBuffer to finger characteristics and store in CharBuffer1 or CharBuffer2.
@param integer(1 byte) charBufferNumber
@return boolean
"""
if (charBufferNumber != 0x01 and charBufferNumber != 0x02):
raise ValueError('The given charbuffer number is invalid!')
packetPayload = (
FINGERPRINT_CONVERTIMAGE,
charBufferNumber,
)
self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)
receivedPacket = self.__readPacket()
receivedPacketType = receivedPacket[0]
receivedPacketPayload = receivedPacket[1]
if (receivedPacketType != FINGERPRINT_ACKPACKET):
raise Exception('The received packet is no ack packet!')
## DEBUG: Image converted
if (receivedPacketPayload[0] == FINGERPRINT_OK):
return True
elif (receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION):
raise Exception('Communication error')
elif (receivedPacketPayload[0] == FINGERPRINT_ERROR_MESSYIMAGE):
raise Exception('The image is too messy')
elif (receivedPacketPayload[0] == FINGERPRINT_ERROR_FEWFEATUREPOINTS):
raise Exception('The image contains too few feature points')
elif (receivedPacketPayload[0] == FINGERPRINT_ERROR_INVALIDIMAGE):
raise Exception('The image is invalid')
else:
raise Exception('Unknown error ' + hex(receivedPacketPayload[0]))
def createTemplate(self):
"""
Combine the characteristics which are stored in CharBuffer1 and CharBuffer2 to a template.
The created template will be stored again in CharBuffer1 and CharBuffer2 as the same.
@return boolean
"""
packetPayload = (
FINGERPRINT_CREATETEMPLATE,
)
self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)
receivedPacket = self.__readPacket()
receivedPacketType = receivedPacket[0]
receivedPacketPayload = receivedPacket[1]
if (receivedPacketType != FINGERPRINT_ACKPACKET):
raise Exception('The received packet is no ack packet!')
## DEBUG: Template created successful
if (receivedPacketPayload[0] == FINGERPRINT_OK):
return True
elif (receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION):
raise Exception('Communication error')
## DEBUG: The characteristics not matching
elif (receivedPacketPayload[0] == FINGERPRINT_ERROR_CHARACTERISTICSMISMATCH):
return False
else:
raise Exception('Unknown error ' + hex(receivedPacketPayload[0]))
def storeTemplate(self, positionNumber=-1, charBufferNumber=0x01):
"""
Save a template from the specified CharBuffer to the given position number.
@param integer(2 bytes) positionNumber
@param integer(1 byte) charBufferNumber
@return integer
"""
## Find a free index
if (positionNumber == -1):
for page in range(0, 4):
## Free index found?
if (positionNumber >= 0):
break
templateIndex = self.getTemplateIndex(page)
for i in range(0, len(templateIndex)):
## Index not used?
if (templateIndex[i] == False):
positionNumber = (len(templateIndex) * page) + i
break
if (positionNumber < 0x0000 or positionNumber >= self.getStorageCapacity()):
raise ValueError('The given position number is invalid!')
if (charBufferNumber != 0x01 and charBufferNumber != 0x02):
raise ValueError('The given charbuffer number is invalid!')
packetPayload = (
FINGERPRINT_STORETEMPLATE,
charBufferNumber,
self.__rightShift(positionNumber, 8),
self.__rightShift(positionNumber, 0),
)
self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)
receivedPacket = self.__readPacket()
receivedPacketType = receivedPacket[0]
receivedPacketPayload = receivedPacket[1]
if (receivedPacketType != FINGERPRINT_ACKPACKET):
raise Exception('The received packet is no ack packet!')
## DEBUG: Template stored successful
if (receivedPacketPayload[0] == FINGERPRINT_OK):
return positionNumber
elif (receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION):
raise Exception('Communication error')
elif (receivedPacketPayload[0] == FINGERPRINT_ERROR_INVALIDPOSITION):
raise Exception('Could not store template in that position')
elif (receivedPacketPayload[0] == FINGERPRINT_ERROR_FLASH):
raise Exception('Error writing to flash')
else:
raise Exception('Unknown error ' + hex(receivedPacketPayload[0]))
def searchTemplate(self):
"""
Search the finger characteristics in CharBuffer in database.
Return a tuple that contain the following information:
0: integer(2 bytes) The position number of found template.
1: integer(2 bytes) The accuracy score of found template.
@return tuple
"""
## CharBuffer1 and CharBuffer2 are the same in this case
charBufferNumber = 0x01
## Begin search at index 0
positionStart = 0x0000
templatesCount = self.getStorageCapacity()
packetPayload = (
FINGERPRINT_SEARCHTEMPLATE,
charBufferNumber,
self.__rightShift(positionStart, 8),
self.__rightShift(positionStart, 0),
self.__rightShift(templatesCount, 8),
self.__rightShift(templatesCount, 0),
)
self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)
receivedPacket = self.__readPacket()
receivedPacketType = receivedPacket[0]
receivedPacketPayload = receivedPacket[1]
if (receivedPacketType != FINGERPRINT_ACKPACKET):
raise Exception('The received packet is no ack packet!')
## DEBUG: Found template
if (receivedPacketPayload[0] == FINGERPRINT_OK):
positionNumber = self.__leftShift(receivedPacketPayload[1], 8)
positionNumber = positionNumber | self.__leftShift(receivedPacketPayload[2], 0)
accuracyScore = self.__leftShift(receivedPacketPayload[3], 8)
accuracyScore = accuracyScore | self.__leftShift(receivedPacketPayload[4], 0)
return (positionNumber, accuracyScore)
elif (receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION):
raise Exception('Communication error')
## DEBUG: Did not found a matching template
elif (receivedPacketPayload[0] == FINGERPRINT_ERROR_NOTEMPLATEFOUND):
return (-1, -1)
else:
raise Exception('Unknown error ' + hex(receivedPacketPayload[0]))
def loadTemplate(self, positionNumber, charBufferNumber=0x01):
"""
Load an existing template specified by position number to specified CharBuffer.
@param integer(2 bytes) positionNumber
@param integer(1 byte) charBufferNumber
@return boolean
"""
if (positionNumber < 0x0000 or positionNumber >= self.getStorageCapacity()):
raise ValueError('The given position number is invalid!')
if (charBufferNumber != 0x01 and charBufferNumber != 0x02):
raise ValueError('The given charbuffer number is invalid!')
packetPayload = (
FINGERPRINT_LOADTEMPLATE,
charBufferNumber,
self.__rightShift(positionNumber, 8),
self.__rightShift(positionNumber, 0),
)
self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)
receivedPacket = self.__readPacket()
receivedPacketType = receivedPacket[0]
receivedPacketPayload = receivedPacket[1]
if (receivedPacketType != FINGERPRINT_ACKPACKET):
raise Exception('The received packet is no ack packet!')
## DEBUG: Template loaded successful
if (receivedPacketPayload[0] == FINGERPRINT_OK):