ESP32 WROOM Dev kit, MySQL Abfrage

Hallo zusammen,

Ich versuche gerade einen Türöffner mit einem ESP32 zu basteln.
Geöffnet werden soll die Tür durch das Auslesen eines RFID Tags.
Der Hex Code der RFID Tags die zum öffnen berechtigt sind liegen in einer MySql Datenbank die hier bei mir im Lan auf einem Server läuft.
Soweit das die Tags ausgelesen werden und mit werten verglichen werden das habe ich hingebracht. Allerdings will es einfach nicht klappen, dass ich die hinterlegten Werte aus der Datenbank auslese. Habe schon versucht von einem anderen Rechner aus auf die Datenbank zu zugreifen. Das funktioniert prima. Eben nur vom ESP32 nicht.
Kann mir da bitte wer Helfen?

Hier mal der Code:

In der Credentials.h sind ssid,pass,user,password angegeben.


//Libraries
#include <SPI.h>//https://www.arduino.cc/en/reference/SPI
#include <MFRC522.h>//https://github.com/miguelbalboa/rfid
#include <Adafruit_GFX.h>    // Adafruit Grafik-Bibliothek wird benötigt
#include <Adafruit_ST7735.h> // Adafruit ST7735-Bibliothek wird benötigt
#include <MySQL_Generic.h>
#include "Credentials.h"
#include "defines.h"

//Constants
#define SS_PIN 21
#define RST_PIN 22
#define TFT_PIN_CS   2 // Arduino-Pin an Display CS   
#define TFT_PIN_RS   25  // Arduino-Pin an 
#define TFT_PIN_RST  26  // Arduino Reset-Pin
#define MAX_QUERY_LEN 128
#define MAX_KEYS     20 // max keys in list

//Adafruit_ST7735 tft = Adafruit_ST7735(TFT_PIN_CS, TFT_PIN_RS, TFT_PIN_RST);  // ST7735-Bibliothek Setup

//Variables
//byte nuidPICC[4] = {0, 0, 0, 0};
//MFRC522::MIFARE_Key key;
MFRC522 rfid = MFRC522(SS_PIN, RST_PIN);
IPAddress dbHost(192, 168, 10, 51);            // MySQL hostname or IP address
uint16_t dbPort = 3306;                        // MySQL host port
int ID[9];
char database[] = "XXXX";         // Database name

const char query[] = "SELECT * FROM zugangskontrolle";

MySQL_Connection conn((Client *)&client);

struct KeyData {
    byte* id; // Dynamic array to hold the ID
    char* name; // Dynamically allocated
    char* message; // Dynamically allocated
    unsigned int idLength; // Length of the ID byte array

    KeyData() : id(nullptr), name(nullptr), message(nullptr), idLength(0) {}
    ~KeyData() {
        delete[] id;
        free(name);
        free(message);
    }

    // Copy constructor and assignment operator should be defined or deleted
    // to handle deep copy or prevent copying if not needed.
};

int currentKeyListSize = 0;
KeyData keyList[MAX_KEYS] = {};

void initializeKeyList() {
    // Temporary hard-coded IDs for demonstration
    byte ids[][4] = {
        {0xA3, 0x17, 0x43, 0xA8},
        {0x05, 0x06, 0x07, 0x08}
    };
    const char* names[] = {"X", "Y"};
    const char* messages[] = {"Hello", "asdf"};

    for (int i = 0; i < currentKeyListSize; ++i) {
        keyList[i].id = new byte[4]; // Assuming all IDs are 4 bytes
        memcpy(keyList[i].id, ids[i], 4);
        keyList[i].idLength = 4;
        keyList[i].name = strdup(names[i]);
        keyList[i].message = strdup(messages[i]);
    }
}

void setup() {
  //Init Serial USB
  Serial.begin(115200);
  Serial.println(F("Initialize System"));



  updateKeyData();
  printKeyList();
}

void loop() {   
  //readRFID();
}

void readRFID() { /* function readRFID */
  // Look for new 1 cards
  if (!rfid.PICC_IsNewCardPresent())
    return;

  // Verify if the NUID has been read
  if (!rfid.PICC_ReadCardSerial())
    return;
  
  Serial.print(F("RFID In hex: "));
  printHex(rfid.uid.uidByte, rfid.uid.size);
  Serial.println();

  rfid.PICC_HaltA(); // halt PICC
  rfid.PCD_StopCrypto1(); // stop encryption on PCD

  KeyData *keyData = getMatchingKeyData(rfid.uid.uidByte, rfid.uid.size);
  if(keyData == nullptr) {
    Serial.println("access denied.");
    return;
  }
  //KeyData keyData = *keyDataRef;

  Serial.print("Access Granted: ");
  Serial.println(keyData->message);
}

/**
   Helper routine to dump a byte array as hex values to Serial.
*/
void printHex(byte *buffer, byte bufferSize) {
  for (byte i = 0; i < bufferSize; i++) {
    Serial.print(buffer[i] < 0x10 ? " 0" : " ");
    Serial.print(buffer[i], HEX);
  }
}

