forked from tschuehly/music-cards
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Reader.py
81 lines (67 loc) · 2.15 KB
/
Reader.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
import sys
import nfc
import nfc.ndef
class Reader:
def startup(self, targets):
print "waiting for new NFC tags..."
return targets
def released(self, tag):
print("released:")
return tag
def connected_read(self, tag):
if not tag.ndef or not tag.ndef.is_writeable:
print("not a writeable nfc tag")
return False
print 'data:', nfc.ndef.TextRecord(tag.ndef.message[0]).text
def connected_write(self, tag):
if not tag.ndef or not tag.ndef.is_writeable:
print("not a writeable nfc tag")
return False
try:
print 'old data:', nfc.ndef.TextRecord(tag.ndef.message[0]).text
except ValueError:
print "this NFC is NEW"
record = nfc.ndef.TextRecord(self.text)
new_message = nfc.ndef.Message(record)
if len(str(new_message)) > tag.ndef.capacity:
print "too long message"
return False
if tag.ndef.message == new_message:
print "already same record"
return True
tag.ndef.message = new_message
print 'new data:', nfc.ndef.TextRecord(tag.ndef.message[0]).text
print "release your NFC"
def readCard(self):
rdwr_options = {
'on-startup': self.startup,
'on-connect': self.connected_read,
}
with nfc.ContactlessFrontend('usb') as clf:
tag = clf.connect(rdwr=rdwr_options)
if tag.ndef:
return(nfc.ndef.TextRecord(tag.ndef.message[0]).text)
else:
return False
def writeCard(self, text):
self.text = text
rdwr_options = {
'on-startup': self.startup,
'on-connect': self.connected_write,
}
with nfc.ContactlessFrontend('usb') as clf:
tag = clf.connect(rdwr=rdwr_options)
if tag.ndef:
return(nfc.ndef.TextRecord(tag.ndef.message[0]).text)
else:
return False
def released_Card(self):
rdwr_options = {
'on-release': self.released,
}
with nfc.ContactlessFrontend('usb') as clf:
tag = clf.connect(rdwr=rdwr_options)
if tag.ndef:
return(nfc.ndef.TextRecord(tag.ndef.message[0]).text)
else:
return False