1
0
forked from tanchou/Verilog
This commit is contained in:
Gamenight77
2025-04-28 09:22:17 +02:00
parent a976fcb266
commit 505f71974e
26 changed files with 94421 additions and 4 deletions

View File

@@ -0,0 +1,85 @@
# Projet FPGA (Tang Nano 20K) + ESP32
## Objectif global
Le but est de pouvoir se connecter à lESP32 via Wi-Fi, et de communiquer avec un PC (ou autre appareil USB connecté au FPGA).
LESP32 agit comme **esclave** pour le FPGA et sert uniquement de **portail Wi-Fi**.
Le FPGA fait le lien entre les appareils Wi-Fi et le périphérique USB.
---
## Rôles des composants
### FPGA (Tang Nano 20K)
- Gère linterface UART avec lESP32
- Gère la communication USB avec le PC
- Fait le routage bidirectionnel des données (mux / buffer intelligent)
### ESP32
- Crée un réseau Wi-Fi local
- Écoute via une connexion UART avec le FPGA
- Reçoit les commandes du FPGA et envoie les données des clients Wi-Fi
### PC (ou autre appareil USB)
- Envoie et reçoit des données (via terminal série ou logiciel personnalisé)
---
## Architecture
```
[ PC via USB ]
┌───────▼────────┐
│ uart_usb │ <— UART avec le PC
└──────┬─────────┘
┌──────────────┐
│ uart_core │ <— Routeur/contrôleur central
└────┬────┬────┘
│ │
┌─────────────┘ └────────────┐
▼ ▼
[uart_wifi] [user_logic] (LEDs)
<— UART avec ESP32 (comporte les modules fonctionnels)
```
---
## Détails des modules
### `uart_usb`
- Interface UART vers le PC (via USB-UART)
- Peut utiliser un convertisseur USB-UART via `uart_rx_pc` / `uart_tx_pc`
- Fournit :
- `rx_data`, `rx_valid`, `rx_ready`
- `tx_data`, `tx_valid`, `tx_ready`
### `uart_wifi`
- Interface UART avec lESP32
- Même interface que `uart_usb`, mais avec `uart_rx_esp` / `uart_tx_esp`
- Sert à la communication Wi-Fi
### `uart_core`
- Module central de routage UART
- Gère la logique de communication :
- Lecture des commandes depuis le PC → envoie à lESP32
- Réception de réponse de lESP32 → envoie au PC
- Peut être codé comme une FSM maître ou un router simple
---
## Signaux principaux
| Signal | Description |
|------------------------|------------------------------------------------------|
| `uart_rx_pc` | UART RX depuis le PC |
| `uart_tx_pc` | UART TX vers le PC |
| `uart_rx_esp` | UART RX depuis lESP32 |
| `uart_tx_esp` | UART TX vers lESP32 |
| `fifo_rx_pc_to_esp` | Données du PC à transférer à lESP32 |
| `fifo_rx_esp_to_pc` | Données de lESP32 à transférer au PC |
| `link_manager` | Logique de contrôle des transferts entre buffers/UART|
| `status_led` | Gestion des LEDs de statut |

View File

