Zum Inhalt springen

ESP-Now lernen: Unterschied zwischen den Versionen

Aus Mein Projekte Wiki
Peter (Diskussion | Beiträge)
Peter (Diskussion | Beiträge)
Keine Bearbeitungszusammenfassung
 
(5 dazwischenliegende Versionen desselben Benutzers werden nicht angezeigt)
Zeile 3: Zeile 3:
Ich habe vor längerer Zeit schon mal mit ESP-Now auf M5Stack-Geräten herumgespielt. Davon ist aber nichts mehr präsent. Gute Informationen zu ESP-Now gibt es hier: https://randomnerdtutorials.com/?s=ESP-NOW
Ich habe vor längerer Zeit schon mal mit ESP-Now auf M5Stack-Geräten herumgespielt. Davon ist aber nichts mehr präsent. Gute Informationen zu ESP-Now gibt es hier: https://randomnerdtutorials.com/?s=ESP-NOW


== ESP-Now Beschreibung von Espressif==
Hier befindet sich eine DeepL-Übersetzung der originalen Dokumentation voen Espressif.</br>
Quelle: https://docs.espressif.com/projects/esp-idf/en/v6.0/esp32/api-reference/network/esp_now.html


=== ESP-NOW===
== [[ESP-Now Beschreibung von Espressif]]==
==== Overview====
ESP-NOW ist ein von Espressif definiertes verbindungsloses WLAN-Kommunikationsprotokoll. Bei ESP-NOW werden Anwendungsdaten in einen herstellerspezifischen Aktionsrahmen gekapselt und anschließend ohne Verbindung von einem WLAN-Gerät zum anderen übertragen.
 
CTR mit CBC-MAC-Protokoll (CCMP) wird aus Sicherheitsgründen zum Schutz des Aktionsframes verwendet. ESP-NOW findet breite Anwendung in intelligenten Leuchten, Fernsteuerungen, Sensoren usw.
 
=== Frame Format===
 
ESP-NOW verwendet einen herstellerspezifischen Aktionsrahmen zur Übertragung von ESP-NOW-Daten. Die Standard-Bitrate von ESP-NOW beträgt 1 Mbit/s.
 
Derzeit unterstützt ESP-NOW zwei Versionen: v1.0 und v2.0. Die von v2.0-Geräten unterstützte maximale Paketlänge beträgt 1470 (ESP_NOW_MAX_DATA_LEN_V2) Byte, während die von v1.0-Geräten unterstützte maximale Paketlänge 250 (ESP_NOW_MAX_DATA_LEN) Byte beträgt.
 
Geräte der Version 2.0 können Pakete sowohl von v2.0- als auch von v1.0-Geräten empfangen. Im Gegensatz dazu können v1.0-Geräte nur Pakete von anderen v1.0-Geräten empfangen.
 
Geräte der Version 1.0 können jedoch Pakete der Version 2.0 empfangen, wenn die Paketlänge kleiner oder gleich 250 (ESP_NOW_MAX_IE_DATA_LEN) ist. Bei Paketen, die diese Länge überschreiten, kürzen die Geräte der Version 1.0 die Daten entweder auf die ersten 250 (ESP_NOW_MAX_IE_DATA_LEN) Bytes oder verwerfen das Paket vollständig.
 
Das genaue Verhalten entnehmen Sie bitte der Dokumentation zur jeweiligen IDF-Version.
 
Das Format des herstellerspezifischen Aktionsrahmens lautet wie folgt:
 
------------------------------------------------------------------------------------------------------------
| MAC Header | Category Code | Organization Identifier | Random Values | Vendor Specific Content |  FCS  |
------------------------------------------------------------------------------------------------------------
  24 bytes        1 byte              3 bytes              4 bytes            7-x bytes        4 bytes
 
    Category Code: The Category Code field is set to the value (127) indicating the vendor-specific category.
 
    Organization Identifier: The Organization Identifier contains a unique identifier (0x18fe34), which is the first three bytes of MAC address applied by Espressif.
 
    Random Value: The Random Value filed is used to prevents relay attacks.
 
    Vendor Specific Content: The Vendor Specific Content contains several (at least one) vendor-specific element fields. For version v2.0, x = 1512(1470 + 6*7), for version v1.0, x = 257(250 + 7).
 
The format of the vendor-specific element frame is as follows:
 
