I have the following problem. I am working with Python and RaspberryPi 3 recently.
My task is to write the data (RFID together with date and time into the MySQL database).
Date and time works, they are displayed in MySQL.
import RPi.GPIO as GPIO
import MFRC522
import signal
import time
import MySQLdb
global c
global db
continue_reading = True
def insert_to_db():
rfnummer = (getrfnummer())
zeit = (datetime.datetime.fromtimestamp(time.time()).strftime("%H:%M:%S"))
datum = (datetime.datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d"))
print((RFnummer + " - " + zeit + " - " + datum))
sql = "INSERT INTO TAB_RFID (RFnummer, T_Date, T_Time) VALUES (%s, %s, %s)"
try:
c.execute(sql,(str(rfnummer), str(datum), str(zeit)))
db.commit()
except:
db.rollback()
# db.close()
def read_from_db():
try:
c.execute("SELECT * FROM TAB_RFID ORDER BY ID DESC LIMIT 1")
result = c.fetchall()
if result is not None:
print(('RFnummer: ', result[0][1], '| time: ', result[0][3], ' | datum: ', result[0][2]))
except:
print("read error")
# Capture SIGINT for cleanup when the script is aborted
def end_read(signal, frame):
global continue_reading
continue_reading = False
GPIO.cleanup()
Hook the SIGINT
signal.signal(signal.SIGINT, end_read)
Create an object of the class MFRC522
MIFAREReader = MFRC522.MFRC522()
This loop keeps checking for chips. If one is near it will get the UID and authenticate
while continue_reading:
# Scan for cards
(status, TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)
# If a card is found
# if status == MIFAREReader.MI_OK:
# print "Card Detected"
# Get the UID of the card
(status, uid) = MIFAREReader.MFRC522_Anticoll()
# If we have the UID, continue
if status == MIFAREReader.MI_OK:
# Print UID
# print str(uid[0])+str(uid[1])+str(uid[2])+str(uid[3])
time.sleep(0.5)
if status == MIFAREReader.MI_OK:
print((time.strftime("%d.%m.%Y %H:%M:%S")))
def main(): while 1: insert_to_db() read_from_db() # time.sleep(5)
if name == 'main': try: db = MySQLdb.connect("localhost", "root", "mypassword", "mydb") c = db.cursor() except: print("Keine Verbindung zum Server...")
try:
main()
except KeyboardInterrupt:
print("bye bye...")
pass