@@ -0,0 +1,233 @@
#include <WiFi.h>
#include <WebServer.h>
#include "esp_wifi.h"
const char* ssid = "ESP32-Louis";
const char* password = "motdepasse";
WebServer server(80);
void handleRoot() {
digitalWrite(2,HIGH);
wifi_sta_list_t sta_list;
esp_wifi_ap_get_sta_list(&sta_list);
String page = "";
page += "<!DOCTYPE html>";
page += "<html>";
page += "<head>";
page += "<title>ESP32</title>";
page += "<meta charset=\"UTF-8\">";
page += "</head>";
page += "<body>";
page += "<h1>Appareils connectés à l'ESP32</h1>";
page += "<ul>";
page += "<ul>";
for (int i = 0; i < sta_list.num; i++) {
const wifi_sta_info_t& client = sta_list.sta[i];
char macStr[18];
snprintf(macStr, sizeof(macStr),
"%02X:%02X:%02X:%02X:%02X:%02X",
client.mac[0], client.mac[1], client.mac[2],
client.mac[3], client.mac[4], client.mac[5]);
page += "<li>MAC : ";
page += macStr;
page += "</li>";
}
page += "</ul>";
page += "<p>Nombre total : " + String(sta_list.num) + "</p>";
page += "</body></html>";
server.send(200, "text/html", page);
digitalWrite(2,LOW);
}
void onClientConnected(WiFiEvent_t event, WiFiEventInfo_t info) {
digitalWrite(2, HIGH);
const wifi_event_ap_staconnected_t* conn = reinterpret_cast<const wifi_event_ap_staconnected_t*>(&info);
byte packet[11]; // 2 header + 1 code + 6 MAC + 1 fin
packet[0] = 0x02;
packet[1] = 0x02;
packet[2] = 0x01;
// Copier l'adr MAC dans le tableau
memcpy(&packet[3], conn->mac, 6);
packet[9] = 0x1B; // marqueur avant fin
packet[10] = 0x03; // fin de trame
Serial.write(packet, sizeof(packet));
digitalWrite(2, LOW);
}
void onClientDisconnected(WiFiEvent_t event, WiFiEventInfo_t info) {
digitalWrite(2, HIGH);
const wifi_event_ap_stadisconnected_t* disc = reinterpret_cast<const wifi_event_ap_stadisconnected_t*>(&info);
byte packet[12];
packet[0] = 0x02;
packet[1] = 0x02; // OP_CODE: Connection Update
packet[2] = 0x00; // Disconnected
memcpy(&packet[3], disc->mac, 6); // MAC address
packet[9] = 0x1B; // marqueur avant fin
packet[10] = 0x03; // fin de trame
packet[11] = '\n'; // (optionnel, pour debug dans terminal série)
Serial.write(packet, 11); // <= envoie bien 11 octets, pas 12 (on ne compte pas le \n ici si tu veux lignorer)
digitalWrite(2, LOW);
}
#define BUFFER_SIZE 64
uint8_t rxBuffer[BUFFER_SIZE];
uint8_t rxIndex = 0;
bool inFrame = false;
void processCommand(uint8_t* data, int length) {
// Vérifie la validité de la trame
if (length < 4 || data[0] != 0x02 || data[length - 2] != 0x1B || data[length - 1] != 0x03) {
byte packet[] = {0x02, 0x00, 0x03, 0x1B, 0x03}; // Erreur : Trame invalide
Serial.write(packet, sizeof(packet));
return;
}
uint8_t type = data[1];
switch (type) {
case 0x01: { // Wi-Fi State
bool wifiUp = WiFi.status() == WL_CONNECTED;
byte packet[] = {0x02, 0x01, wifiUp ? 0x01 : 0x00, 0x1B, 0x03};
Serial.write(packet, sizeof(packet));
break;
}
case 0x03: { // Request Connected Devices
wifi_sta_list_t staList;
if (esp_wifi_ap_get_sta_list(&staList) == ESP_OK) {
byte packet[3 + 1 + 6 * 10 + 2]; // max 10 clients
uint8_t index = 0;
packet[index++] = 0x02;
packet[index++] = 0x04;
packet[index++] = staList.num; // LEN
for (int i = 0; i < staList.num; i++) {
memcpy(&packet[index], staList.sta[i].mac, 6);
index += 6;
}
packet[index++] = 0x1B;
packet[index++] = 0x03;
Serial.write(packet, index);
} else {
byte error[] = {0x02, 0x00, 0x02, 0x1B, 0x03}; // Erreur : args
Serial.write(error, sizeof(error));
}
break;
}
case 0x05: { // Send Message
if (length < 12) {
byte packet[] = {0x02, 0x00, 0x02, 0x1B, 0x03}; // args error
Serial.write(packet, sizeof(packet));
break;
}
uint8_t* mac = &data[2];
uint8_t msgLen = data[8];
if (length != 9 + msgLen + 2) {
byte packet[] = {0x02, 0x00, 0x04, 0x1B, 0x03}; // too long trame
Serial.write(packet, sizeof(packet));
break;
}
// Ici tu pourrais ajouter une logique pour router le message au bon appareil (plus tard)
// ACK possible :
byte ack[] = {0x02, 0x04, 0x01, 0x1B, 0x03}; // ACK
Serial.write(ack, sizeof(ack));
break;
}
default: {
byte packet[] = {0x02, 0x00, 0x01, 0x1B, 0x03}; // Erreur : commande inconnue
Serial.write(packet, sizeof(packet));
}
}
}
void setup() {
Serial.begin(115200);
if (!WiFi.softAP(ssid, password)) {
byte packet[] = {0x02, 0x01, 0x00, 0x03};
Serial.write(packet, sizeof(packet));
}
WiFi.onEvent(onClientConnected, ARDUINO_EVENT_WIFI_AP_STACONNECTED);
WiFi.onEvent(onClientDisconnected, ARDUINO_EVENT_WIFI_AP_STADISCONNECTED);
delay(1000); // Donne un peu de temps pour démarrer le WiFi
server.on("/", handleRoot);
server.begin();
pinMode(2, OUTPUT);
byte packet[] = {0x02, 0x01, 0x01, 0x03};
Serial.write(packet, sizeof(packet));
}
void loop() {
server.handleClient();
bool escaping = false;
while (Serial.available()) {
uint8_t b = Serial.read();
if (!inFrame) {
if (b == 0x02) {
inFrame = true;
rxIndex = 0;
rxBuffer[rxIndex++] = b;
}
continue;
}
if (escaping) {
if (rxIndex < BUFFER_SIZE) {
rxBuffer[rxIndex++] = b;
}
escaping = false;
continue;
}
if (b == 0x1B) {
escaping = true;
} else if (b == 0x03) {
rxBuffer[rxIndex++] = b;
processCommand(rxBuffer, rxIndex);
inFrame = false;
rxIndex = 0;
} else {
if (rxIndex < BUFFER_SIZE) {
rxBuffer[rxIndex++] = b;
} else {
inFrame = false;
rxIndex = 0;
}
}
}
}