ESP-NOW v1.0:
------------------------------------------------------------------------------------------
| Element ID | Length | Organization Identifier | Type | Reserved | Version |    Body    |
------------------------------------------------------------------------------------------
                                                        7~4 bits | 3~0 bits
    1 byte    1 byte            3 bytes        1 byte        1 byte        0-250 bytes
 
ESP-NOW v2.0:
-----------------------------------------------------------------------------------------------------
| Element ID | Length | Organization Identifier | Type | Reserved | More data |Version |    Body    |
-----------------------------------------------------------------------------------------------------
                                                        7~5 bits |  1 bit  |3~0 bits
    1 byte    1 byte            3 bytes        1 byte            1 byte                0-250 bytes
 
    Element ID: The Element ID field is set to the value (221), indicating the vendor-specific element.
 
    Length: The length is the total length of Organization Identifier, Type, Version and Body, the maximum value is 255.
 
    Organization Identifier: The Organization Identifier contains a unique identifier (0x18fe34), which is the first three bytes of MAC address applied by Espressif.
 
    Type: The Type field is set to the value (4) indicating ESP-NOW.
 
    Version: The Version field is set to the version of ESP-NOW.
 
    Body: The Body contains the actual ESP-NOW data to be transmitted.
 
As ESP-NOW is connectionless, the MAC header is a little different from that of standard frames. The FromDS and ToDS bits of FrameControl field are both 0. The first address field is set to the destination address. The second address field is set to the source address. The third address field is set to broadcast address (0xff:0xff:0xff:0xff:0xff:0xff).
 
=== Security===
 
ESP-NOW uses the CCMP method, which is described in IEEE Std. 802.11-2012, to protect the vendor-specific action frame. The Wi-Fi device maintains a Primary Master Key (PMK) and several Local Master Keys (LMKs, each paired device has one LMK). The lengths of both PMK and LMK are 16 bytes.
 
        PMK is used to encrypt LMK with the AES-128 algorithm. Call esp_now_set_pmk() to set PMK. If PMK is not set, a default PMK will be used.
 
        LMK of the paired device is used to encrypt the vendor-specific action frame with the CCMP method. If the LMK of the paired device is not set, the vendor-specific action frame will not be encrypted.
 
Encrypting multicast vendor-specific action frame is not supported.
 
=== Initialization and Deinitialization===
 
Call esp_now_init() to initialize ESP-NOW and esp_now_deinit() to de-initialize ESP-NOW. ESP-NOW data must be transmitted after Wi-Fi is started, so it is recommended to start Wi-Fi before initializing ESP-NOW and stop Wi-Fi after de-initializing ESP-NOW.
 
When esp_now_deinit() is called, all of the information of paired devices are deleted.
 
=== Add Paired Device===
 
Call esp_now_add_peer() to add the device to the paired device list before you send data to this device. If security is enabled, the LMK must be set. A device with a broadcast MAC address must be added before sending broadcast data.
 
You can send ESP-NOW data via both the Station and the SoftAP interface. Make sure that the interface is enabled before sending ESP-NOW data.
 
The range of the channel of paired devices is from 0 to 14. If the channel is set to 0, data will be sent on the current channel. Otherwise, the channel must be set as the channel that the local device is on.
 
For the receiving device, calling esp_now_add_peer() is not required. If no paired device is added, it can only receive broadcast packets and unencrypted unicast packets. To receive encrypted unicast packets, a paired device must be added, and the same LMK must be set.
 
The maximum number of paired devices is 20, and the paired encryption devices are no more than 17, the default is 7. If you want to change the number of paired encryption devices, set CONFIG_ESP_WIFI_ESPNOW_MAX_ENCRYPT_NUM in the Wi-Fi component configuration menu.
 
=== Send ESP-NOW Data===
 
Call esp_now_send() to send ESP-NOW data and esp_now_register_send_cb() to register sending callback function. It will return ESP_NOW_SEND_SUCCESS in sending callback function if the data is received successfully on the MAC layer. Otherwise, it will return ESP_NOW_SEND_FAIL. Several reasons can lead to ESP-NOW fails to send data. For example, the destination device does not exist; the channels of the devices are not the same; the action frame is lost when transmitting on the air, etc. It is not guaranteed that application layer can receive the data. If necessary, send back ack data when receiving ESP-NOW data. If receiving ack data timeouts, retransmit the ESP-NOW data. A sequence number can also be assigned to ESP-NOW data to drop the duplicate data.
 
