Probleme bei if abfrage

Wenn du dir nicht sicher bist, in welchem der anderen Foren du die Frage stellen sollst, dann bist du hier im Forum für allgemeine Fragen sicher richtig.
Antworten
seeks
User
Beiträge: 4
Registriert: Sonntag 18. Oktober 2020, 13:01

Hallo,

ich versuche seit stunden eine if abfrage zu basteln bekomme es aber leider nicht hin.
wenn die variable data None enthält, soll das script es mit print in die console schreiben und nicht das script abbrechen.

hätte da einer ein kleines beispiel für mich bitte?

Code: Alles auswählen

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 "Card read UID: %s,%s,%s,%s" % (uid[0], uid[1], uid[2], uid[3])
		# This is the default key for authentication
		key = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]
		# Select the scanned tag
		MIFAREReader.MFRC522_SelectTag(uid)
		# Authenticate
		status = MIFAREReader.MFRC522_Auth(MIFAREReader.PICC_AUTHENT1A, 8, key, uid)
		# Check if authenticated
		if status == MIFAREReader.MI_OK:
			data = MIFAREReader.MFRC522_Read(8)
			print "Data:", data
			MIFAREReader.MFRC522_StopCrypto1()
			text = "".join(chr(x) for x in data)
			print text
			print data
			print uid
		else:
			print "Authentication error"
Benutzeravatar
sparrow
User
Beiträge: 4538
Registriert: Freitag 17. April 2009, 10:28

Python 2 ist tot. Es wird nicht mehr weiterenwickelt und es gibt seit Anfang des Jahres auch keine Sicherheitsupdates mehr. Bitte verwende Python 3.x

Was hast du denn versucht um feszustellen, ob data "None" ist?
Die Prüfung darauf ist ja eher trivial.
ElektroBerry
User
Beiträge: 31
Registriert: Samstag 16. Mai 2020, 18:52

In Python3 könnte man es so schreiben:

Code: Alles auswählen

if data := MIFAREReader.MFRC522_Read(8): 
    print(f"Data:" {data})
    MIFAREReader.MFRC522_StopCrypto1()
    text = "".join(chr(x) for x in data)
    print(f"{text}\n{data}\n{uid}")
else:
    print("Error: data is None.")
Und ansonsten die direkte Antwort:

Code: Alles auswählen

data = ""
if not data:
    print("Data is None")
else:
    print(f"Data: {data}")
seeks
User
Beiträge: 4
Registriert: Sonntag 18. Oktober 2020, 13:01

Ohh super danke euch!

ist ein beispiel script zum auslesen von einem RC522 RF IC Reader Sensor Modul
seeks
User
Beiträge: 4
Registriert: Sonntag 18. Oktober 2020, 13:01

Hallo,

ich habe ein wenig am script weitergebastelt, dabei bin ich allerdings auf einen neuen fehler gestoßen und komme leider nicht weiter :(


der fehler:
Traceback (most recent call last):
File "read2.py", line 61, in <module>
db.mysql_read('hallo')
AttributeError: 'DB' object has no attribute 'mysql_read'
das read script:

Code: Alles auswählen

import RPi.GPIO as GPIO
import MFRC522
import signal


from sql import *
db = DB()

continue_reading = True

# Capture SIGINT for cleanup when the script is aborted
def end_read(signal,frame):
	global continue_reading
	print ("Ctrl+C captured, ending read.")
	continue_reading = False
	GPIO.cleanup()

# Hook the SIGINT
signal.signal(signal.SIGINT, end_read)

# Create an object of the class MFRC522
MIFAREReader = MFRC522.MFRC522()

# Welcome message
print ("Welcome to the MFRC522 data read example")
print ("Press Ctrl-C to stop.")

# 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 ("Card read UID: %s,%s,%s,%s" % (uid[0], uid[1], uid[2], uid[3]))
		# This is the default key for authentication
		key = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]
		# Select the scanned tag
		MIFAREReader.MFRC522_SelectTag(uid)
		# Authenticate
		status = MIFAREReader.MFRC522_Auth(MIFAREReader.PICC_AUTHENT1A, 8, key, uid)
		# Check if authenticated
		if status == MIFAREReader.MI_OK:
			data = MIFAREReader.MFRC522_Read(8)
			#print "Data:", data
			if not data:
				MIFAREReader.MFRC522_StopCrypto1()
			else:
				MIFAREReader.MFRC522_StopCrypto1()
				text = "".join(chr(x) for x in data)
				print ("Test:", text)
				print ("Data:", data)
				print ("UID:", uid)
				check = db.mysql_read(uid)
				print ("Check:", check)
		else:
			print ("Authentication error")
das sql script:

Code: Alles auswählen

import serial
import pymysql
import sys