View File

@@ -0,0 +1,28 @@
import serial
def main():
try:
with serial.Serial('COM5', 115200, timeout=1) as ser:
buffer = []
while True:
byte = ser.read(1)
if byte:
value = byte[0]
buffer.append(value)
print(f"Reçu: {value:#04x}")
# Vérifie début de trame
if len(buffer) == 1 and buffer[0] != 0x02:
buffer.clear()
# Vérifie fin de trame
if len(buffer) >= 3 and buffer[-2] == 0x1B and buffer[-1] == 0x03:
print("\n=== Trame complète reçue ===")
print("Trame :", ' '.join(f"{b:#04x}" for b in buffer))
print("=============================\n")
buffer.clear()
except serial.SerialException as e:
print("Erreur de port série :", e)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,54 @@
import serial
def read_frame(ser):
frame = []
in_frame = False
while True:
byte = ser.read()
if not byte:
continue
b = byte[0]
if not in_frame:
if b == 0x02:
frame = [b]
in_frame = True
else:
frame.append(b)
if len(frame) >= 2 and frame[-2] == 0x1B and frame[-1] == 0x03:
return frame
def interpret_frame(frame):
if len(frame) < 4 or frame[0] != 0x02 or frame[-2:] != [0x1B, 0x03]:
return "Trame invalide"
op_code = frame[1]
if op_code == 0x00:
return f"[Erreur] Code: {hex(frame[2])}"
elif op_code == 0x01:
state = frame[2]
return f"[Wi-Fi] {'UP' if state == 1 else 'DOWN'}"
elif op_code == 0x02:
status = 'Connecté' if frame[2] == 0x01 else 'Déconnecté'
mac = ':'.join(f"{b:02X}" for b in frame[3:9])
return f"[Connexion] {status} - {mac}"
elif op_code == 0x03:
return "[Demande appareils connectés]"
elif op_code == 0x04:
mac = ':'.join(f"{b:02X}" for b in frame[2:8])
length = frame[8]
msg = bytes(frame[9:9+length]).decode(errors='ignore')
return f"[Message] à {mac} : {msg}"
else:
return f"[OpCode inconnu] {hex(op_code)}"
def main():
with serial.Serial('COM5', 115200, timeout=1) as ser:
print("Lecture des trames...")
while True:
frame = read_frame(ser)
info = interpret_frame(frame)
print(info)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,60 @@
import serial
import time
START_BYTE = 0x02
END_BYTES = [0x1B, 0x03]
def build_command(opcode, payload=b''):
frame = bytearray()
frame.append(START_BYTE)
frame.append(opcode)
frame.extend(payload)
frame.extend(END_BYTES)
return frame
def send_command(ser, opcode, payload=b''):
frame = build_command(opcode, payload)
print(f"Envoi : {[hex(b) for b in frame]}")
ser.write(frame)
def main():
port = 'COM5'
baud = 115200
try:
with serial.Serial(port, baud, timeout=2) as ser:
while True:
print("\nCommandes disponibles :")
print("1. État du Wi-Fi")
print("2. Liste des clients connectés")
print("3. Envoyer un message")
print("4. Quitter")
choix = input("Choix (1-4) : ")
if choix == "1":
send_command(ser, 0x01)
elif choix == "2":
send_command(ser, 0x03)
elif choix == "3":
msg = input("Message à envoyer : ")
msg_bytes = msg.encode('utf-8')
send_command(ser, 0x05, msg_bytes)
elif choix == "4":
print("Fermeture.")
break
else:
print("Choix invalide.")
time.sleep(0.5)
print("Réponse reçue :")
while ser.in_waiting:
byte = ser.read(1)
print(f"Reçu : 0x{byte[0]:02X}")
except serial.SerialException as e:
print(f"Erreur de port série : {e}")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,106 @@
#include <WiFi.h>
#include <WebServer.h>
#include "esp_wifi.h"
const char* ssid = "ESP32-Louis";
const char* password = "motdepasse";
WebServer server(80);
void handleRoot() {
digitalWrite(2,HIGH);
wifi_sta_list_t sta_list;
esp_wifi_ap_get_sta_list(&sta_list);
String page = "";
page += "<!DOCTYPE html>";
page += "<html>";
page += "<head>";
page += "<title>ESP32</title>";
page += "<meta charset=\"UTF-8\">";
page += "</head>";
page += "<body>";
page += "<h1>Appareils connectés à l'ESP32</h1>";
page += "<ul>";
page += "<ul>";
for (int i = 0; i < sta_list.num; i++) {
const wifi_sta_info_t& client = sta_list.sta[i];
char macStr[18];
snprintf(macStr, sizeof(macStr),
"%02X:%02X:%02X:%02X:%02X:%02X",
client.mac[0], client.mac[1], client.mac[2],
client.mac[3], client.mac[4], client.mac[5]);
page += "<li>MAC : ";
page += macStr;
page += "</li>";
}
page += "</ul>";
page += "<p>Nombre total : " + String(sta_list.num) + "</p>";
page += "</body></html>";
server.send(200, "text/html", page);
digitalWrite(2,LOW);
}
void onClientConnected(WiFiEvent_t event, WiFiEventInfo_t info) {
digitalWrite(2,HIGH);
wifi_sta_list_t sta_list;
esp_wifi_ap_get_sta_list(&sta_list);
for (int i = 0; i < sta_list.num; i++) {
const wifi_sta_info_t& client = sta_list.sta[i];
char macStr[18];
snprintf(macStr, sizeof(macStr),
"%02X:%02X:%02X:%02X:%02X:%02X",
client.mac[0], client.mac[1], client.mac[2],
client.mac[3], client.mac[4], client.mac[5]);
Serial.print("Adresse MAC : ");
Serial.println(macStr);
}
digitalWrite(2,LOW);
}
void onClientDisconnected(WiFiEvent_t event, WiFiEventInfo_t info) {
digitalWrite(2,HIGH);
wifi_sta_list_t sta_list;
esp_wifi_ap_get_sta_list(&sta_list);
for (int i = 0; i < sta_list.num; i++) {
const wifi_sta_info_t& client = sta_list.sta[i];
char macStr[18];
snprintf(macStr, sizeof(macStr),
"%02X:%02X:%02X:%02X:%02X:%02X",
client.mac[0], client.mac[1], client.mac[2],
client.mac[3], client.mac[4], client.mac[5]);
Serial.print("",macStr);
}
digitalWrite(2,LOW);
}
void setup() {
Serial.begin(115200);
WiFi.softAP(ssid, password);
WiFi.onEvent(onClientConnected, ARDUINO_EVENT_WIFI_AP_STACONNECTED);
WiFi.onEvent(onClientDisconnected, ARDUINO_EVENT_WIFI_AP_STADISCONNECTED);
delay(1000); // Donne un peu de temps pour démarrer le WiFi
server.on("/", handleRoot);
server.begin();
pinMode(2, OUTPUT);
}
void loop() {
server.handleClient();
}