If there is a lot of ESP-NOW data to send, call esp_now_send() to send less than or equal to the maximum packet length (v1.0 is 250 bytes, v2.0 is 1470 bytes) of data once a time. Note that too short interval between sending two ESP-NOW data may lead to disorder of sending callback function. So, it is recommended that sending the next ESP-NOW data after the sending callback function of the previous sending has returned. The sending callback function runs from a high-priority Wi-Fi task. So, do not do lengthy operations in the callback function. Instead, post the necessary data to a queue and handle it from a lower priority task.
 
=== Receiving ESP-NOW Data===
 
Call esp_now_register_recv_cb() to register receiving callback function. Call the receiving callback function when receiving ESP-NOW. The receiving callback function also runs from the Wi-Fi task. So, do not do lengthy operations in the callback function. Instead, post the necessary data to a queue and handle it from a lower priority task.
 
=== Config ESP-NOW Rate===
 
Call esp_now_set_peer_rate_config() to configure ESP-NOW rate of each peer. Make sure that the peer is added before configuring the rate. This API should be called after esp_wifi_start() and esp_now_add_peer().
 
=== Config ESP-NOW Power-saving Parameter===
 
Sleep is supported only when ESP32 is configured as station.
 
Call esp_now_set_wake_window() to configure Window for ESP-NOW RX at sleep. The default value is the maximum, which allowing RX all the time.
 
If Power-saving is needed for ESP-NOW, call esp_wifi_connectionless_module_set_wake_interval() to configure Interval as well.
 
Please refer to connectionless module power save to get more detail.


== Was ist ESP-Now==
== Was ist ESP-Now==
Zeile 129: Zeile 13:
* [[ESP-Now Master-Client Kommunikation]]
* [[ESP-Now Master-Client Kommunikation]]


 
== [[ESP-Now - Der erste Versuch]]==
 
== Der erste Versuch==
 
=== Hardware===
Für die ersten Versuche habe ich einen ESP32-C3-SuperMini als Master und 2 ESP32-C3-SuperMini mit 0,42"-Display als Client gewählt.
 
Bild
 
=== Der Umgang mit der MAC-Adresse===
Die Handhabung der MAC-Adresse in Micropython erschließt sich von selbst. Sie wird intern als Bytestring aus 6 Hexwerten daegestellt:
<pre>
b'\x01 \x02 \x03 \x04 \x05 \x06'
</pre>
Wenn dieser Bytestring mit print ausgegeben wird, werden die Hexwerte gemäß UTF8 in Charakter umgewandelt. Das sieht dann sehr verwirrend aus. Deshalb habe ich ein kleines Modul '''mac_tools.py''' geschrieben, dass u.a. die Umwandlung des Bytestrings in einen druckbaren String und umgekehrt übernimmt.
<pre>
# mac_tools.py
 
# Die MAC-Adresse wird als Bytestring dargestellt:
# b'\x01 \x02 \x03 \x04 \x05 \x06'
# Also 6 Hexwerte, die bei einer Print-Ausgabe aber fehlinterpretiert werden.
 
# V.0.01
# date: 24.09.2025
 
 
from machine import Pin, I2C, ADC
import ssd1306
import gc
import network
import espnow
import time
import framebuf
import freesans20
import writer
import esp32
import ubinascii
 
 
def mac_save():
    '''Sichert die MAC-Adresse in der Datei mac_adr.txt'''
    mac_str = mac2str(get_mac())
    print(mac_str)
    with open('mac_adr.txt','w') as file:
        file.write(mac_str)
 
def str2mac(mac_str):
    '''Gibt die Stringdarstellung als MAC-Adresse zurück'''   
    # Entfernt Doppelpunkte, wandelt Hex in Bytes
    mac_str = mac_str.replace(":", "")
    return ubinascii.unhexlify(mac_str)
 
def mac2str(mac):
    '''Wandelt eine MAC-Adresse in eine Stringdarstellung'''
    return ubinascii.hexlify(mac, ":").decode().upper()
 
def get_mac():
    '''Gibt die MAC-Adresse zurück'''
    sta = network.WLAN(network.STA_IF)
    sta.active(True)
    return sta.config('mac')
 