KeyData* getMatchingKeyData(byte *inputId, int inputIdLength) {
  for(unsigned int i = 0; i < currentKeyListSize; i++) {
    if(checkKey(inputId, inputIdLength, keyList[i].id, keyList[i].idLength)) {
      return &keyList[i];
    }
  }
  return nullptr;
}

bool checkKey(byte *inputId, int inputIdLength, byte *keyId, int keyIdLength) {
  if(inputIdLength != keyIdLength)
    return false;
  
  for (unsigned int i = 0; i < keyIdLength; i++) {
    if (inputId[i] != keyId[i]) {
      return false; // Arrays are not equal
    }
  }
  return true; // Arrays are equal
}

// Converts a hex string to a byte array, dynamically allocates memory for the byte array.
// Caller is responsible for freeing the memory.
byte* hexStringToByteArray(const char* hexString, unsigned int& outLength) {
    // Calculate the length of the input string and allocate memory accordingly
    outLength = 0;
    for (const char* p = hexString; *p; p++) {
        if (*p != ' ') outLength++;
    }
    outLength = outLength / 2; // Two hex chars represent one byte

    byte* byteArray = new byte[outLength];
    const char* hexChar = hexString;
    for (unsigned int i = 0; i < outLength; i++) {
        unsigned int byte;
        while (*hexChar == ' ') hexChar++; // Skip spaces
        sscanf(hexChar, "%2x", &byte);
        byteArray[i] = byte;
        hexChar += 2; // Move past the two hex digits
        while (*hexChar == ' ') hexChar++; // Skip spaces after the hex digits if any
    }
    return byteArray;
}

// Frees dynamically allocated memory in a KeyData struct and resets its members.
void freeKeyData(KeyData& keyData) {
    if (keyData.id) {
        delete[] keyData.id;
        keyData.id = nullptr;
    }
    if (keyData.name) {
        free(keyData.name);
        keyData.name = nullptr;
    }
    if (keyData.message) {
        free(keyData.message);
        keyData.message = nullptr;
    }
    keyData.idLength = 0;
}


void updateKeyData() {
    if(connectWifi()) {
        if(connectDatabase()) {
            queryDatabase();
        }
        disconnectDatabasse();
    }
    disconnectWifi();
}


boolean connectWifi() {
    // Ensure WiFi is connected
    Serial.print(F("Connecting to WiFi..."));
    WiFi.begin(ssid, pass);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println();
    Serial.println(F("Connected to WiFi."));
    return true; 
}

boolean disconnectWifi() {
    WiFi.disconnect();
    Serial.println(F("Disconnected from WiFi."));
}

boolean connectDatabase() {
  Serial.print(F("Connecting to Database..."));
  while(conn.connectNonBlocking(dbHost, dbPort, user, password, database) != RESULT_OK)
  {
      delay(500);
      Serial.print(".");
  }
  Serial.println();
  Serial.println(F("Connected to Database."));
  return true;
}

boolean disconnectDatabasse() {
    conn.close();// close the connection
}

// Updates keyList with new data from the database.
void queryDatabase() {
    MySQL_Query query_mem = MySQL_Query(&conn);
    Serial.println(F("Execute Query."));
    if (!query_mem.execute(query)) {
        Serial.println(F("Query failed."));
        return;
    }
    Serial.println(F("Query succeeded."));

}

void printKeyData(const KeyData& keyData) {
    Serial.print("ID: ");
    for (unsigned int i = 0; i < keyData.idLength; i++) {
        if (keyData.id[i] < 0x10) {
            Serial.print('0'); // Print leading zero for single digit hex values
        }
        Serial.print(keyData.id[i], HEX);
        Serial.print(" "); // Space between bytes for readability
    }
    Serial.print(", Name: ");
    Serial.print(keyData.name ? keyData.name : "NULL");
    Serial.print(", Message: ");
    Serial.println(keyData.message ? keyData.message : "NULL");
}

void printKeyList() {
    Serial.println("Current Key List:");
    for (int i = 0; i < currentKeyListSize; i++) {
        printKeyData(keyList[i]);
    }
}

 

Schonmal VIELEN DANK!

Sehe keine Definition von client.

Da die RFID Geschichte kein Thema ist, schmeiß sie doch raus und bau einen Test-Sketch, der nur die Daten aus deiner Datenbank holt.

Wenn du nachsehen würdest, was du für Debug-Ausgaben im SerialMonitor erhältst, könntest du eher eingrenzen wo es hängt. Und eventuell deine Serial.print Testausgaben erweitern.

"Es funktioniert nicht" ist übrigens keine Fehlerbeschreibung

Gerne.

Servus Michael!

Danke für deine Antwort.
Ums ehrlich zu sagen, ich hab sehr wenig Dunst vom Programmieren.
Das hat ein Freund für mich geschrieben.

Nun ja, die Fehlermeldung.

Das WLAN Verbinden funktioniert.

Er bleibt immer in dieser Schleife hängen und macht Punkte.

 while(conn.connectNonBlocking(dbHost, dbPort, user, password, database) != RESULT_OK)
  {
      delay(500);
      Serial.print(".");
  }
  Serial.println();
  Serial.println(F("Connected to Database."));
  return true;

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.