class DB():
	def __init__ (self):
		db = pymysql.connect (host="localhost", user="NFC", passwd="blaa", db="NFC")
		db.autocommit (True)
		self.cur = db.cursor()
	def close_db( self ):
		self.cur.close()

		def add_user (self,rfid_id, name):
			add=self.cur.execute("INSERT INTO users (UID, name) " + "VALUES (%s,%s)", (rfid_id, name))

		def mysql_read (self, rfid_id):
			print ("angekommen:", rfid_id)
			a=self.cur.execute ("SELECT name, UID, nummer, zeit" + "FROM users WHERE nummer = %s" ,rfid_id)
			name = 0
			UID = 0 
			nummer = 0
			zeit = 0
			for row in self.cur.fetchall():
				name = int(row[0])
				UID = str(row[1]) 
				nummer = str(row[2])
				zeit = str(row[3])
			return name, UID, nummer, zeit

		def update_timestamp (self, rfid_id):
			a=self.cur.execute("UPDATE users SET zeit = NOW() " + "WHERE nummer = %s" ,rfid_id)
Benutzeravatar
sparrow
User
Beiträge: 4538
Registriert: Freitag 17. April 2009, 10:28

Nab rückt mit 4 Leerzeichen ein. Nicht mit Tabstops.
Und offensichtlich stimmt die Einrückung in der Klasse nicht. Das ist aber esentiell in Python.
Sirius3
User
Beiträge: 18272
Registriert: Sonntag 21. Oktober 2012, 17:20

Cursor sind was kurzlebiges, das sollte nicht länger als eine Transaktion existieren.
Eine Klasse, die nur ein einziges Attribut hat, ist keine sinnvolle Klasse.
Du bindest den Rückgabewert von execute an Variablen, die nie benutzt werden, was ja auch klar ist, weil das keinen nutzbaren Rückgabewert hat.
Wenn das SELECT nur einen Wert liefern kann, dann ist eine for-Schleife und fetchall verwirrend.
Die Daten sollten schon die richtigen Typen haben, so dass die int- und str-Aufrufe unsinnig sein sollten. Ist der Rückgabewert von 0,0,0,0 wirklich sinnvoll?
Im Hauptprogramm ist das Signalhandling Schrott, man sollte keine globalen Variablen benutzen.

Code: Alles auswählen

from contextlib import closing
from RPi import GPIO
import MFRC522
import pymysql

# This is the default key for authentication
KEY = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]

def initialize_db():
    return pymysql.connect(host="localhost", user="NFC", passwd="blaa", db="NFC")

def add_user(db, rfid_id, name):
    with closing(db.cursor()) as cursor:
        cursor.execute("INSERT INTO users (UID, name) VALUES (%s,%s)", (rfid_id, name))
        db.commit()

def mysql_read(db, rfid_id):
    print("angekommen:", rfid_id)
    with closing(db.cursor()) as cursor:
        cursor.execute("SELECT name, UID, nummer, zeit FROM users WHERE nummer = %s", [rfid_id])
        return cursor.fetchone()

def update_timestamp(db, rfid_id):
    with closing(db.cursor()) as cursor:
        cursor.execute("UPDATE users SET zeit = NOW() WHERE nummer = %s", [rfid_id])
        db.commit()

def read_card(db, mifare_reader):
    (status,TagType) = mifare_reader.MFRC522_Request(mifare_reader.PICC_REQIDL)
    if status != mifare_reader.MI_OK:
        return
    print("Card detected")
    # Get the UID of the card
    (status,uid) = mifare_reader.MFRC522_Anticoll()
    # If we have the UID, continue
    if status != mifare_reader.MI_OK:
        return
    # Print UID
    print("Card read UID: %s,%s,%s,%s" % (uid[0], uid[1], uid[2], uid[3]))
    # Select the scanned tag
    mifare_reader.MFRC522_SelectTag(uid)
    # Authenticate
    status = mifare_reader.MFRC522_Auth(mifare_reader.PICC_AUTHENT1A, 8, KEY, uid)
    # Check if authenticated
    if status != mifare_reader.MI_OK:
        return
    data = mifare_reader.MFRC522_Read(8)
    mifare_reader.MFRC522_StopCrypto1()
    if not data:
        return
    text = "".join(chr(x) for x in data)
    print("Test:", text)
    print("Data:", data)
    print("UID:", uid)
    check = db.mysql_read(uid)
    print("Check:", check)

def main():
    try:
        db = initialize_db()
        mifare_reader = MFRC522.MFRC522()
        while True: 
            read_card(db, mifare_reader)
    finally:
        GPIO.cleanup()

if __name__ == "__main__":
    main()
seeks
User
Beiträge: 4
Registriert: Sonntag 18. Oktober 2020, 13:01

Hallo,

vielen vielen dank für die tipps, das mit den einrücken werde ich mir zu herzen nehmen und nicht mehr mit tabs arbeiten!
Antworten