def send_mac(espnow_instanz, dest_mac):
    '''Schickt die eigene MAC-Adresse an dest_mac.
      Damit kann sich ein Client beim Master anmelden.
    '''
    pass
 
</pre>
Noch ist das Modul nicht vollständig.
 
=== Die Empfänger Software===
 
 
<pre>
# espnow_rx_001.py
 
# Testprogramm zum Empfang von Nachrichten mit ESP-Now.
 
# Autor: Peter Stöck
# Datum: 24.09.2025
 
 
from machine import Pin, I2C, ADC
import ssd1306
import gc
import network
import espnow
import time
import framebuf
import freesans20
import writer
import esp32
import ubinascii
 
# Konstanten definieren
Disp_SCL = const(6)
Disp_SDA = const(5)
 
SCL = const(9)
SDA = const(8)
 
# I2C für Display einrichten
i2c = I2C(0, scl=Pin(Disp_SCL), sda=Pin(Disp_SDA))
oled = ssd1306.SSD1306_I2C(72, 40, i2c)
 
# Display für unterschiedliche Fonts vorbereiten
wri = writer.Writer(oled, freesans20)
 
# Wlan Engine einrichten
sta = network.WLAN(network.STA_IF)
sta.active(True)
mac = sta.config('mac')
# eigene MAC-Adresse ausgeben
print(ubinascii.hexlify(mac, ":").decode().upper())
 
# ESP-Now einrichten
e = espnow.ESPNow()
e.active(True)
 
# Startmeldung ausgeben
oled.fill(0)
oled.text("ESP-Now", 0, 0)
oled.show()
 
# Auf ESP-Now Message warten
while True:
    host, msg = e.recv()
    if msg:
        oled.fill(0)
        oled.text(msg, 0, 0)
        oled.show()
 
</pre>
 
=== Die Sender Software===
 
=== Die Peers Liste verwalten ===
Um Nachrichten an Peers versenden zu können muss deren MAC-Adresse der ESP-Now-Instanz bekannt sein. Dazu wird deren MAC-Adresse mit <code>e.add_peer(peer_mac)</code> an die ESP-Now-Instanz übergeben.
 
Probleme gibt es wohl mit der '''Brodcast-Adresse''' (BC) <code>b'\xff'*6</code>. Chatgpt meint, dass die '''BC''' nicht bekanntgemacht werden muss oder sogar darf. Bei meinem Tests mit einem '''ESP32-C3-SuperMini''' war das aber erforderlich.
 
Ich habe zuerst die Liste <code>peers</code> mit dem Eintrag für '''BC''' erstellt und diese Liste mit:
<pre>
for peer in peers:
    e.add_peer(peer)
</pre>
an <code>e</code> übergeben.
 
Der Versuch später mit <code>e.add_peer()</code> einen weiteren Peer bekannt zu machen führte zu einer Fehlermeldung.
 
==== Lösung ====
Wenn ein neuer Peer hinzugefügt werden soll, muss dessen MAC-Adresse erst in <code>peers</code> eingetragen werden. Dann wird die '''ESP-Now-Instanz deaktiviert''', das löscht die bekannten Peers. Nachdem die '''ESP-Now-Instanz''' wieder '''aktiviert''' ist, kann die komplette erweiterte <code>peers</code> Liste wieder in der Schleife übergeben werden.
 
<pre>
def new_peer_list(new_peer):
    global peers
    peers.append(new_peer)
    e.active(False)
    e.active(True)
    for peer in peers:
        e.add_peer(peer)
</pre>
 
Das funktioniert.
 
Gemäß '''Chatgpt''' soll es sich dabei um einen '''Bug''' im Micropython für den '''ESP32-C3''' handeln.
 




== Navigation==
== Navigation==
[[Hauptseite| Zurück zur Hauptseite]]
[[Hauptseite| Zurück zur Hauptseite]]

Aktuelle Version vom 9. September 2026, 18:25 Uhr

Für mein ESP32 Klingel Projekt will ich ESP-Now einsetzen. Deshalb muss ich mich damit vertraut machen.

Ich habe vor längerer Zeit schon mal mit ESP-Now auf M5Stack-Geräten herumgespielt. Davon ist aber nichts mehr präsent. Gute Informationen zu ESP-Now gibt es hier: https://randomnerdtutorials.com/?s=ESP-NOW


Was ist ESP-Now

[Bearbeiten]
[Bearbeiten]

Zurück zur Hauptseite