View File

@@ -0,0 +1,11 @@
void setup() {
Serial.begin(115200);
pinMode(2, OUTPUT); // LED intégrée sur beaucoup d'ESP32
}
void loop() {
digitalWrite(2, HIGH);
delay(500);
digitalWrite(2, LOW);
delay(500);
}

View File

@@ -0,0 +1,81 @@
# Protocole between FPGA and ESP32
Ce protocole permet la communication entre le FPGA et l'ESP32 via UART, principalement pour transférer des données ou des commandes de contrôle simples.
---
## Structure générale des trames
Chaque trame est encadrée par des caractères spéciaux :
- **ESCAPE** (Before special char) : `0x1B`
- **STX** (Start of Text) : `0x02`
- **ETX** (End of Text) : `0x03`
**Format de trame :**
```
0x02 OP_CODE VALUE_1 VALUE_2 ... 0x1B 0x03
```
---
## Détail des commandes
| OP_CODE | Nom | Description | Format |
|---------|---------------------------|---------------------------------------------------------|-------------------------------------------------------------------------------|
| 0x00 | Error | Indique une erreur | `0x02 0x00 [ERROR_CODE] 0x1B 0x03` |
| 0x01 | Wi-Fi State | Indique l'état du Wi-Fi (0 = down, 1 = up) | `0x02 0x01 [0x00/0x01] 0x1B 0x03` |
| 0x02 | Connection Update | Notification de connexion ou déconnexion dun appareil | `0x02 0x02 [0x00/0x01] [MAC_ADDR (6 bytes)] 0x1B 0x03` |
| 0x03 | Request Connected Devices | Demande la liste des appareils connectés | `0x02 0x03 0x1B 0x03` |
| 0x04 | Send Connected Devices | Envoie la liste des appareil connecter | `0x02 0x04 [LEN (1 byte)] [MAC_LIST (n bytes)[MAC_ADDR (6 bytes)]] 0x1B 0x03` |
| 0x05 | Send Message | Envoie un message à un appareil connecté via son MAC | `0x02 0x05 [MAC_ADDR (6 bytes)] [LEN (1 byte)] [MESSAGE] 0x1B 0x03` |
---
## Détail des code erreur
| ERROR_CODE | Description |
|---------------|---------------------------------------------------------------|
| 0x00 | |
| 0x01 | Unknow command |
| 0x02 | Args error |
| 0x03 | Invalid Trame |
| 0x04 | Too long trame |
---
## Détails des champs
- **MAC_ADDR** : 6 octets représentant ladresse MAC du destinataire.
- **LEN** : Longueur du message à envoyer (1 octet).
- **MESSAGE** : Suite doctets de taille `LEN` représentant le message (binaire ou texte selon le contexte).
---
## Exemples
### Exemple 1 : Wi-Fi actif
```
0x02 0x01 0x01 0x03
```
→ Indique que le Wi-Fi est actif.
### Exemple 2 : Connexion d'un appareil
```
0x02 0x02 0x01 0x12 0x34 0x56 0x78 0x9A 0xBC 0x03
```
→ Un appareil avec ladresse MAC `12:34:56:78:9A:BC` vient de se connecter.
### Exemple 3 : Envoi de message
```
0x02 0x04 0x12 0x34 0x56 0x78 0x9A 0xBC 0x05 0x48 0x65 0x6C 0x6C 0x6F 0x03
```
→ Envoi du message `"Hello"` à lappareil `12:34:56:78:9A:BC`.
---
## Remarques
- Aucune vérification CRC/Checksum nest ajoutée pour le moment (possible amélioration future).
- Le protocole est extensible : il suffit dajouter de nouveaux OP_CODEs au besoin.